path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/com/ginsberg/advent2019/Day16.kt
tginsberg
222,116,116
false
null
/* * Copyright (c) 2019 by <NAME> */ /** * Advent of Code 2019, Day 16 - Flawed Frequency Transmission * Problem Description: http://adventofcode.com/2019/day/16 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day16/ */ package com.ginsberg.advent2019 import kotlin.math.absoluteValue class Day16(private val input: String) { private val signal: IntArray = input.map { Character.getNumericValue(it) }.toIntArray() fun solvePart1(phases: Int = 100): String = (1..phases).fold(signal) { carry, _ -> phase(carry) }.joinToString(separator = "").take(8) fun solvePart2(phases: Int = 100): String { val offset = input.take(7).toInt() val stretchedInput = (offset until 10_000 * input.length).map { signal[it % input.length] }.toIntArray() repeat(phases) { stretchedInput.indices.reversed().fold(0) { carry, idx -> (stretchedInput[idx] + carry).lastDigit().also { stretchedInput[idx] = it } } } return stretchedInput.take(8).joinToString(separator = "") } private fun phase(input: IntArray): IntArray = (1..input.size).map { element -> val cycle: IntArray = base.cycle(element, input.size) input.mapIndexed { index, inputElement -> (inputElement * cycle[index]) }.sum().lastDigit() }.toIntArray() private fun Int.lastDigit(): Int = (this % 10).absoluteValue private fun IntArray.cycle(perCycle: Int, length: Int): IntArray = (0..length / perCycle).flatMap { idx -> List(perCycle) { this[idx % this.size] } }.drop(1).toIntArray() companion object { val base: IntArray = intArrayOf(0, 1, 0, -1) } }
0
Kotlin
2
23
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
1,749
advent-2019-kotlin
Apache License 2.0
src/Day08.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
fun main() { tailrec fun isVisible( grid: Array<Array<Int>>, rowIndex: Int, columnIndex: Int, treeHeight: Int, xDirection: Int, yDirection: Int ): Boolean { require(xDirection != 0 || yDirection != 0) { "Only one direction can be used" } val rowIndexToConsider = rowIndex + xDirection val columnIndexToConsider = columnIndex + yDirection fun isOutsideGrid(): Boolean { return rowIndexToConsider < 0 || rowIndexToConsider >= grid[0].size || columnIndexToConsider < 0 || columnIndexToConsider >= grid.size } return if (isOutsideGrid()) { true } else { val adjacentHeight = grid[rowIndexToConsider][columnIndexToConsider] if (treeHeight <= adjacentHeight) { false } else { isVisible(grid, rowIndexToConsider, columnIndexToConsider, treeHeight, xDirection, yDirection) } } } tailrec fun countVisibleTrees( grid: Array<Array<Int>>, rowIndex: Int, columnIndex: Int, treeHeight: Int, xDirection: Int, yDirection: Int, visitedTrees: Int = 0 ): Int { require(xDirection != 0 || yDirection != 0) { "Only one direction can be used" } val rowIndexToConsider = rowIndex + xDirection val columnIndexToConsider = columnIndex + yDirection fun isOutsideGrid(): Boolean { return rowIndexToConsider < 0 || rowIndexToConsider >= grid[0].size || columnIndexToConsider < 0 || columnIndexToConsider >= grid.size } return if (isOutsideGrid()) { visitedTrees } else { val adjacentHeight = grid[rowIndexToConsider][columnIndexToConsider] if (treeHeight <= adjacentHeight) { visitedTrees + 1 } else { countVisibleTrees(grid, rowIndexToConsider, columnIndexToConsider, treeHeight, xDirection, yDirection, visitedTrees + 1) } } } fun part1(input: List<String>): Int { val height = input.size val width = input[0].length val treeGrid: Array<Array<Int>> = Array(height) { Array(width) { 0 } } input.forEachIndexed { rowIndex, rowData -> rowData.map { it.digitToInt() }.forEachIndexed { columnIndex, height -> treeGrid[rowIndex][columnIndex] = height } } var amountOfVisibleTrees = 0 treeGrid.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, height -> val isVisibleLeft = isVisible(treeGrid, rowIndex, columnIndex, height, -1, 0) val isVisibleRight = isVisible(treeGrid, rowIndex, columnIndex, height, 1, 0) val isVisibleTop = isVisible(treeGrid, rowIndex, columnIndex, height, 0, -1) val isVisibleBottom = isVisible(treeGrid, rowIndex, columnIndex, height, 0, 1) if (isVisibleLeft || isVisibleRight || isVisibleTop || isVisibleBottom) { amountOfVisibleTrees++ } } } return amountOfVisibleTrees } fun part2(input: List<String>): Int { val height = input.size val width = input[0].length val treeGrid: Array<Array<Int>> = Array(height) { Array(width) { 0 } } input.forEachIndexed { rowIndex, rowData -> rowData.map { it.digitToInt() }.forEachIndexed { columnIndex, height -> treeGrid[rowIndex][columnIndex] = height } } var maxScore = 0 treeGrid.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, height -> val scoreLeft = countVisibleTrees(treeGrid, rowIndex, columnIndex, height, -1, 0) val scoreRight = countVisibleTrees(treeGrid, rowIndex, columnIndex, height, 1, 0) val scoreTop = countVisibleTrees(treeGrid, rowIndex, columnIndex, height, 0, -1) val scoreBottom = countVisibleTrees(treeGrid, rowIndex, columnIndex, height, 0, 1) val score = scoreLeft * scoreRight * scoreTop * scoreBottom maxScore = maxOf(score, maxScore) } } return maxScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
4,655
advent-of-code-2022-kotlin
Apache License 2.0
src/Tasks.kt
DmitrySwan
360,247,950
false
null
fun main() { println( repeatedIntersection(intArrayOf(3, 6, 7, 8, 7, 9), mutableListOf(12, 6, 7, 6, 7, 565)) ) println(countLetters("AAGGDDDFBBBAAABB")) println(groupWords(arrayOf("ate", "tdb", "eat", "ref", "fer", "test"))) } fun repeatedIntersection(array1: IntArray, array2: MutableList<Int>): List<Int> { return array1 .filter { e -> array2.remove(e) } } fun countLetters(input: String): String { var i = 0 var count = 0 var result = "" for (letter in input) { count++ i++ if (i < input.length && letter == input[i]) { continue } result += "${input[i - 1]}$count" count = 0 } return result } fun groupWords(words: Array<String>): List<List<String>> { val map: MutableMap<String, MutableList<String>> = HashMap() for (word in words) { val sum: String = word.toCharArray().sorted().joinToString() map.getOrPut(sum) { mutableListOf() } .add(word) } return map.values.toList() }
0
Kotlin
0
0
83dbf8b060b34b5286fc9b0a013725a98ae36960
1,066
KotlinEducation
MIT License
src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day03.kt
rafaeltoledo
726,542,427
false
{"Kotlin": 11895}
package net.rafaeltoledo.kotlin.advent class Day03 { fun invoke(input: List<String>): Int { val positioning = input.toPositioning() return positioning.filter { it.checkBoundaries(input) }.sumOf { it.number } } fun invoke2(input: List<String>): Int { val positioning = input.toPositioning() return positioning .map { it.fillAsteriskData(input) } .filter { it.symbolPosition != null } .groupBy { it.symbolPosition } .filter { it.value.size >= 2 } .map { it.value.first().number * it.value.last().number } .sum() } fun NumberPositioning.checkBoundaries(input: List<String>): Boolean { val lines = listOf(this.start.first - 1, this.start.first, this.start.first + 1).filter { it >= 0 }.filter { it <= input.size - 1 } val range = ((start.second - 1)..(end.second + 1)).toList().filter { it >= 0 }.filter { it <= input.first().length - 1 } lines.forEach { line -> range.forEach { column -> if (input.get(line).get(column).isValid()) { return true } } } return false } fun NumberPositioning.fillAsteriskData(input: List<String>): NumberPositioning { val lines = listOf(this.start.first - 1, this.start.first, this.start.first + 1).filter { it >= 0 }.filter { it <= input.size - 1 } val range = ((start.second - 1)..(end.second + 1)).toList().filter { it >= 0 }.filter { it <= input.first().length - 1 } lines.forEach { line -> range.forEach { column -> if (input.get(line).get(column).isAsterisk()) { return this.copy( symbolPosition = Pair(line, column), ) } } } return this } } fun NumberPositioning.prettyPrint(input: List<String>) { val lines = listOf(this.start.first - 1, this.start.first, this.start.first + 1).filter { it >= 0 }.filter { it <= input.size - 1 } val range = ((start.second - 1)..(end.second + 1)).toList().filter { it >= 0 }.filter { it <= input.first().length - 1 } lines.forEach { line -> range.forEach { column -> print(input.get(line).get(column)) } println() } println() } private fun Char.isValid(): Boolean { return (!isDigit() && this != '.') } private fun Char.isAsterisk(): Boolean { return this == '*' } private fun List<String>.toPositioning(): List<NumberPositioning> { val list = mutableListOf<NumberPositioning>() this.forEachIndexed { line, value -> var tempStr = "" var startIndex = -1 value.forEachIndexed { strIndex, char -> if (char.isDigit()) { tempStr += char if (startIndex == -1) { startIndex = strIndex } } else { if (tempStr.isNotEmpty()) { list.add(NumberPositioning(tempStr.toInt(), Pair(line, startIndex), Pair(line, strIndex - 1))) } tempStr = "" startIndex = -1 } } if (tempStr.isNotEmpty()) { list.add(NumberPositioning(tempStr.toInt(), Pair(line, startIndex), Pair(line, value.length - 1))) } } return list.toList() } data class NumberPositioning( val number: Int, val start: Pair<Int, Int>, val end: Pair<Int, Int>, var symbolPosition: Pair<Int, Int>? = null, )
0
Kotlin
0
0
7bee985147466cd796e0183d7c719ca6d01b5908
3,215
aoc2023
Apache License 2.0
src/main/kotlin/dk/lessor/Day5.kt
aoc-team-1
317,571,356
false
{"Java": 70687, "Kotlin": 34171}
package dk.lessor fun main() { val lines = readFile("day_5.txt") val b = lines.map(BoardingPass.Companion::parse).sortedBy { it.id } println(b.last().id) println(findId(b)) } fun findId(boardingPasses: List<BoardingPass>): Int { for ((index, bp) in boardingPasses.withIndex()) { if (index == 0) continue val last = boardingPasses[index - 1] if (last.id + 1 != bp.id) return last.id + 1 } return 0 } data class BoardingPass( val row: Int, val column: Int, ) { val id: Int get() = row * 8 + column companion object { fun parse(input: String): BoardingPass { val row = traverseRows(input.take(7)) val column = traverseColumn(input.drop(7)) return BoardingPass(row, column) } private fun traverseRows(rows: String): Int { return traverse(rows, 'F', (0..127)) } private fun traverseColumn(columns: String): Int { return traverse(columns, 'L', (0..7)) } private fun traverse(path: String, check: Char, range: IntRange): Int { if (path.isEmpty()) { return range.first } val split = (range.last - range.first) / 2 val newRange = if (path.first() == check) { (range.first..range.first + split) } else { (range.first + split + 1..range.last) } return traverse(path.drop(1), check, newRange) } } }
0
Java
0
0
48ea750b60a6a2a92f9048c04971b1dc340780d5
1,535
lessor-aoc-comp-2020
MIT License
app/src/main/kotlin/com/resurtm/aoc2023/day05/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day05 /** * See the README.md file for more details on this one. */ fun launchDay05(testCase: String) { val env = readEnv(testCase) println("Day 05, part 01: ${solvePart1(env)}") println("Day 05, part 02: ${solvePart2(env)}") } /** * See the README.md file for more details on this one. */ private fun solvePart2(env: Env): Long? { var min: Long? = null for (rawPair in env.seedsV2) { for (raw in rawPair.first..<rawPair.first + rawPair.second) { var seed = raw for (trans in env.trans) { seed = doTrans(seed, trans) } if (min == null || min > seed) { min = seed } } } return min } private fun solvePart1(env: Env): Long? { var min: Long? = null for (raw in env.seeds) { var seed = raw for (trans in env.trans) { seed = doTrans(seed, trans) } if (min == null || min > seed) { min = seed } } return min } private fun doTrans(seed: Long, trans: List<TransItem>): Long { for (tr in trans) { if (seed in tr.src..<tr.src + tr.len) { return seed + (tr.dst - tr.src) } } return seed } private fun readEnv(testCase: String): Env { val rawReader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() val reader = rawReader ?: throw Exception("Cannot read the input") val seeds = mutableListOf<Long>() val trans = mutableListOf<List<TransItem>>() var transItem = mutableListOf<TransItem>() var readMap = false while (true) { val line = reader.readLine() ?: break if (readMap) { if (line.isEmpty()) { trans.add(transItem) transItem = mutableListOf() readMap = false continue } val raw = line.split(" ").map { it.trim() }.filter { it.isNotEmpty() }.map { it.toLong() } transItem.add(TransItem(dst = raw[0], src = raw[1], len = raw[2])) continue } if (line.contains("seeds: ")) { seeds.addAll(line.split(":")[1].trim().split(" ").map { it.trim() }.filter { it.isNotEmpty() } .map { it.toLong() }) continue } if (line.contains(" map:")) { readMap = true continue } } if (transItem.isNotEmpty()) { trans.add(transItem) } val seedsV2 = seeds.chunked(2).map { Pair(it[0], it[1]) } return Env(seeds = seeds, seedsV2 = seedsV2, trans = trans) } private data class Env(val seeds: List<Long>, val seedsV2: List<Pair<Long, Long>>, val trans: List<List<TransItem>>) private data class TransItem(val dst: Long, val src: Long, val len: Long)
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
2,836
advent-of-code-2023
MIT License
src/Day07.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 07 - No Space Left On Device // https://adventofcode.com/2022/day/7 fun main() { class File( val name: String, val size: Int ) class Directory( val name: String = "", val root: Directory? = null, val parent: Directory? = null, val dirs: MutableMap<String, Directory> = mutableMapOf(), val files: MutableMap<String, File> = mutableMapOf() ) { fun cd(dir: String): Directory? = when (dir) { "/" -> root ?: this ".." -> parent ?: this else -> dirs[dir] } fun mkdir(dir: String): Directory = dirs.getOrPut(dir) { Directory(dir, root, this) } fun size(): Int = dirs.values.sumOf { it.size() } + files.values.sumOf { it.size } } fun parse(input: List<String>): List<Directory> { val root = Directory() var current = root val all = mutableListOf(root) for (line in input) { val parts = line.split(' ') when (parts[0]) { "$" -> when (parts[1]) { "cd" -> current = current.cd(parts[2]) ?: error("Invalid command: $line") "ls" -> Unit // nothing to do else -> error("Invalid command: $line") } "dir" -> current.mkdir(parts[1]).also(all::add) else -> current.files[parts[1]] = File(parts[1], parts[0].toInt()) } } return all } fun part1(input: List<String>): Int { return parse(input) .filter { it.size() <= 100000 } .sumOf { it.size() } } fun part2(input: List<String>): Int { val fs = parse(input) val need = 30000000 - (70000000 - fs[0].size()) return fs .sortedBy { it.size() } .first {it.size() >= need } .size() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) println(part2(input)) } /* --- Day 7: No Space Left On Device --- You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway? The device the Elves gave you has problems with more than just its communication system. You try to run a system update: $ system-update --please --pretty-please-with-sugar-on-top Error: No space left on device Perhaps you can delete some files to make space for the update? You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example: $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in. Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers: cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument: cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory. cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory. cd / switches the current directory to the outermost directory, /. ls means list. It prints out all of the files and directories immediately contained by the current directory: 123 abc means that the current directory contains a file named abc with size 123. dir xyz means that the current directory contains a directory named xyz. Given the commands and output in the example above, you can determine that the filesystem looks visually like this: - / (dir) - a (dir) - e (dir) - i (file, size=584) - f (file, size=29116) - g (file, size=2557) - h.lst (file, size=62596) - b.txt (file, size=14848514) - c.dat (file, size=8504156) - d (dir) - j (file, size=4060174) - d.log (file, size=8033020) - d.ext (file, size=5626152) - k (file, size=7214296) Here, there are four directories: / (the outermost directory), a and d (which are in /), and e (which is in a). These directories also contain files of various sizes. Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.) The total sizes of the directories above can be found as follows: The total size of directory e is 584 because it contains a single file i of size 584 and no other directories. The directory a has total size 94853 because it contains files f (size 29116), g (size 2557), and h.lst (size 62596), plus file i indirectly (a contains e which contains i). Directory d has total size 24933642. As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file. To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a and e; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!) Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories? Your puzzle answer was 1611443. --- Part Two --- Now, you're ready to choose a directory to delete. The total disk space available to the filesystem is 70000000. To run the update, you need unused space of at least 30000000. You need to find a directory you can delete that will free up enough space to run the update. In the example above, the total size of the outermost directory (and thus the total amount of used space) is 48381165; this means that the size of the unused space must currently be 21618835, which isn't quite the 30000000 required by the update. Therefore, the update still requires a directory with total size of at least 8381165 to be deleted before it can run. To achieve this, you have the following options: Delete directory e, which would increase unused space by 584. Delete directory a, which would increase unused space by 94853. Delete directory d, which would increase unused space by 24933642. Delete directory /, which would increase unused space by 48381165. Directories e and a are both too small; deleting them would not free up enough space. However, directories d and / are both big enough! Between these, choose the smallest: d, increasing unused space by 24933642. Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory? Your puzzle answer was 2086088. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
7,588
aoc-2022-in-kotlin
Apache License 2.0
kotlin/misc/TernarySearch.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package misc import java.util.Random // https://en.wikipedia.org/wiki/Ternary_search // Finds the smallest i in [a, b] that maximizes f(i), assuming that f(a) < ... < f(i) ≥ ··· ≥ f(b) object TernarySearch { fun ternarySearch(f: IntUnaryOperator, fromInclusive: Int, toInclusive: Int): Int { var lo = fromInclusive - 1 var hi = toInclusive while (hi - lo > 1) { val mid = lo + hi ushr 1 if (f.applyAsInt(mid) < f.applyAsInt(mid + 1)) { lo = mid } else { hi = mid } } return hi } fun ternarySearch2(f: IntUnaryOperator, fromInclusive: Int, toInclusive: Int): Int { var lo = fromInclusive var hi = toInclusive while (hi > lo + 2) { val m1 = lo + (hi - lo) / 3 val m2 = hi - (hi - lo) / 3 if (f.applyAsInt(m1) < f.applyAsInt(m2)) lo = m1 else hi = m2 } var res = lo for (i in lo + 1..hi) if (f.applyAsInt(res) < f.applyAsInt(i)) res = i return res } fun ternarySearchDouble(f: DoubleUnaryOperator, lo: Double, hi: Double): Double { var lo = lo var hi = hi for (step in 0..999) { val m1 = lo + (hi - lo) / 3 val m2 = hi - (hi - lo) / 3 if (f.applyAsDouble(m1) < f.applyAsDouble(m2)) lo = m1 else hi = m2 } return (lo + hi) / 2 } // random tests fun main(args: Array<String?>?) { System.out.println(ternarySearchDouble(DoubleUnaryOperator { x -> -(x - 2) * (x - 2) }, -10.0, 10.0)) val rnd = Random(1) for (step in 0..9999) { val n: Int = rnd.nextInt(20) + 1 val p: Int = rnd.nextInt(n) val a = IntArray(n) val range = 10 a[p] = rnd.nextInt(range) for (i in p - 1 downTo 0) a[i] = a[i + 1] - rnd.nextInt(range) - 1 for (i in p + 1 until n) a[i] = a[i - 1] - rnd.nextInt(range) val res = ternarySearch(IntUnaryOperator { i -> a[i] }, 0, a.size - 1) val res2 = ternarySearch2(IntUnaryOperator { i -> a[i] }, 0, a.size - 1) if (p != res || p != res2) throw RuntimeException() } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,262
codelibrary
The Unlicense
src/main/kotlin/days/Day4.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days import days.Day4Util.toRange class Day4 : Day(4) { override fun partOne(): Any { return inputList .map { line -> val (firstRangeString, secondRangeString) = line.split(",") val firstRange = toRange(firstRangeString) val secondRange = toRange(secondRangeString) if (firstRange.fullyContains(secondRange) || secondRange.fullyContains(firstRange)) { 1 } else { 0 } }.sum() } override fun partTwo(): Any { return inputList .map { line -> val (firstRangeString, secondRangeString) = line.split(",") val firstRange = toRange(firstRangeString) val secondRange = toRange(secondRangeString) if (firstRange.hasOverlap(secondRange)) { 1 } else { 0 } }.sum() } } private fun IntRange.hasOverlap(secondRange: IntRange): Boolean { // N^2 complexity, but let's try it return this.any { firstRangeElement -> secondRange.contains(firstRangeElement) } } private fun IntRange.fullyContains(secondRange: IntRange): Boolean { return this.first <= secondRange.first && secondRange.last <= this.last } object Day4Util { fun toRange(s: String): IntRange { val (from, to) = s.split("-") return IntRange(from.toInt(), to.toInt()) } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
1,529
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day2.kt
maldoinc
726,264,110
false
{"Kotlin": 14472}
import java.io.File data class DeckSize(val red: Int, val green: Int, val blue: Int) fun getColorValues(draw: String, color: String): Sequence<Int> = Regex("(\\d+) $color").findAll(draw).map { it.groupValues[1].toInt() } fun getColorSum(draw: String, color: String): Int = getColorValues(draw, color).sum() fun getLargestColor(draw: String, color: String): Int = getColorValues(draw, color).max() fun isGamePossible(game: String, deckSize: DeckSize): Boolean = game.split(';').firstOrNull { getColorSum(it, "red") > deckSize.red || getColorSum(it, "green") > deckSize.green || getColorSum(it, "blue") > deckSize.blue } == null fun findLargestDrawSize(draws: String): DeckSize = DeckSize( red = getLargestColor(draws, "red"), green = getLargestColor(draws, "green"), blue = getLargestColor(draws, "blue") ) fun main(args: Array<String>) { val deck = DeckSize(red = 12, green = 13, blue = 14) val part1 = File(args[0]) .readLines() .map { it.substring(5) } .map { it.split(':') } .filter { isGamePossible(it[1], deck) } .sumOf { it[0].toInt() } val part2 = File(args[0]) .readLines() .map { findLargestDrawSize(it) } .sumOf { it.red * it.green * it.blue } println("Part1: $part1") println("Part2: $part2") }
0
Kotlin
0
1
47a1ab8185eb6cf16bc012f20af28a4a3fef2f47
1,439
advent-2023
MIT License
archive/328/solve.kt
daniellionel01
435,306,139
false
null
/* === #328 Lowest-cost Search - Project Euler === We are trying to find a hidden number selected from the set of integers {1, 2, ..., n} by asking questions. Each number (question) we ask, has a cost equal to the number asked and we get one of three possible answers: "Your guess is lower than the hidden number", or "Yes, that's it!", or "Your guess is higher than the hidden number". Given the value of n, an optimal strategy minimizes the total cost (i.e. the sum of all the questions asked) for the worst possible case. E.g. If n=3, the best we can do is obviously to ask the number "2". The answer will immediately lead us to find the hidden number (at a total cost = 2). If n=8, we might decide to use a "binary search" type of strategy: Our first question would be "4" and if the hidden number is higher than 4 we will need one or two additional questions. Let our second question be "6". If the hidden number is still higher than 6, we will need a third question in order to discriminate between 7 and 8. Thus, our third question will be "7" and the total cost for this worst-case scenario will be 4+6+7=17. We can improve considerably the worst-case cost for n=8, by asking "5" as our first question. If we are told that the hidden number is higher than 5, our second question will be "7", then we'll know for certain what the hidden number is (for a total cost of 5+7=12). If we are told that the hidden number is lower than 5, our second question will be "3" and if the hidden number is lower than 3 our third question will be "1", giving a total cost of 5+3+1=9. Since 12>9, the worst-case cost for this strategy is 12. That's better than what we achieved previously with the "binary search" strategy; it is also better than or equal to any other strategy. So, in fact, we have just described an optimal strategy for n=8. Let C(n) be the worst-case cost achieved by an optimal strategy for n, as described above. Thus C(1) = 0, C(2) = 1, C(3) = 2 and C(8) = 12. Similarly, C(100) = 400 and $\sum \limits_{n = 1}^{100} {C(n)} = 17575$. Find $\sum \limits_{n = 1}^{200000} {C(n)}$ . Difficulty rating: 95% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
2,230
euler
MIT License
src/Day13.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
import java.io.File fun main() { fun parseInput(input: String): List<Pair<String, String>> { return input.split("\n\n").map { Pair(it.split("\n")[0], it.split("\n")[1]) } } fun parseSomething(input:MutableList<String>): Pair<MutableList<Any>, Int> { var res = mutableListOf<Any>() var index = 0 while (index < input.size) { if (input[index] == "["){ var (innerList, endIndex) = parseSomething(input.slice(index+1 until input.size).toMutableList()) res.add(innerList) index += endIndex+2 } else if (input[index] == "]") { return Pair(res, index) } else { res.add(input[index].toInt()) index ++ } } return Pair(res, index) } fun turnToList(input: String): MutableList<String>{ var testList = mutableListOf<String>() var index = 0 while (index < input.length) { if (input[index] == ',') index++ else if (input[index] in listOf(']', '[')) { testList.add(input[index].toString()); index++ } else { var number = input.substring(index) .takeWhile { it.isDigit() }; testList.add(number); index += number.length } } return testList } fun ifLess(left: ArrayList<*>, right: ArrayList<*>): Int{ var index = 0 var flag = 0 if ((left.size == 0)&&(right.size > 0)) flag = 1 if ((right.size == 0)&&(left.size > 0)) flag = -1 while ((index < minOf(left.size, right.size))&&(flag == 0)){ var it = Pair(left[index], right[index]) if ((it.first is Int)&&(it.second is Int)){ if ((it.first as Int) < (it.second as Int)) flag = 1 if ((it.first as Int) > (it.second as Int)) flag = -1 } if ((it.first is ArrayList<*>)&&(it.second is Int)) flag = ifLess(it.first as ArrayList<*>, arrayListOf(it.second)) if ((it.second is ArrayList<*>)&&(it.first is Int)) flag = ifLess(arrayListOf(it.first), it.second as ArrayList<*>) if ((it.first is ArrayList<*>)&&(it.second is ArrayList<*>)) flag = ifLess(it.first as ArrayList<*>, it.second as ArrayList<*>) index ++ } if ((left.size > right.size)&&(flag == 0)) flag = -1 if ((left.size < right.size)&&(flag == 0)) flag = 1 return flag } fun part1(input: String) { var res = 0 var listPairs = parseInput(input) listPairs.forEachIndexed { index, pair -> var leftList = parseSomething(turnToList(pair.first)).first[0] as List<Any> var rightList = parseSomething(turnToList(pair.second)).first[0] as List<Any> var flag = ifLess(leftList as ArrayList<*>, rightList as ArrayList<*>).coerceIn(0..1) res += (index+1)*flag } println(res) } fun part2(input: String) { var res = 0 var listPairs = parseInput(input) var divider1 = arrayListOf(arrayListOf(2)) as ArrayList<*> var divider2 = arrayListOf(arrayListOf(6)) as ArrayList<*> var allPackets = arrayListOf(divider1, divider2) listPairs.forEachIndexed { index, pair -> var leftList = parseSomething(turnToList(pair.first)).first[0] as List<Any> var rightList = parseSomething(turnToList(pair.second)).first[0] as List<Any> allPackets.add(leftList as ArrayList<*>) allPackets.add(rightList as ArrayList<*>) } val packetsComparator = Comparator{packet1: ArrayList<*>, packet2: ArrayList<*> -> ifLess(packet1, packet2)} val sortedPackets = allPackets.sortedWith(packetsComparator).reversed() println(sortedPackets.indexOf(divider1)) println(sortedPackets.indexOf(divider2)) println((sortedPackets.indexOf(divider1)+1)*(sortedPackets.indexOf(divider2)+1)) } // fun part2(input: List<String>){} // test if implementation meets criteria from the description, like: val textTest = File("src", "Day13_test.txt").readText() part1(textTest) part2(textTest) val text = File("src", "Day13.txt").readText() part1(text) part2(text) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
4,387
aoc22
Apache License 2.0
src/commonMain/kotlin/search/analysis.kt
jillesvangurp
271,782,317
false
null
package search import kotlin.math.min interface TextFilter { fun filter(text: String): String } class LowerCaseTextFilter : TextFilter { override fun filter(text: String): String { return text.lowercase() } } interface Tokenizer { fun tokenize(text: String): List<String> } class SplittingTokenizer : Tokenizer { val re = Regex("""\s+""", RegexOption.MULTILINE) override fun tokenize(text: String): List<String> { return re.split(text).filter { it.isNotBlank() }.toList() } } interface TokenFilter { fun filter(tokens: List<String>): List<String> } class NgramTokenFilter(val ngramSize: Int) : TokenFilter { override fun filter(tokens: List<String>): List<String> { val joined = tokens.joinToString("") return if(joined.isBlank()) listOf() else if (joined.length < ngramSize) { listOf(joined) } else { (0..joined.length - ngramSize).map { i -> joined.subSequence(i, i+ngramSize).toString() } }.distinct() } } class EdgeNgramsTokenFilter(val minLength:Int, val maxLength:Int): TokenFilter { override fun filter(tokens: List<String>): List<String> { return tokens.flatMap { token -> if(token.length<=minLength) listOf(token) else { (minLength..min(maxLength, token.length)).flatMap { length -> listOf( token.subSequence(0,length).toString(), token.subSequence(token.length-length,token.length).toString() ) } } }.distinct() } } class InterpunctionTextFilter : TextFilter { private val interpunctionRE = """[\\\]\['"!,.@#$%^&*()_+-={}|><`~±§?]""".toRegex() override fun filter(text: String): String { return interpunctionRE.replace(text, " ") } } class Analyzer( private val textFilters: List<TextFilter> = listOf(LowerCaseTextFilter(), InterpunctionTextFilter()), private val tokenizer: Tokenizer = SplittingTokenizer(), private val tokenFilter: List<TokenFilter> = emptyList() ) { fun analyze(text: String): List<String> { var filtered = text textFilters.forEach { filtered = it.filter(filtered) } var tokens = tokenizer.tokenize(filtered) tokenFilter.forEach { tokens = it.filter(tokens) } return tokens } }
0
Kotlin
1
4
0f4236bf891faa841c6e32fe37c9ab9d2e6ce7c5
2,468
querylight
MIT License
src/main/kotlin/days/Day02.kt
julia-kim
435,257,054
false
{"Kotlin": 15771}
package days import readInput fun main() { fun part1(input: List<String>): Int { // - forward X increases the horizontal position by X units. // - down X increases the depth by X units. // - up X decreases the depth by X units. var horizontalPosition = 0 var depth = 0 input.forEach { command -> val (direction, number) = command.split(" ") when (direction) { ("forward") -> horizontalPosition += number.toInt() ("down") -> depth += number.toInt() ("up") -> depth -= number.toInt() } } return horizontalPosition * depth } fun part2(input: List<String>): Int { // - down X increases your aim by X units. // - up X decreases your aim by X units. // - forward X does two things: // - It increases your horizontal position by X units. // - It increases your depth by your aim multiplied by X. var aim = 0 var horizontalPosition = 0 var depth = 0 input.forEach { command -> val (direction, number) = command.split(" ") when (direction) { ("forward") -> { horizontalPosition += number.toInt() depth += number.toInt() * aim } ("down") -> aim += number.toInt() ("up") -> aim -= number.toInt() } } return horizontalPosition * depth } val testInput = readInput("Day02_test") check(part1(testInput) == 150) check(part2(testInput) == 900) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5febe0d5b9464738f9a7523c0e1d21bd992b9302
1,833
advent-of-code-2021
Apache License 2.0
src/Day01.kt
petoS6
573,018,212
false
{"Kotlin": 14258}
fun main() { fun part1(input: List<String>): Int { return getSnackSum(input).max() } fun part2(input: List<String>): Int { return getSnackSum(input).sortedDescending().take(3).sum() } val testInput = readInput("Day01.txt") println(part1(testInput)) println(part2(testInput)) } private fun getSnackSum(input: List<String>) = input.chunkedByPredicate(String::isBlank).map { it.sumOf(String::toInt) } private fun <T> List<T>.chunkedByPredicate(predicate : (T) -> Boolean): List<List<T>> = buildList { this@chunkedByPredicate.fold(emptyList<T>()) { acc, value -> if (predicate(value).not()) { acc + value } else { add(acc) emptyList() } } }
0
Kotlin
0
0
40bd094155e664a89892400aaf8ba8505fdd1986
697
kotlin-aoc-2022
Apache License 2.0
src/main/kotlin/dfsbfs/특정_거리의_도시_찾기.kt
CokeLee777
614,704,937
false
null
package dfsbfs import java.util.* import kotlin.math.* fun main(){ val sc = Scanner(System.`in`) val n = sc.nextInt() //도시의 개수 val m = sc.nextInt() //도로의 개수 val k = sc.nextInt() //거리 정보 val x = sc.nextInt() //출발 도시의 번호 //최단거리 테이블 초기화 val distances = IntArray(n + 1) { 1e9.toInt() } //그래프 초기화 val graph = mutableListOf<MutableList<City>>() for(i in 0..n){ graph.add(mutableListOf()) } //그래프 입력받기 for(i in 0 until m){ val a = sc.nextInt() val b = sc.nextInt() graph[a].add(City(b, 1)) } fun dijkstra(start: Int){ val pq = PriorityQueue<City>() //시작 도시 큐에 삽입 pq.offer(City(start, 0)) distances[start] = 0 //큐가 빌 때까지 반복 while(!pq.isEmpty()){ val now = pq.poll() val cityNumber = now.number val distance = now.distance //이미 처리된 도시라면 무시 if(distances[cityNumber] < distance) continue //현재 도시와 연결되어있는 도시 방문 for(city in graph[cityNumber]){ val cost = distance + city.distance //거리가 더 가깝다면 if(cost < distances[city.number]){ pq.offer(City(city.number, cost)) distances[city.number] = cost } } } } //다익스트라 최단경로 알고리즘 수행 dijkstra(x) if(distances.count{ it == k } == 0) { println(-1) return } for(i in distances.indices){ if(distances[i] == k) println(i) } } data class City(val number: Int, val distance: Int): Comparable<City> { override fun compareTo(other: City): Int = this.distance - other.distance }
0
Kotlin
0
0
919d6231c87fe4ee7fda6c700099e212e8da833f
1,935
algorithm
MIT License
day03/src/Day03.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File import javax.xml.stream.events.Characters class Day03(path: String) { private val numbers = mutableListOf<String>() init { File(path).forEachLine { numbers.add(it) } } fun part1(): Int { var gamma = 0 var epsilon = 0 val sum = IntArray(numbers[0].length) numbers.forEach { number -> number.forEachIndexed { index, c -> sum[index] += Character.getNumericValue(c) } } sum.forEach { gamma = gamma shl 1 epsilon = epsilon shl 1 if (it >= numbers.size / 2) { // gamma gamma = gamma or 1 } else { // epsilon epsilon = epsilon or 1 } } return gamma * epsilon } fun part2(): Int { var o2 = 0 var co2 = 0 // o2 var candidates = numbers.toMutableList() var pos = 0 while (candidates.size > 1) { val ones = candidates.count { it[pos] == '1' } val zeroes = candidates.size - ones candidates = if (ones >= zeroes) { candidates.filter { it[pos] == '1' }.toMutableList() } else { candidates.filter { it[pos] == '0' }.toMutableList() } pos++ } candidates[0].forEach { o2 = o2 shl 1 o2 = o2 or Character.getNumericValue(it) } // co2 candidates = numbers.toMutableList() pos = 0 while (candidates.size > 1) { val zeroes = candidates.count { it[pos] == '0' } val ones = candidates.size - zeroes candidates = if (zeroes <= ones) { candidates.filter { it[pos] == '0' }.toMutableList() } else { candidates.filter { it[pos] == '1' }.toMutableList() } pos++ } candidates[0].forEach { co2 = co2 shl 1 co2 = co2 or Character.getNumericValue(it) } return o2 * co2 } } fun main(args: Array<String>) { val aoc = Day03("day03/input.txt") println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
2,274
aoc2021
Apache License 2.0
src/main/kotlin/days/Day4.kt
mstar95
317,305,289
false
null
package days import util.groupByEmpty class Day4 : Day(4) { override fun partOne(): Any { val props = getProps() val valid = props.filter { isValid(it.keys) } return valid.size } private fun getProps(): List<Map<Key, String>> { val groups = groupByEmpty(inputList) println(groups) println(groups.toString() == "[[eyr:1972 cid:100, hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926], [iyr:2019, hcl:#602927 eyr:1967 hgt:170cm, ecl:grn pid:012533040 byr:1946], [hcl:dab227 iyr:2012, ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277], [hgt:59cm ecl:zzz, eyr:2038 hcl:74454a iyr:2023, pid:3556412378 byr:2007], [pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980, hcl:#623a2f], [eyr:2029 ecl:blu cid:129 byr:1989, iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm], [hcl:#888785, hgt:164cm byr:2001 iyr:2015 cid:88, pid:545766238 ecl:hzl, eyr:2022], [iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719]]") val flatten = flatten(groups) val props = flatten.map { props(it) } return props } override fun partTwo(): Any { val props = getProps() val valid = props.filter { isValid(it.keys) } val result = valid.filter { validateValues(it) } return result.size } private fun flatten(groups: List<List<String>>): List<List<String>> { return groups.map { group -> group.flatMap { it.split(" ") } } } private fun props(input: List<String>): Map<Key, String> { return input.map { it.split(":") } .map { Key.valueOf(it[0]) to it[1] }.toMap() } private fun isValid(keys: Set<Key>): Boolean { if (keys.size == Key.values().size) { return true } if (keys.size == Key.values().size - 1 && !keys.contains(Key.cid)) { return true } return false } private fun validateValues(input: Map<Key, String>): Boolean { val debug = false if(debug == true) { val x = input.entries .map { it to validateEntry(it) } if(x.any{ !it.second }) { println(x) } return x.map { it.second }.all { it } } return input.entries.all { validateEntry(it) } } private fun validateEntry(entry: Map.Entry<Key, String>) = when (entry.key) { Key.byr -> entry.value.toInt().let { it in 1920..2002 } Key.iyr -> entry.value.toInt().let { it in 2010..2020 } Key.eyr -> entry.value.toInt().let { it in 2020..2030 } Key.hgt -> hgt(entry.value) Key.hcl -> hcl(entry.value) Key.ecl -> entry.value in listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") Key.pid -> pid(entry) Key.cid -> true } private fun pid(entry: Map.Entry<Key, String>) = entry.value.length == 9 && entry.value.all { it.isDigit() } private fun hgt(input: String): Boolean { return when(input.takeLast(2)) { "cm" -> input.dropLast(2).toInt().let { it in 150..193 } "in" -> input.dropLast(2).toInt().let { it in 59..76 } else -> false } } private fun hcl(input: String): Boolean { if (input[0].toString() == "#" ) { val rest = input.drop(1) if(rest.length == 6) { return rest.all { it.toString().matches(Regex("[0-9]|[a-f]")) } } } return false } } enum class Key { byr, iyr, eyr, hgt, hcl, ecl, pid, cid }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
3,574
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/ru/timakden/aoc/year2022/Day22.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2022.Day22.Facing.* import ru.timakden.aoc.year2022.Day22.Side.* import ru.timakden.aoc.year2022.Day22.Side.Companion.toSide /** * [Day 22: Monkey Map](https://adventofcode.com/2022/day/22). */ object Day22 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day22") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val delimiterIndex = input.indexOfFirst { it.isBlank() } val map = BoardMap(input.subList(0, delimiterIndex)) "\\d+|[LR]".toRegex().findAll(input[delimiterIndex + 1]).map { it.value }.forEach { when (it) { "L" -> map.turnCounterclockwise() "R" -> map.turnClockwise() else -> for (i in 0..<it.toInt()) if (!map.move()) break } } return map.password } fun part2(input: List<String>): Int { val delimiterIndex = input.indexOfFirst { it.isBlank() } val map = BoardMap(input.subList(0, delimiterIndex)) "\\d+|[LR]".toRegex().findAll(input[delimiterIndex + 1]).map { it.value }.forEach { when (it) { "L" -> map.turnCounterclockwise() "R" -> map.turnClockwise() else -> for (i in 0..<it.toInt()) if (!map.moveCube()) break } } return map.password } private data class BoardMap(val map: List<String>) { val height = map.size val width = map.maxOf { it.length } var position = Point(map.first().indexOfFirst { it == '.' }, 0) var facing = RIGHT private val allowedTiles = listOf('.', '#') fun turnClockwise() { facing = when (facing) { DOWN -> LEFT LEFT -> UP RIGHT -> DOWN UP -> RIGHT } } fun turnCounterclockwise() { facing = when (facing) { DOWN -> RIGHT LEFT -> DOWN RIGHT -> UP UP -> LEFT } } private fun wrap(): Point { when (facing) { DOWN -> { var row = position.y while (true) { if (row == 0) return Point(position.x, 0) map[row].getOrNull(position.x)?.let { if (it !in allowedTiles) return Point(position.x, row + 1) } ?: return Point(position.x, row + 1) row-- } } LEFT -> { var column = position.x while (true) { if (column == width - 1) return Point(width - 1, position.y) map[position.y].getOrNull(column)?.let { if (it !in allowedTiles) return Point(column - 1, position.y) } ?: return Point(column - 1, position.y) column++ } } RIGHT -> { var column = position.x while (true) { if (column == 0) return Point(0, position.y) map[position.y].getOrNull(column)?.let { if (it !in allowedTiles) return Point(column + 1, position.y) } ?: return Point(column + 1, position.y) column-- } } UP -> { var row = position.y while (true) { if (row == height - 1) return Point(position.x, height - 1) map[row].getOrNull(position.x)?.let { if (it !in allowedTiles) return Point(position.x, row - 1) } ?: return Point(position.x, row - 1) row++ } } } } fun wrapCube(): Pair<Point, Facing> { var nextFacing = facing val side = position.toSide() var nextPosition = position if (side == A && facing == UP) { nextFacing = RIGHT nextPosition = Point(0, 3 * 50 + position.x - 50) } else if (side == A && facing == LEFT) { nextFacing = RIGHT nextPosition = Point(0, 2 * 50 + (50 - position.y - 1)) } else if (side == B && facing == UP) { nextFacing = UP nextPosition = Point(position.x - 100, 199) } else if (side == B && facing == RIGHT) { nextFacing = LEFT nextPosition = Point(99, (50 - position.y) + 2 * 50 - 1) } else if (side == B && facing == DOWN) { nextFacing = LEFT nextPosition = Point(99, 50 + (position.x - 2 * 50)) } else if (side == C && facing == RIGHT) { nextFacing = UP nextPosition = Point((position.y - 50) + 2 * 50, 49) } else if (side == C && facing == LEFT) { nextFacing = DOWN nextPosition = Point(position.y - 50, 100) } else if (side == E && facing == LEFT) { nextFacing = RIGHT nextPosition = Point(50, 50 - (position.y - 2 * 50) - 1) } else if (side == E && facing == UP) { nextFacing = RIGHT nextPosition = Point(50, 50 + position.x) } else if (side == D && facing == DOWN) { nextFacing = LEFT nextPosition = Point(49, 3 * 50 + (position.x - 50)) } else if (side == D && facing == RIGHT) { nextFacing = LEFT nextPosition = Point(149, 50 - (position.y - 50 * 2) - 1) } else if (side == F && facing == RIGHT) { nextFacing = UP nextPosition = Point((position.y - 3 * 50) + 50, 149) } else if (side == F && facing == LEFT) { nextFacing = DOWN nextPosition = Point(50 + (position.y - 3 * 50), 0) } else if (side == F && facing == DOWN) { nextFacing = DOWN nextPosition = Point(position.x + 100, 0) } return nextPosition to nextFacing } private fun nextPosition() = when (facing) { DOWN -> kotlin.runCatching { if (map[position.y + 1][position.x] in allowedTiles) Point(position.x, position.y + 1) else wrap() }.getOrDefault(wrap()) LEFT -> kotlin.runCatching { if (map[position.y][position.x - 1] in allowedTiles) Point(position.x - 1, position.y) else wrap() }.getOrDefault(wrap()) RIGHT -> kotlin.runCatching { if (map[position.y][position.x + 1] in allowedTiles) Point(position.x + 1, position.y) else wrap() }.getOrDefault(wrap()) UP -> kotlin.runCatching { if (map[position.y - 1][position.x] in allowedTiles) Point(position.x, position.y - 1) else wrap() }.getOrDefault(wrap()) } private fun nextPositionCube() = when (facing) { DOWN -> kotlin.runCatching { if (map[position.y + 1][position.x] in allowedTiles) Point(position.x, position.y + 1) to facing else wrapCube() }.getOrDefault(wrapCube()) LEFT -> kotlin.runCatching { if (map[position.y][position.x - 1] in allowedTiles) Point(position.x - 1, position.y) to facing else wrapCube() }.getOrDefault(wrapCube()) RIGHT -> kotlin.runCatching { if (map[position.y][position.x + 1] in allowedTiles) Point(position.x + 1, position.y) to facing else wrapCube() }.getOrDefault(wrapCube()) UP -> kotlin.runCatching { if (map[position.y - 1][position.x] in allowedTiles) Point(position.x, position.y - 1) to facing else wrapCube() }.getOrDefault(wrapCube()) } fun move(): Boolean { val nextPosition = nextPosition() if (map[nextPosition.y][nextPosition.x] == '.') { position = nextPosition return true } return false } fun moveCube(): Boolean { val (nextPosition, nextFacing) = nextPositionCube() if (map[nextPosition.y][nextPosition.x] == '.') { position = nextPosition facing = nextFacing return true } return false } val password get() = (position.y + 1) * 1000 + (position.x + 1) * 4 + facing.value } private enum class Facing(val value: Int) { DOWN(1), LEFT(2), RIGHT(0), UP(3) } private enum class Side { A, B, C, D, E, F; companion object { fun Point.toSide(): Side { val row = this.y val column = this.x return if (row in 0..49 && column in 50..99) A else if (row in 0..49 && column in 100..149) B else if (row in 50..99 && column in 50..99) C else if (row in 100..149 && column in 50..99) D else if (row in 100..149 && column in 0..49) E else if (row in 150..199 && column in 0..49) F else error("Invalid position $this") } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
10,149
advent-of-code
MIT License
src/main/kotlin/days/Solution15.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf private val String.hash get() = this.fold(0) { acc, c -> 17 * (acc + c.code) % 256 } private class HashMap { val boxes = List(256) { linkedMapOf<String, Int>() } fun execute(operation: String) { if (operation.endsWith('-')) { val label = operation.dropLast(1) boxes[label.hash].remove(label) } else { val pieces = operation.split('=') val label = pieces.first() val focalLength = pieces.last().toInt() boxes[label.hash][label] = focalLength } } val focusingPower get() = boxes.withIndex() .sumOf { (box, lenses) -> lenses.values .withIndex() .sumOf { (slot, focalLength) -> (box + 1) * (slot + 1) * focalLength } } } object Solution15 : Solution<List<String>>(AOC_YEAR, 15) { override fun getInput(handler: InputHandler) = handler.getInput(",") override fun solve(input: List<String>): PairOf<Int> { val ans1 = input.sumOf(String::hash) val hashMap = HashMap() input.forEach(hashMap::execute) val ans2 = hashMap.focusingPower return ans1 to ans2 } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
1,316
Advent-of-Code-2023
MIT License
src/main/kotlin/adventofcode/year2022/Day09RopeBridge.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2022 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.Tuple.minus import adventofcode.common.Tuple.plus import adventofcode.year2022.Day09RopeBridge.Companion.Direction.D import adventofcode.year2022.Day09RopeBridge.Companion.Direction.L import adventofcode.year2022.Day09RopeBridge.Companion.Direction.R import adventofcode.year2022.Day09RopeBridge.Companion.Direction.U import kotlin.math.abs import kotlin.math.sign class Day09RopeBridge(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val motionMoves by lazy { input.lines().map { line -> line.split(" ") }.map { (direction, steps) -> MotionMove(Direction.valueOf(direction), steps.toInt()) } } override fun partOne() = motionMoves.simulate(2).second.count() override fun partTwo() = motionMoves.simulate(10).second.count() companion object { private enum class Direction { D, L, R, U } private data class MotionMove(val direction: Direction, val steps: Int) private fun List<MotionMove>.simulate(knotCount: Int) = fold(List(knotCount) { (0 to 0) } to setOf(0 to 0)) { (knots, tailVisited), (direction, steps) -> (1..steps).fold(knots to tailVisited) { (knots, tailVisited), _ -> val newKnots = knots .drop(1) .fold(listOf(knots.first().move(direction))) { knotList, knot -> knotList + knot.track(knotList.last()) } newKnots to tailVisited + newKnots.last() } } private fun Pair<Int, Int>.move(direction: Direction) = when (direction) { D -> this + (0 to -1) L -> this + (-1 to 0) R -> this + (1 to 0) U -> this + (0 to 1) } private fun Pair<Int, Int>.track(other: Pair<Int, Int>): Pair<Int, Int> { val (dx, dy) = other - this return when { abs(dx) < 2 && abs(dy) < 2 -> this else -> this + (dx.sign to dy.sign) } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,112
AdventOfCode
MIT License
src/Day06.kt
chasebleyl
573,058,526
false
{"Kotlin": 15274}
fun String.allCharsUnique(): Boolean { val uniques = mutableSetOf<Char>() this.forEach { char -> uniques.add(char) } return uniques.size == this.length } fun main() { fun part1(input: List<String>): Int { val datastream = input[0] if (datastream.length < 4) return 0 for (i in 4 until datastream.length+1) { val currentSubstring = datastream.substring(i-4, i) if (currentSubstring.allCharsUnique()) return i } return 0 } fun part2(input: List<String>): Int { val datastream = input[0] if (datastream.length < 14) return 0 println("datastream=$datastream") for (i in 14 until datastream.length+1) { val currentSubstring = datastream.substring(i-14, i) if (currentSubstring.allCharsUnique()) return i } return 0 } val input = readInput("Day06") val testInput = readInput("Day06_test") // PART 1 check(part1(testInput) == 7) println(part1(input)) // PART 2 check(part2(testInput) == 19) println(part2(input)) }
0
Kotlin
0
1
f2f5cb5fd50fb3e7fb9deeab2ae637d2e3605ea3
1,120
aoc-2022
Apache License 2.0
code/graph/Hungarian.kt
hakiobo
397,069,173
false
null
// https://open.kattis.com/problems/cordonbleu // https://open.kattis.com/problems/toursdesalesforce // Min Cost Match Matching private class Hungarian(val costs: Array<IntArray>) { // assuming a square matrix of costs val n = costs.size var adjustment = 0 val adjustmentByRow = IntArray(n) val adjustmentByCol = IntArray(n) val minSlackRowByCol = IntArray(n) val minSlackValueByCol = IntArray(n) val committedRows = IntArray(n) var numCommittedRows = 0 val parentRowByCommittedCol = IntArray(n) val matchColByRow = IntArray(n) { -1 } val matchRowByCol = IntArray(n) { -1 } fun findBestMatching(): Int { // returns the final cost, can get the arrangements from matchRowByCol an matchColByRow // get some values down to 0 to start for (row in 0 until n) { var low = costs[row][0] for (col in 1 until n) { low = min(adjustmentByRow[row], costs[row][col]) } adjustment += low adjustmentByRow[row] = low } adjustmentByCol.fill(Int.MAX_VALUE) for (row in 0 until n) { for (col in 0 until n) { adjustmentByCol[col] = min(costs[row][col] - adjustmentByRow[row], adjustmentByCol[col]) } } adjustment += adjustmentByCol.sum() // greedily set up some matches for (row in 0 until n) { for (col in 0 until n) { if (matchColByRow[row] == -1 && matchRowByCol[col] == -1 && costs[row][col] - adjustmentByRow[row] - adjustmentByCol[col] == 0) { matchRowByCol[col] = row matchColByRow[row] = col } } } for (row in 0 until n) { if (matchColByRow[row] == -1) { // set some stuff up parentRowByCommittedCol.fill(-1) committedRows[0] = row numCommittedRows = 1 minSlackRowByCol.fill(row) for (col in 0 until n) { minSlackValueByCol[col] = costs[row][col] - adjustmentByRow[row] - adjustmentByCol[col] } executePhase() } } return adjustment } fun executePhase() { while (true) { var minSlackRow = -1 var minSlackCol = -1 var minSlackValue = Int.MAX_VALUE for (col in 0 until n) { if (parentRowByCommittedCol[col] == -1 && minSlackValueByCol[col] < minSlackValue) { minSlackValue = minSlackValueByCol[col] minSlackRow = minSlackRowByCol[col] minSlackCol = col } } if (minSlackValue > 0) { adjustment += minSlackValue for (i in 0 until numCommittedRows) { adjustmentByRow[committedRows[i]] += minSlackValue } for (col in 0 until n) { if (parentRowByCommittedCol[col] == -1) { minSlackValueByCol[col] -= minSlackValue } else { adjustmentByCol[col] -= minSlackValue } } } parentRowByCommittedCol[minSlackCol] = minSlackRow if (matchRowByCol[minSlackCol] == -1) { var committedCol = minSlackCol while (committedCol != -1) { val row = parentRowByCommittedCol[committedCol] val temp = matchColByRow[row] matchRowByCol[committedCol] = row matchColByRow[row] = committedCol committedCol = temp } return } else { val row = matchRowByCol[minSlackCol] committedRows[numCommittedRows++] = row for (col in 0 until n) { if (parentRowByCommittedCol[col] == -1) { val slack = costs[row][col] - adjustmentByRow[row] - adjustmentByCol[col] if (minSlackValueByCol[col] > slack) { minSlackValueByCol[col] = slack minSlackRowByCol[col] = row } } } } } } }
0
Kotlin
1
2
f862cc5e7fb6a81715d6ea8ccf7fb08833a58173
4,414
Kotlinaughts
MIT License
src/main/kotlin/g0601_0700/s0655_print_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0655_print_binary_tree // #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_02_13_Time_176_ms_(100.00%)_Space_36_MB_(80.00%) import com_github_leetcode.TreeNode import java.util.LinkedList import kotlin.math.pow /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun printTree(root: TreeNode?): List<MutableList<String>> { val result: MutableList<MutableList<String>> = LinkedList() val height = if (root == null) 1 else getHeight(root) val columns = (2.0.pow(height.toDouble()) - 1).toInt() val row: MutableList<String> = ArrayList() for (i in 0 until columns) { row.add("") } for (i in 0 until height) { result.add(ArrayList(row)) } populateResult(root, result, 0, height, 0, columns - 1) return result } private fun populateResult( root: TreeNode?, result: List<MutableList<String>>, row: Int, totalRows: Int, i: Int, j: Int ) { if (row == totalRows || root == null) { return } result[row][(i + j) / 2] = root.`val`.toString() populateResult(root.left, result, row + 1, totalRows, i, (i + j) / 2 - 1) populateResult(root.right, result, row + 1, totalRows, (i + j) / 2 + 1, j) } private fun getHeight(root: TreeNode?): Int { return if (root == null) { 0 } else 1 + getHeight(root.left).coerceAtLeast(getHeight(root.right)) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,719
LeetCode-in-Kotlin
MIT License
src/main/kotlin/days/Day8.kt
hughjdavey
572,954,098
false
{"Kotlin": 61752}
package days import xyz.hughjd.aocutils.Collections.takeWhileInclusive import xyz.hughjd.aocutils.Coords.Coord class Day8 : Day(8) { private val trees = Trees(inputList) private val treeCoords = trees.trees.indices.flatMap { y -> trees.trees[0].indices.map { x -> Coord(x, y) } } override fun partOne(): Any { return treeCoords.count(trees::isVisible) } override fun partTwo(): Any { return treeCoords.map(trees::scenicScore).max() } class Trees(input: List<String>, val trees: List<List<Int>> = getTrees(input)) { fun scenicScore(location: Coord): Int { return getTreesToEdgeOfGrid(location, true).map { it.size }.fold(1) { acc, elem -> acc * elem } } fun isVisible(location: Coord): Boolean { val height = safeGet(location)!! return getTreesToEdgeOfGrid(location).any { it.all { height2 -> height2 < height } } } fun getTreesToEdgeOfGrid(location: Coord, considerView: Boolean = false): List<List<Int>> { val height = if (considerView) safeGet(location)!! else null return listOf(shiftToEdge(location, height) { it.plusX(1) }, shiftToEdge(location, height) { it.minusX(1) }, shiftToEdge(location, height) { it.plusY(1) }, shiftToEdge(location, height) { it.minusY(1) }) } private fun shiftToEdge(location: Coord, maxHeight: Int?, shift: (c: Coord) -> Coord): List<Int> { return generateSequence(location, shift).map(this::safeGet).drop(1) .takeWhileInclusive { it != null && (maxHeight == null || it < maxHeight) } .filterNotNull().toList() } private fun safeGet(location: Coord): Int? { return try { trees[location.y][location.x] } catch (e: Exception) { null } } companion object { fun getTrees(input: List<String>): List<List<Int>> { return input.fold(listOf()) { acc, elem -> val row: List<Int> = elem.toCharArray().map { it.toString().toInt() } acc.plusElement(row) } } } } }
0
Kotlin
0
2
65014f2872e5eb84a15df8e80284e43795e4c700
2,257
aoc-2022
Creative Commons Zero v1.0 Universal
src/Day04.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
fun main() { fun parseInput(input: List<String>) = input.map { elfPair -> elfPair.split(",", "-") .chunked(2) .map { it[0].toInt()..it[1].toInt() } } fun part1(input: List<String>): Int { return parseInput(input) .filter { it[0].all { section -> it[1].contains(section) } || it[1].all { section -> it[0].contains(section) } } .size } fun part2(input: List<String>): Int { return parseInput(input) .filter { it[0].any { section -> it[1].contains(section) } || it[1].any { section -> it[0].contains(section) } } .size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val input = readInput("Day04") check(part1(testInput) == 2) println(part1(input)) check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
970
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CoinPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Coin Path. * @see <a href="https://leetcode.com/problems/coin-path/">Source</a> */ fun interface CoinPath { fun cheapestJump(a: IntArray, b: Int): List<Int> } /** * Approach #2 Using Memoization. * Time complexity : O(nB). * Space complexity : O(n). */ class CoinPathMemo : CoinPath { override fun cheapestJump(a: IntArray, b: Int): List<Int> { val next = IntArray(a.size) { -1 } val memo = LongArray(a.size) jump(a, b, 0, next, memo) val res: MutableList<Int> = ArrayList() var i = 0 while (i < a.size && next[i] > 0) { res.add(i + 1) i = next[i] } if (i == a.size - 1 && a[i] >= 0) res.add(a.size) else return ArrayList() return res } private fun jump(a: IntArray, b: Int, i: Int, next: IntArray, memo: LongArray): Long { if (a.isEmpty()) return 0L if (memo[i] > 0) return memo[i] if (i == a.size - 1 && a[i] >= 0) return a[i].toLong() var minCost = Int.MAX_VALUE.toLong() var j = i + 1 while (j <= i + b && j < a.size) { if (a[j] >= 0) { val cost = a[i] + jump(a, b, j, next, memo) if (cost < minCost) { minCost = cost next[i] = j } } j++ } memo[i] = minCost return minCost } } /** * Approach #3 Using Dynamic Programming. * Time complexity : O(nB). * Space complexity : O(n). */ class CoinPathDP : CoinPath { override fun cheapestJump(a: IntArray, b: Int): List<Int> { val next = IntArray(a.size) { -1 } val dp = LongArray(a.size) val res: MutableList<Int> = ArrayList() for (i in a.size - 2 downTo 0) { var minCost = Int.MAX_VALUE.toLong() var j: Int = i + 1 while (j <= i + b && j < a.size) { if (a[j] >= 0) { val cost: Long = a[i] + dp[j] if (cost < minCost) { minCost = cost next[i] = j } } j++ } dp[i] = minCost } var i = 0 while (i < a.size && next[i] > 0) { res.add(i + 1) i = next[i] } if (i == a.size - 1 && a[i] >= 0) res.add(a.size) else return ArrayList() return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,090
kotlab
Apache License 2.0
src/main/kotlin/io/trie/MaximumXORInArray.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.trie import kotlin.math.pow // https://leetcode.com/explore/learn/card/trie/149/practical-application-ii/1057/ class MaximumXORInArray { fun executeInefficient(nums: IntArray): Int = nums.foldIndexed(0) { index, acc, value -> maxOf(acc, (index + 1 until nums.size).map { j -> nums[j].xor(value) }.maxOrNull() ?: Integer.MIN_VALUE) } internal data class TrieNode(var left: TrieNode? = null, var right: TrieNode? = null) { // O(1) TC fun insert(num: Int) { // insert the binary representation of the num var current = this for (i in 31 downTo 0) { //get the ith bit val bit = num shr i and 1 current = if (bit == 0) { current.left ?: TrieNode().also { current.left = it } } else { current.right ?: TrieNode().also { current.right = it } } } } // O(1) TC fun find(num: Int): Int { // we always want to go to opposite path (if exists) because in that way we can have highly varying bits var current = this var opp = 0 for (i in 31 downTo 0) { val bit = num shr i and 1 current = (if (bit == 0) { current.right?.also { opp += 2.0.pow(i.toDouble()).toInt() } ?: current.left ?: break } else { current.left ?: current.right?.also { opp += 2.0.pow(i.toDouble()).toInt() } ?: break }) } return opp } } fun execute(nums: IntArray): Int = TrieNode().let { root -> nums.forEach { root.insert(it) } nums.fold(0) { acc, value -> acc.coerceAtLeast(root.find(value) xor value) } } } fun main() { val maximumXORInArray = MaximumXORInArray() println("${maximumXORInArray.execute(intArrayOf(2, 4, 5, 25))}") }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,749
coding
MIT License
src/com/wd/algorithm/leetcode/ALGO0002.kt
WalkerDenial
327,944,547
false
null
package com.wd.algorithm.leetcode import com.wd.algorithm.test class ListNode(var `val`: Int) { var next: ListNode? = null } /** * 2. 两数相加 * * 给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。 * 请你将两个数相加,并以相同形式返回一个表示和的链表。 * 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。 * */ class ALGO0002 { /** * 方式一 * 转换成对应的整数再进行计算,然后逆序输出 * 时间复杂度 T(n) */ fun addTwoNumbers1(l1: ListNode, l2: ListNode): ListNode { val str1 = l1.contentToString() // l1 逆序 val str2 = l2.contentToString() // l2 逆序 val num1 = if (str1.isBlank()) 0 else str1.reversed().toInt() // l1 真实数值 val num2 = if (str2.isBlank()) 0 else str2.reversed().toInt() // l2 真是数值 val result = (num1 + num2).toString().reversed() // 求出结果并逆序 val data = IntArray(result.length) // 转换成数组 for (i in result.indices) data[i] = result[i].toString().toInt() return getListNode(data) // 获取返回结果 } /** * 方式二 * 按节点进位处理 * 时间复杂度 T(n) */ fun addTwoNumbers2(l1: ListNode?, l2: ListNode?): ListNode { var node1 = l1 var node2 = l2 val node = ListNode(-1) var curr = node var offset = 0 while (node1 != null || node2 != null) { val value1 = node1?.`val` ?: 0 val value2 = node2?.`val` ?: 0 val result = value1 + value2 + offset val value = result.rem(10) offset = result.div(10) val newNode = ListNode(value) node1?.let { node1 = it.next } node2?.let { node2 = it.next } curr.next = newNode curr = curr.next!! } if (offset > 0) { curr.next = ListNode(1) } return node.next!! } } fun main() { val clazz = ALGO0002() val l1 = getListNode(intArrayOf(9, 9, 9, 9, 9, 9, 9)) val l2 = getListNode(intArrayOf(9, 9, 9, 9)) (clazz::addTwoNumbers1).test(l1, l2) (clazz::addTwoNumbers2).test(l1, l2) } private fun getListNode(data: IntArray): ListNode { if (data.isEmpty()) return ListNode(0) var lastNode: ListNode? = null var node: ListNode? = null for (i in data) { val item = ListNode(i) if (node == null) node = item else lastNode?.next = item lastNode = item } return node!! } private fun ListNode?.contentToString(): String { if (this == null) return "" val sb = StringBuilder() var item: ListNode? = this while (item != null) { sb.append("${item.`val`}") item = item.next } return sb.toString() }
0
Kotlin
0
0
245ab89bd8bf467625901034dc1139f0a626887b
2,951
AlgorithmAnalyze
Apache License 2.0
src/Day07.kt
esteluk
572,920,449
false
{"Kotlin": 29185}
interface Node { val name: String fun size(): Int } data class File(override val name: String, val size: Int): Node { override fun size(): Int { return this.size } override fun toString(): String { return "- $name (file, size=$size)" } } data class Directory(override val name: String, val parent: Directory?, var children: List<Node>): Node { override fun size(): Int { return children.sumOf { it.size() } } fun addDirectory(directoryName: String): Directory { val existing = children.firstOrNull { it.name == directoryName } if (existing != null) { if (existing is Directory) { return existing } else { println("Attempting to traverse to a file") throw IllegalAccessException() } } else { val newDirectory = Directory(directoryName, this, listOf()) this.children = children + newDirectory return newDirectory } } fun addFile(file: File) { val existing = children.firstOrNull { it.name == file.name } if (existing != null) { println("Attempting to add file that already exists") return } this.children = children + file } fun findDirectories(maxSize: Int): List<Directory> { val dirs = mutableListOf<Directory>() children.forEach { if (it is Directory) { if (it.size() < maxSize) { dirs.add(it) } dirs.addAll(it.findDirectories(maxSize)) } } return dirs } fun findLargeDirectories(minSize: Int): List<Directory> { val dirs = mutableListOf<Directory>() children.forEach { if (it is Directory) { if (it.size() >= minSize) { dirs.add(it) } dirs.addAll(it.findLargeDirectories(minSize)) } } return dirs } private fun depth(): Int { var depth = 0 var p = parent while (p != null) { p = p.parent depth += 1 } return depth } override fun toString(): String { return children.fold("- $name (dir, size=${size()})") { acc, element -> val indent = " ".repeat(depth()) "$acc\n$indent$element" } } } fun main() { fun parseFilesystem(input: List<String>): Directory { val filesystem = Directory("/", null, listOf()) var currentDirectory: Directory = filesystem for (line in input) { if (line.startsWith("$")) { val command = line.substring(2) if (command.startsWith("cd")) { val directory = command.substring(3) if (directory == "/") { currentDirectory = filesystem } else if (directory == "..") { currentDirectory = currentDirectory.parent ?: filesystem } else { currentDirectory = currentDirectory.addDirectory(directory) } } else if (command.startsWith("ls")) { // Do nothing, next input will parse } } else { // Must be file size output if (line.startsWith("dir")) { val dirName = line.substring(4) currentDirectory.addDirectory(dirName) } else { // Is file with size val split = line.split(" ") val size = split[0].toInt() val name = split[1] val file = File(name, size) currentDirectory.addFile(file) } } } // println(filesystem) return filesystem } fun part1(input: List<String>): Int { val filesystem = parseFilesystem(input) val smallDirectories = filesystem.findDirectories(100000) return smallDirectories.fold(0) { acc, element -> acc + element.size() } } fun part2(input: List<String>): Int { val filesystem = parseFilesystem(input) val totalSpace = 70000000 val necessarySpace = 30000000 val availableSpace = totalSpace - filesystem.size() val requiredSpace = necessarySpace - availableSpace val largeDirectories = filesystem.findLargeDirectories(requiredSpace) return largeDirectories.minByOrNull { it.size() }!!.size() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73
4,953
adventofcode-2022
Apache License 2.0
src/shreckye/coursera/algorithms/Course 3 Programming Assignment #3 Question 3.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.io.File import java.util.* import kotlin.test.assertEquals val filename = args[0] val INDEX_LABEL_OFFSET = 1 val questionVertexLabels = intArrayOf(1, 2, 3, 4, 17, 117, 517, 997) val (numVertices, vertexWeights) = File(filename).bufferedReader().use { val numVertices = it.readLine().toInt() val vertexWeights = it.lineSequence().map(String::toInt).toIntArray(numVertices) numVertices to vertexWeights } fun mwis(numVertices: Int, vertexWeights: IntArray): Pair<Long, BitSet> { //val maxWeights = IntArray(numVertices + 1) val choiceSet = BitSet(numVertices + 1) // Int causes overflow var maxWeightNMinus2 = 0L var maxWeightNMinus1 = vertexWeights[0].toLong() choiceSet[1] = false for (n in 2..numVertices) { val maxWeight2 = maxWeightNMinus2 + vertexWeights[n - 1] val choice = maxWeightNMinus1 >= maxWeight2 choiceSet[n] = choice val maxWeightI = if (choice) maxWeightNMinus1 else maxWeight2 maxWeightNMinus2 = maxWeightNMinus1 maxWeightNMinus1 = maxWeightI } // Reconstruction val takenSet = BitSet(numVertices) var n = numVertices while (n > 0) if (choiceSet[n]) n-- else { takenSet[n - 1] = true n -= 2 } return maxWeightNMinus1 to takenSet } val mwisSet = mwis(numVertices, vertexWeights).second println(questionVertexLabels.map { if (mwisSet[it - INDEX_LABEL_OFFSET]) '1' else '0' }.joinToString("")) // Test cases // n = 0 case: not supported, n = 1 case: special case that takes 1 element for (n in 2 until 1024) { val (mwisWeight, mwisSet) = mwis(n, IntArray(n) { it % 2 }) assertEquals(n / 2, mwisWeight.toInt(), "n = $n") assertEquals( BitSet(n).also { set -> (0 until n).filter { it % 2 != 0 }.forEach { set[it] = true } }, mwisSet, "n = $n" ) }
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
1,930
coursera-stanford-algorithms-solutions-kotlin
MIT License
advent-of-code-2022/src/test/kotlin/Day 9 Rope Bridge.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import kotlin.math.abs import org.junit.jupiter.api.Test class `Day 9 Rope Bridge` { @Test fun silverTest() { amountOfVisitedPoints(parseInput(testInput), true) shouldBe 13 } @Test fun silver() { amountOfVisitedPoints(parseInput(loadResource("day9"))) shouldBe 6197 } @Test fun goldTest() { amountOfVisitedPointsLongerRope(parseInput(largerInput), debug = true) shouldBe 36 } @Test fun gold() { amountOfVisitedPointsLongerRope(parseInput(loadResource("day9"))) shouldBe 2562 } private fun amountOfVisitedPoints(input: List<Point>, debug: Boolean = false): Int { val visited = input .scan(Point(0, 0) to Point(0, 0)) { (prevHead, prevTail), move -> val head = prevHead + move val diff = head - prevTail val isTooLong = diff.run { abs(x) > 1 || abs(y) > 1 } val tail = when { isTooLong -> prevTail + diff.direction() else -> prevTail } head to tail } .map { it.second } .toSet() if (debug) printMap(visited.associateWith { "#" }) return visited.size } private fun amountOfVisitedPointsLongerRope(input: List<Point>, debug: Boolean = false): Int { val visited = input .scan(buildList { repeat(10) { add(Point(0, 0)) } }) { rope, move -> moveRope(rope, move) } .map { it.last() } .toSet() if (debug) printMap(visited.associateWith { "#" }) return visited.size } /** Pulls the head and then all other segments as needed */ private fun moveRope(rope: List<Point>, move: Point): List<Point> { return buildList { val movedRope = this add(rope.first() + move) rope.drop(1).forEach { point -> val diff = movedRope.last() - point val isTooLong = diff.run { abs(x) > 1 || abs(y) > 1 } when { isTooLong -> add(point + diff.direction()) else -> add(point) } } } } private fun parseInput(input: String): List<Point> { val up = Point(0, 0).up() val down = Point(0, 0).down() val left = Point(0, 0).left() val right = Point(0, 0).right() return input.trim().lines().flatMap { val (direction, amount) = it.split(" ") val vector = when (direction) { "L" -> left "R" -> right "U" -> up "D" -> down else -> error("") } buildList { repeat(amount.toInt()) { add(vector) } } } } private val testInput = """ R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 """.trimIndent() val largerInput = """ R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
2,827
advent-of-code
MIT License
src/main/kotlin/org/hydev/lcci/lcci_02.kt
VergeDX
334,298,924
false
null
package org.hydev.lcci import ListNode.Companion.joinNode import java.math.BigInteger // https://leetcode-cn.com/problems/remove-duplicate-node-lcci/ class ListNode(var `val`: Int) { var next: ListNode? = null companion object { fun removeDuplicateNodes(head: ListNode?): ListNode? { if (head == null) return null // Linked Hash Set has order. val emptyOrderedSet = LinkedHashSet<Int>() // Here, head != null, so current value = head.`val`. var currentNode = head while (currentNode != null) { // For each node's val. val currentVal = currentNode.`val` emptyOrderedSet.add(currentVal) currentNode = currentNode.next } val resultNodeList = emptyOrderedSet.map { ListNode(it) } resultNodeList.forEachIndexed { index, listNode -> if (index != resultNodeList.size - 1) listNode.next = resultNodeList[index + 1] } return resultNodeList[0] } fun ListNode?.joinNode(x: Int): ListNode { if (this == null) return ListNode(x) var currentNode = this while (currentNode != null) { if (currentNode.next == null) break currentNode = currentNode.next } // Here, currentNode.next == null. currentNode!!.next = ListNode(x) return this } // https://leetcode-cn.com/problems/partition-list-lcci/ fun partition(head: ListNode?, x: Int): ListNode? { if (head == null) return head if (head.next == null) return head var smallPart: ListNode? = null var bigPart: ListNode? = null var currentNode = head while (currentNode != null) { val currentVal = currentNode.`val` when { currentVal < x -> smallPart = smallPart.joinNode(currentVal) else -> bigPart = bigPart.joinNode(currentVal) } currentNode = currentNode.next } currentNode = smallPart while (currentNode != null) { if (currentNode.next == null) break currentNode = currentNode.next } currentNode?.next = bigPart return smallPart ?: bigPart } // https://leetcode-cn.com/problems/sum-lists-lcci/ fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { var nl1 = "" var nl2 = "" var currentNode = l1 while (currentNode != null) { val currentVal = currentNode.`val` nl1 += currentVal.toString() currentNode = currentNode.next } currentNode = l2 while (currentNode != null) { val currentVal = currentNode.`val` nl2 += currentVal.toString() currentNode = currentNode.next } // Null check. if (nl1.isBlank()) nl1 = "0" if (nl2.isBlank()) nl2 = "0" // result maybe 0. val bnl1 = BigInteger(nl1.reversed()) val bnl2 = BigInteger(nl2.reversed()) val resultStringReversed = bnl1.add(bnl2).toString().reversed() // Then turn result.toString().reversed() -> ListNode. val result = ListNode(resultStringReversed[0].toString().toInt()) // if (result.`val`.toString().length == 1) return result currentNode = result for (index in resultStringReversed.indices) { // Index == 0, continue. if (index == 0) continue val tempNode = ListNode(resultStringReversed[index].toString().toInt()) currentNode!!.next = tempNode currentNode = tempNode } return result } // https://leetcode-cn.com/problems/palindrome-linked-list-lcci/ fun isPalindrome(head: ListNode?): Boolean { val InputNumberList = ArrayList<Int>() var currentNode = head while (currentNode != null) { val currentVal = currentNode.`val` // if (currentVal < 0) input += "-" InputNumberList += currentVal currentNode = currentNode.next } return InputNumberList == InputNumberList.reversed() } } } // https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/ fun kthToLast(head: ListNode?, k: Int): Int { val resultList = ArrayList<Int>() var currentNode = head while (currentNode != null) { val currentVal = currentNode.`val` resultList.add(currentVal) currentNode = currentNode.next } return resultList[resultList.size - k] } fun main() { val example1 = ListNode(1).apply { next = ListNode(2).apply { next = ListNode(3).apply { next = ListNode(3).apply { next = ListNode(2).apply { next = ListNode(1) } } } } } val example2 = ListNode(1).apply { next = ListNode(1).apply { next = ListNode(1).apply { next = ListNode(1).apply { next = ListNode(2) } } } } ListNode.removeDuplicateNodes(example1) ListNode.removeDuplicateNodes(example2) ListNode(0).joinNode(2) ListNode.partition(example1, 3) val nl1 = ListNode(7).apply { next = ListNode(1).apply { next = ListNode(6) } } val nl2 = ListNode(5).apply { next = ListNode(9).apply { next = ListNode(2) } } ListNode.addTwoNumbers(nl1, nl2) ListNode.addTwoNumbers(null, null) val negative = ListNode(-129).apply { next = ListNode(-129) } ListNode.isPalindrome(negative) }
0
Kotlin
0
0
9a26ac2e24b0a0bdf4ec5c491523fe9721c6c406
6,125
LeetCode_Practice
MIT License
2022/src/day23/day23.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day23 import GREEN import RESET import printTimeMillis import readInput data class Elf(val x: Int, val y: Int) { fun nextPos(elves: Set<Elf>, round: Int): Elf { val POS = listOf(north(), south(), west(), east()) val CHOSEN = listOf( Elf(x, y - 1), // up Elf(x, y + 1), // down Elf(x - 1, y), // left Elf(x + 1, y) // right ) var elfAround = false for (neighbors in POS.flatten()) { if (elves.contains(neighbors)) { elfAround = true break } } if (!elfAround) return this // Nothing around, don't move for (i in 0 until 4) { var elfInDirection = false for (neighbor in POS[(round + i) % POS.size]) { if (elves.contains(neighbor)) { elfInDirection = true break } } // Nothing in that direction, go in that direction if (!elfInDirection) return CHOSEN[(round + i) % POS.size] } return this // Cannot go on any direction but there is another elf in the 8 pos around } private fun north() = setOf(Elf(x - 1, y - 1), Elf(x, y - 1), Elf(x + 1, y - 1)) private fun south() = setOf(Elf(x - 1, y + 1), Elf(x, y + 1), Elf(x + 1, y + 1)) private fun west() = setOf(Elf(x - 1, y - 1), Elf(x - 1, y), Elf(x - 1, y + 1)) private fun east() = setOf(Elf(x + 1, y - 1 ), Elf(x + 1, y), Elf(x + 1, y + 1)) } fun List<String>.toPoints(): Set<Elf> { val ret = mutableSetOf<Elf>() forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') ret.add(Elf(x, y)) } } return ret } fun Set<Elf>.print() { val (minX, maxX) = Pair(minBy { it.x }.x - 1, maxBy { it.x }.x + 1) val (minY, maxY) = Pair(minBy { it.y }.y - 1, maxBy { it.y }.y + 1) println("--------") for (y in minY..maxY) { for (x in minX..maxX) { if (contains(Elf(x, y))) print('#') else print('.') } println() } println("--------") } fun Set<Elf>.count(): Int { val (minX, maxX) = Pair(minBy { it.x }.x, maxBy { it.x }.x) val (minY, maxY) = Pair(minBy { it.y }.y, maxBy { it.y }.y) var ret = 0 for (y in minY..maxY) { for (x in minX..maxX) { if (!contains(Elf(x, y))) ret += 1 } } return ret } fun executeRound(elves: Set<Elf>, roundNb: Int): Set<Elf> { val newPos = mutableMapOf<Elf, MutableList<Elf>>() // map of NewPos -> listOf(OriginalPos) for (elf in elves) { val nextPos = elf.nextPos(elves, roundNb) if (newPos.contains(nextPos)) { newPos[nextPos]?.add(elf) } else { newPos[nextPos] = mutableListOf(elf) } } val newPts = mutableSetOf<Elf>() for (elf in newPos.keys) { val list = newPos[elf]!! if (list.size == 1) { newPts.add(elf) // add the moved position } else { newPts.addAll(list) // add the original elves positions } } return newPts } fun part1(input: List<String>, rounds: Int = 1): Int { var pts = input.toPoints() for (round in 0 until rounds) { pts = executeRound(pts, round) } return pts.count() } fun part2(input: List<String>): Int { var pts = input.toPoints() var roundNb = 0 while (true) { val newPts = executeRound(pts, roundNb) if (pts == newPts) return roundNb + 1 pts = newPts roundNb += 1 } } fun main() { val smallTest = readInput("day23_small_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(smallTest, 4) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(smallTest) + RESET) } val testInput = readInput("day23_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput, 10) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day23.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input, 10) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
4,267
advent-of-code
Apache License 2.0
src/main/kotlin/day14/Day14ChocolateCharts.kt
Zordid
160,908,640
false
null
package day14 import shared.readPuzzle fun recipeSequencer() = sequence { val scores = mutableListOf(3, 7) var (elf1, elf2) = 0 to 1 yieldAll(scores) while (true) { val newScore = scores[elf1] + scores[elf2] if (newScore >= 10) yield((newScore / 10).also { scores.add(it) }) yield((newScore % 10).also { scores.add(it) }) elf1 = (elf1 + scores[elf1] + 1) % scores.size elf2 = (elf2 + scores[elf2] + 1) % scores.size } } fun part1(puzzle: String) = recipeSequencer().drop(puzzle.toInt()).take(10).joinToString("") fun part2(puzzle: String): Int { val key = puzzle.map { (it - '0') } return recipeSequencer() .windowed(puzzle.length, step = 1) .takeWhile { it != key }.count() } fun main() { val puzzle = readPuzzle(14).single() println(part1(puzzle)) println(part2(puzzle)) }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
893
adventofcode-kotlin-2018
Apache License 2.0
src/day06/Day06.kt
banshay
572,450,866
false
{"Kotlin": 33644}
package day06 import readInput fun main() { fun part1(input: List<String>): Int { return input.map { it.toSignal().indexOfStartSignal() }[0] } fun part2(input: List<String>): Int { return input.map { it.toSignal().indexOfMessageStart() }.also { println(it) }[0] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") val input = readInput("Day06") println("test part1: ${part1(testInput)}") println("result part1: ${part1(input)}") println("test part2: ${part2(testInput)}") println("result part2: ${part2(input)}") } fun String.toSignal(): Signal = Signal(this) data class Signal(val signal: String) { fun indexOfStartSignal(): Int { val startSignal = signal.windowed(size = 4, step = 1) .map { it.toSet() } .first { it.size == 4 } .joinToString("") return signal.indexOf(startSignal) + 4 } fun indexOfMessageStart(): Int { val messageSignal = signal.windowed(14) .map { it.toSet() } .first { it.size == 14 } .joinToString("") return signal.indexOf(messageSignal) + 14 } }
0
Kotlin
0
0
c3de3641c20c8c2598359e7aae3051d6d7582e7e
1,220
advent-of-code-22
Apache License 2.0
src/Day06.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
import java.math.BigInteger import java.util.regex.Pattern import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt fun main() { val input = readInput("Day06") var times = input[0].removePrefix("Time:").trim().split(Pattern.compile("\\W+")).map { it.toLong() } var distances = input[1].removePrefix("Distance:").trim().split(Pattern.compile("\\W+")).map { it.toLong() } times = listOf(times.joinToString("").toLong()) distances = listOf(distances.joinToString("").toLong()) var res = BigInteger.ONE for (raceNo in times.indices) { val T = times[raceNo] val d = distances[raceNo] // t(T-t) > d, t^2 - tT + d = 0 val a = 1 val b = -T val c = d val D = sqrt(b*b - 4.0*a*c) var x1 = (-b - D)/2/a var x2 = (-b + D) /2/a if (ceil(x1) == x1) { x1 += 1 } else { x1 = ceil(x1) } if (floor(x2) == x2) { x2 -= 1 } else { x2 = floor(x2) } val x = (x2 - x1 + 1).toLong() res *= x.toBigInteger() } println(res) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,138
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/day2/Day2.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day2 import java.lang.IllegalArgumentException class Day2 { fun getGameStore(filename: String): GameStore { val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines() return GameStore( readLines.map { Round(Shape.fromString(it[0]), Shape.fromString(it[2])) }, readLines.map { Round(Shape.fromString(it[0]), Shape.fromStringv2(Shape.fromString(it[0]), it[2])) } ) } } sealed class Shape { abstract fun score(): Int abstract fun winShape(): Shape abstract fun drawShape(): Shape abstract fun loseShape(): Shape object Rock: Shape() { override fun score(): Int = 1 override fun winShape(): Shape = Paper override fun drawShape(): Shape = Rock override fun loseShape(): Shape = Scissors } object Paper: Shape() { override fun score(): Int = 2 override fun winShape(): Shape = Scissors override fun drawShape(): Shape = Paper override fun loseShape(): Shape = Rock } object Scissors: Shape() { override fun score(): Int = 3 override fun winShape(): Shape = Rock override fun drawShape(): Shape = Scissors override fun loseShape(): Shape = Paper } companion object { fun fromString(input: Char): Shape { return when(input) { 'A' -> Rock 'B' -> Paper 'C' -> Scissors 'Y' -> Paper 'X' -> Rock 'Z' -> Scissors else -> throw IllegalArgumentException("Unknown shape $input") } } fun fromStringv2(opponent: Shape, input: Char): Shape { return when(input) { 'Y' -> opponent.drawShape() 'X' -> opponent.loseShape() 'Z' -> opponent.winShape() else -> throw IllegalArgumentException("Unknown shape $input") } } } } class Round(private val opponent: Shape, private val you: Shape) { override fun toString(): String { return "$opponent vs $you" } private fun shapeScore(): Int = you.score() private fun roundScore(): Int { return when(opponent) { Shape.Paper -> when(you) { Shape.Paper -> 3 Shape.Rock -> 0 Shape.Scissors -> 6 } Shape.Rock -> when(you) { Shape.Paper -> 6 Shape.Rock -> 3 Shape.Scissors -> 0 } Shape.Scissors -> when(you) { Shape.Paper -> 0 Shape.Rock -> 6 Shape.Scissors -> 3 } } } fun score(): Int = roundScore() + shapeScore() } class GameStore(val roundList: List<Round>, val roundListPart2: List<Round>) { fun score(): Int = roundList.sumOf { it.score() } fun scorePart2(): Int = roundListPart2.sumOf { it.score() } } fun main() { println(Day2().getGameStore("/day2_test.txt").score()) println(Day2().getGameStore("/day2_input.txt").score()) println(Day2().getGameStore("/day2_test.txt").scorePart2()) println(Day2().getGameStore("/day2_input.txt").scorePart2()) }
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
3,268
adventofcode2022
Apache License 2.0
src/main/kotlin/io/github/kmakma/adventofcode/y2019/utils/Vector2D.kt
kmakma
225,714,388
false
null
package io.github.kmakma.adventofcode.y2019.utils import io.github.kmakma.adventofcode.utils.gcd import kotlin.math.* /** * integer vector, careful using [rotated] */ internal data class Vector2D(val x: Int, val y: Int) : Comparable<Vector2D> { // TODO rename to simpleVector val length = sqrt((x * x + y * y).toDouble()) val manhattanDistance = abs(x) + abs(y) fun shortest(): Vector2D { val gcd = abs(gcd(x, y)) return if (gcd != 0) { this / gcd } else { Vector2D(x, y) } } fun rotated(degree: Int): Vector2D { val radians = degree * PI / 180 val cos = cos(radians) val sin = sin(radians) val turnedX = x * cos - y * sin val turnedY = x * sin + y * cos return Vector2D(turnedX.toInt(), turnedY.toInt()) } override fun compareTo(other: Vector2D): Int { // FIXME check weather changes influence other stuff return if (this.y != other.y) { this.y - other.y } else { this.x - other.x } } override fun toString(): String = "($x,$y)" operator fun plus(vector2D: Vector2D) = Vector2D(x + vector2D.x, y + vector2D.y) operator fun minus(vector2D: Vector2D) = Vector2D(x - vector2D.x, y - vector2D.y) operator fun div(number: Int): Vector2D = Vector2D(x / number, y / number) operator fun rangeTo(other: Vector2D) = PointProgression2D(this, other) operator fun inc(): Vector2D { val gcd = gcd(x, y) return this + this / gcd } operator fun dec(): Vector2D { val gcd = gcd(x, y) return this - this / gcd } infix fun until(to: Vector2D): PointProgression2D { var newX = to.x var newY = to.y if (y != to.y) { if (y > to.y) { newY++ } else { newY-- } } else { when { x == to.x -> { } x > to.x -> newX++ x < to.x -> newX-- } } return PointProgression2D( this, Vector2D(newX, newY) ) } companion object { val basicDirections by lazy { Direction.values().map { it.vector } } enum class Direction(val vector: Vector2D) { UP(Vector2D(0, 1)), DOWN(Vector2D(0, -1)), RIGHT(Vector2D(1, 0)), LEFT(Vector2D(-1, 0)) } } } internal class PointIterator2D( startVector: Vector2D, private val endVectorInclusive: Vector2D, private val steps: Int ) : Iterator<Vector2D> { private var currentVector: Vector2D = startVector private var hasNext = currentVector != endVectorInclusive override fun hasNext() = hasNext override fun next(): Vector2D { val next = currentVector if (currentVector == endVectorInclusive) { hasNext = false } else { nextCurrentPoint() } return next } private fun nextCurrentPoint() { var newX = currentVector.x var newY = currentVector.y when { currentVector.x == endVectorInclusive.x -> { newY = stepOverY(steps) } abs(endVectorInclusive.x - currentVector.x) >= steps -> { newX = stepOverX(steps) } else -> { // more steps to take then left to endPointInclusive newX = endVectorInclusive.x // left over steps done over y newY = stepOverY(steps - abs(endVectorInclusive.x - currentVector.x)) } } currentVector = Vector2D(newX, newY) } private fun stepOverX(xSteps: Int): Int { return if (currentVector.x <= endVectorInclusive.x) { currentVector.x + xSteps } else { currentVector.x - xSteps } } private fun stepOverY(ySteps: Int): Int { return if (currentVector.y <= endVectorInclusive.y) { currentVector.y + ySteps } else { currentVector.y - ySteps } } } internal class PointProgression2D( override val start: Vector2D, override val endInclusive: Vector2D, private val steps: Int = 1 ) : Iterable<Vector2D>, ClosedRange<Vector2D> { override fun iterator(): Iterator<Vector2D> = PointIterator2D(start, endInclusive, steps) infix fun step(stepSteps: Int) = PointProgression2D(start, endInclusive, stepSteps) }
0
Kotlin
0
0
7e6241173959b9d838fa00f81fdeb39fdb3ef6fe
4,563
adventofcode-kotlin
MIT License
src/day01/Day01.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day01 import readInput import kotlin.math.max fun main() { val input = readInput(parent = "src/Day01", name = "Day01_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartOne(input: List<String>): Int { var max = 0 var curr = 0 input.forEach { foodItem -> if (foodItem.isEmpty()) { max = max(max, curr) curr = 0 } else { curr += foodItem.toInt() } } return max } private fun solvePartTwo(input: List<String>): Int { val topThreeCalories = IntArray(3) var curr = 0 input.forEach { foodItem -> if (foodItem.isEmpty()) { for (i in 0..2) { if (curr > topThreeCalories[i]) { if (i == 0) { topThreeCalories[2] = topThreeCalories[1] topThreeCalories[1] = topThreeCalories[0] } else if (i == 1) { topThreeCalories[2] = topThreeCalories[1] } topThreeCalories[i] = curr break } } curr = 0 } else { curr += foodItem.toInt() } } return topThreeCalories.sum() }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
1,284
advent-of-code-2022
Apache License 2.0
src/adventOfCode/day7Problem.kt
cunrein
159,861,371
false
null
package adventOfCode class CharGraph { var grid = arrayOf<Array<Int>>() var charMap = mutableMapOf<Char, Int>() init { var k = 0 for (i in 'A'..'Z') { var array = arrayOf<Int>() charMap.put(i, k) for (j in 'A'..'Z') { array += 0 } grid += array k++ } } fun addEdge(sourceVertex: Char, destinationVertex: Char) { // Add edge to source vertex / node. grid[charMap[sourceVertex]!!][charMap[destinationVertex]!!] = 1 //grid[charMap[destinationVertex]!!][charMap[sourceVertex]!!] = 1 } override fun toString(): String = StringBuffer().apply { for (i in 'A'..'Z') { val lst = mutableListOf<String>() for (j in 'A'..'Z') { if(grid[charMap[i]!!][charMap[j]!!] == 1) lst.add("$j") } if (lst.isNotEmpty()) { append("$i -> ") append(lst.joinToString(",", "[", "]\n")) } } }.toString() } fun createGraph(data: List<String>): CharGraph { return CharGraph().apply { data.forEach { val raw = it.split(" ") val source = raw[1].toCharArray()[0] val dest = raw[7].toCharArray()[0] addEdge(source, dest) } } } fun findPath(graph: CharGraph): String { val lsts = mutableSetOf<String>() var nodes = setOf<String>() for (i in 'A'..'Z') { val lstd = mutableSetOf<String>() for (j in 'A'..'Z') { if(graph.grid[graph.charMap[i]!!][graph.charMap[j]!!] == 1) lstd.add("$j") } if (lstd.isNotEmpty()) { lsts.add("$i") nodes = nodes.union(lsts.union(lstd)) } } println(nodes) // find start nodes val lst = graph.charMap.filter { graph.grid[it.value].sum() == 0 } return processNodes(lst.keys.sorted(), graph) } fun processNodes(nodes: List<Char>, graph: CharGraph): String { return StringBuilder().apply { nodes.forEach{ append(it) val lst = graph.charMap.filter { p -> graph.grid[graph.charMap[it]!!][p.value] == 1 } processNodes(lst.keys.sorted(), graph) } }.toString() } val day7Data = listOf("Step C must be finished before step A can begin,", "Step C must be finished before step F can begin.", "Step A must be finished before step B can begin.", "Step A must be finished before step D can begin.", "Step B must be finished before step E can begin.", "Step D must be finished before step E can begin.", "Step F must be finished before step E can begin.")
0
Kotlin
0
0
3488ccb200f993a84f1e9302eca3fe3977dbfcd9
2,798
ProblemOfTheDay
Apache License 2.0
src/main/kotlin/day14.kt
p88h
317,362,882
false
null
internal var counter = 0L internal data class FuzzyTree(var left: FuzzyTree?, var right: FuzzyTree?, var fuzzy: Boolean, var value: Long) { constructor(bits: Int = 36, data: Long = 0) : this(null, null, false, data) { if (bits > 0) { left = FuzzyTree(bits - 1, data) fuzzy = true } } fun write(mask: CharSequence, addr: Long, data: Long, pos: Int = 0) { if (pos < mask.length) { when (mask[pos]) { 'X' -> { left?.write(mask, addr, data, pos + 1) if (!fuzzy) right?.write(mask, addr, data, pos + 1) } '1' -> { defuzz() right!!.write(mask, addr, data, pos + 1) } '0' -> { defuzz() val bit = addr and (1L shl (35 - pos)) if (bit != 0L) { right!!.write(mask, addr, data, pos + 1) } else { left!!.write(mask, addr, data, pos + 1) } } } } else { value = data counter += 1 } } fun defuzz() { if (fuzzy) { right = left!!.copy() fuzzy = false } } fun copy(): FuzzyTree { var leftCopy = left?.copy() var rightCopy = if (fuzzy) leftCopy else right?.copy() return FuzzyTree(leftCopy, rightCopy, fuzzy, value) } fun dump(bits: Int = 36, prefix: String = "") { if (bits > 0) { if (fuzzy) { left!!.dump(bits - 1, prefix + "X") } else { left?.dump(bits - 1, prefix + "0") right?.dump(bits - 1, prefix + "1") } } else { println("$prefix: $value") } } fun sum(bits: Int = 36): Long { if (bits > 0) { if (fuzzy) { return 2 * left!!.sum(bits - 1) } else { var rsum = right?.sum( bits -1 ) ?: 0L return rsum + left!!.sum( bits - 1) } } else { return value } } } fun main(args: Array<String>) { val fmt = "([a-z]+)\\[?([0-9]+)?\\]?\\s=\\s([0-9X]+)".toRegex() var fuzz = "000000000000000000000000000000000000" var mask = 0L var bits = 0L var memm = Array(65536) { 0L } var tree = FuzzyTree() allLines(args, "day14.in").toList().forEach { fmt.matchEntire(it)?.destructured?.let { (cmd, addr, value) -> //println("$cmd $addr $value") when (cmd) { "mask" -> { mask = value.replace('0', '1').replace('X', '0').toLong(2) bits = value.replace('X', '0').toLong(2) fuzz = value } "mem" -> { val num = value.toLong() val masked = (num - (num and mask)) or bits memm[addr.toInt()] = masked tree.write(fuzz, addr.toLong(), num) } } //tree.dump() } } println(memm.sum()) println(tree.sum()) println(counter) }
0
Kotlin
0
5
846ad4a978823563b2910c743056d44552a4b172
3,282
aoc2020
The Unlicense
src/Day08.kt
chasegn
573,224,944
false
{"Kotlin": 29978}
/** * Day 08 for Advent of Code 2022 * https://adventofcode.com/2022/day/8 */ class Day08 : Day { override val inputFileName: String = "Day08" // override val test1Expected: Int? = null override val test1Expected: Int = 21 // override val test2Expected: Int? = null override val test2Expected: Int = 8 /** * Accepted solution: 1711 */ override fun part1(input: List<String>): Int { val trees = buildTreeGrid(input) var result = 0 for (i in 1 until trees.size-1) { for (j in 1 until trees.size-1) { // print("$i,$j: ${trees[i]!![j]}") if (isVisible(trees, i, j)) { result++ // print(" vis") } // print("\n") } } // print("\n") return result + ((trees[0]!!.size - 1)*2 + (trees.size - 1)*2) } /** * Accepted solution: 301392 */ override fun part2(input: List<String>): Int { val trees = buildTreeGrid(input) var max = 0 for (i in trees.indices) { for (j in trees.indices) { val score = scenicValue(trees, i, j) max = max.coerceAtLeast(score) } } return max } private fun buildTreeGrid(input: List<String>): Array<Array<Int>?> { val trees = arrayOfNulls<Array<Int>>(input.size) input.forEachIndexed { idx, line -> trees[idx] = line.toCharArray().map { it.digitToInt() }.toTypedArray() } return trees } private fun isVisible(trees: Array<Array<Int>?>, x: Int, y: Int): Boolean { val curHeight = trees[x]!![y] // quick check if neighbors are all taller var blockedNorth = trees[x-1]!![y] >= curHeight var blockedWest = trees[x]!![y-1] >= curHeight var blockedEast = trees[x]!![y+1] >= curHeight var blockedSouth = trees[x+1]!![y] >= curHeight // check north (--x) if (!blockedNorth) { for (i in (x-1) downTo 0) { if (trees[i]!![y] >= curHeight) { blockedNorth = true break } } } // check west (--y) if (!blockedWest) { for (i in (y-1)downTo 0) { if (trees[x]!![i] >= curHeight) { blockedWest = true break } } } // check east (y++) if (!blockedEast) { for (i in (y+1) until trees.size) { if (trees[x]!![i] >= curHeight) { blockedEast = true break } } } // check south (x++) if (!blockedSouth) { for (i in (x+1) until trees.size) { if (trees[i]!![y] >= curHeight) { blockedSouth = true break } } } // can exit early if any ONE direction fails return !blockedNorth || !blockedWest || !blockedEast || !blockedSouth } private fun scenicValue(trees: Array<Array<Int>?>, x: Int, y: Int): Int { val curHeight = trees[x]!![y] var scoreN = 0 var scoreW = 0 var scoreE = 0 var scoreS = 0 for (i in (x-1) downTo 0) { scoreN++ if (trees[i]!![y] >= curHeight) { break } } for (i in (y-1) downTo 0) { scoreW++ if (trees[x]!![i] >= curHeight) { break } } for (i in (y+1) until trees.size) { scoreE++ if (trees[x]!![i] >= curHeight) { break } } for (i in (x+1) until trees.size) { scoreS++ if (trees[i]!![y] >= curHeight) { break } } return scoreN * scoreW * scoreE * scoreS } }
0
Kotlin
0
0
2b9a91f083a83aa474fad64f73758b363e8a7ad6
4,044
advent-of-code-2022
Apache License 2.0
Collections/Sequences/src/Task.kt
diskostu
554,658,487
false
{"Kotlin": 36179}
// Find the most expensive product among all the delivered products // ordered by the customer. Use `Order.isDelivered` flag. fun findMostExpensiveProductBy(customer: Customer): Product? { val ordersAsSequence = customer.orders.asSequence() return ordersAsSequence .filter { it.isDelivered } .flatMap { it.products } .maxByOrNull { it.price } } // Count the amount of times a product was ordered. // Note that a customer may order the same product several times. fun Shop.getNumberOfTimesProductWasOrdered(product: Product): Int { return customers.asSequence() .flatMap { it.orders } .flatMap { it.products } .count { it == product } } fun main() { // demo code to find the solutions val shop = createSampleShop() // task 1 val mostExpensiveDeliveredProduct = findMostExpensiveProductBy(shop.customers[0]) println("mostExpensiveDeliveredProduct = $mostExpensiveDeliveredProduct") // task 2 val product3 = shop.customers .flatMap { it.orders } .flatMap { it.products } .first { it.name == "product 3" } val allProduct3Count = shop.getNumberOfTimesProductWasOrdered(product3) println("allProduct3Count = $allProduct3Count") } fun createSampleShop(): Shop { // create some sample entities val product1 = Product("product 1", 1.0) val product2 = Product("product 2", 2.0) val product3 = Product("product 3", 3.0) val product4 = Product("product 4", 4.0) val product5 = Product("product 5", 5.0) val order1 = Order(listOf(product1, product3), false) val order2 = Order(listOf(product2, product3), true) val order3 = Order(listOf(product1, product3, product4), true) val customer1 = Customer( name = "custumer1", city = City("Berlin"), orders = listOf(order1, order3) ) val customer2 = Customer( name = "custumer2", city = City("Hamburg"), orders = listOf(order2) ) return Shop("myShop", listOf(customer1, customer2)) }
0
Kotlin
0
0
3cad6559e1add8d202e15501165e2aca0ee82168
2,047
Kotlin_Koans
MIT License
src/main/kotlin/d24/d24.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d24 import readInput import java.lang.IllegalArgumentException data class State(val x:Int, val y:Int, val time:Int) { var prev : State? = null } fun printValley(valley : List<Array<Square>>) { for (line in valley) { for (sq in line) print(sq.char) println() } } fun printValley(valley : List<Array<Square>>, x:Int, y:Int) { for (line in valley.withIndex()) { for (sq in line.value.withIndex()) { if (x == sq.index && y==line.index) if (sq.value.isFree) print('E') else print('ø') else print(sq.value.char) } println() } } fun part1(input: List<String>): Int { val valley = readPuzzle(input) blizzards.add(valley) val x = valley[0].withIndex().first { it.value.isFree }.index val y = 0 return dijkstra(x, y, 0, valley.size - 1)?.time ?: -1 } fun testEvolve (input: List<String>) { var valley = readPuzzle(input) blizzards.add(valley) repeat(7) { println("round $it") for (line in valley) { for (sq in line) print(sq.char) println() } valley = evolve(it + 1) } } private fun dijkstra(x: Int, y: Int, t0: Int, targetY: Int): State? { val queue = ArrayDeque<State>() val visited = mutableSetOf<State>() queue.add(State(x, y, t0)) while (queue.isNotEmpty()) { val state = queue.removeFirst() if (state in visited) continue visited.add(state) val (xp, yp, t) = state if (yp == targetY) { println("***********************************************************************") var st: State? = state while (st != null) { printValley(evolve(st.time), st.x, st.y) st = st.prev } return state } val valley = evolve(t + 1) if (valley[yp][xp - 1].isFree) queue.add(State(xp - 1, yp, t + 1).apply { prev = state }) if (valley[yp][xp + 1].isFree) queue.add(State(xp + 1, yp, t + 1).apply { prev = state }) if (yp > 0 && valley[yp - 1][xp].isFree) queue.add(State(xp, yp - 1, t + 1).apply { prev = state }) if (yp < valley.size - 1 && valley[yp + 1][xp].isFree) queue.add(State(xp, yp + 1, t + 1).apply { prev = state }) if (valley[yp][xp].isFree) queue.add(State(xp, yp, t + 1).apply { prev = state }) } return null } fun part2(input: List<String>): Int { val valley = readPuzzle(input) blizzards.add(valley) val x = valley[0].withIndex().first { it.value.isFree }.index val y = 0 val down = dijkstra(x, y, 0, valley.size - 1)!! val up = dijkstra(down.x, down.y, down.time, 0)!! val goal = dijkstra(up.x, up.y, up.time, valley.size - 1)!! return goal.time } val blizzards = mutableListOf<List<Array<Square>>>() val wall = Square(wall = true) fun evolve(time: Int): List<Array<Square>> { if (blizzards.size > time) return blizzards[time] assert(time == blizzards.size) val valley = blizzards[time-1] val res = ArrayList<Array<Square>>(valley.size) val lastY = valley.size - 2 val lastX = valley[0].size - 2 res.add(valley[0]) for (y in 1..lastY) { val line = Array(valley[y].size) { Square() } line[0] = wall line[lastX + 1] = wall for (x in 1..lastX) { line[x].down = if (y != 1) valley[y - 1][x].down else valley[lastY][x].down line[x].up = if (y != lastY) valley[y + 1][x].up else valley[1][x].up line[x].left = if (x != lastX) valley[y][x + 1].left else valley[y][1].left line[x].right = if (x != 1) valley[y][x - 1].right else valley[y][lastX].right } res.add(line) } res.add(valley.last()) blizzards.add(res) println("Time=$time") printValley(res) return res } data class Square( var left: Boolean = false, var down: Boolean = false, var right: Boolean = false, var up: Boolean = false, var wall: Boolean = false ) { val isFree get() = !(left || down || right || up || wall) private val count get() = (if (left) 1 else 0) + (if (right) 1 else 0) + (if (down) 1 else 0) + (if (up) 1 else 0) val char get() = if (wall) '#' else if (count == 0) '.' else if (count > 1) '0' + count else if (left) '<' else if (right) '>' else if (up) '^' else 'v' } fun readPuzzle(input: List<String>): List<Array<Square>> { val res = mutableListOf<Array<Square>>() for (line in input) { if (line.isBlank()) continue res.add(line.map { when (it) { '#' -> Square(wall = true) '>' -> Square(right = true) '<' -> Square(left = true) '^' -> Square(up = true) 'v' -> Square(down = true) '.' -> Square() else -> throw IllegalArgumentException("unknown square $it") } }.toTypedArray()) } return res } fun main() { //val input = readInput("d24/test") //val input = readInput("d24/test1") val input = readInput("d24/input1") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
5,589
aoc2022
Creative Commons Zero v1.0 Universal
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[120]三角形最小路径和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个三角形 triangle ,找出自顶向下的最小路径和。 // // 每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。也就是说,如果 //正位于当前行的下标 i ,那么下一步可以移动到下一行的下标 i 或 i + 1 。 // // // // 示例 1: // // //输入:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] //输出:11 //解释:如下面简图所示: // 2 // 3 4 // 6 5 7 //4 1 8 3 //自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 // // // 示例 2: // // //输入:triangle = [[-10]] //输出:-10 // // // // // 提示: // // // 1 <= triangle.length <= 200 // triangle[0].length == 1 // triangle[i].length == triangle[i - 1].length + 1 // -104 <= triangle[i][j] <= 104 // // // // // 进阶: // // // 你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题吗? // // Related Topics 数组 动态规划 // 👍 898 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun minimumTotal(triangle: List<List<Int>>): Int { //经典动态规划题目 // 方法一: //动态规划 dp[i][j] 表示从点 (i, j)(i,j) 到底边的最小路径和 //时间复杂度 O(n^2) 空间复杂度 O(n^2) //相邻结点:与(i, j) 点相邻的结点为 (i + 1, j) 和 (i + 1, j + 1)。 //状态转移 dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j] /* var len = triangle.size val dp = Array(len + 1) { IntArray(len + 1) } //自顶向上 for (i in len-1 downTo 0){ for (j in 0 .. i){ dp[i][j] = Math.min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j] } } return dp[0][0]*/ //方法二 优化 //上面解法计算 dp[i][j]dp[i][j] 时,只用到了下一行的 dp[i + 1][j]dp[i+1][j] 和 dp[i + 1][j + 1]dp[i+1][j+1]。 //因此 dp 数组不需要定义 N 行,只要定义 1 行也就是一位数组 //状态转移 dp[j]=min(dp[j],dp[j+1])+triangle[i][j] //时间复杂度 O(n^2) 空间复杂度 O(n) var len = triangle.size val dp = IntArray(len + 1) //自顶向上 for (i in len-1 downTo 0){ for (j in 0 .. i){ dp[j] = Math.min(dp[j],dp[j+1])+triangle[i][j] } } return dp[0] } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,629
MyLeetCode
Apache License 2.0
src/main/kotlin/days/Day1.kt
andilau
726,429,411
false
{"Kotlin": 37060}
package days @AdventOfCodePuzzle( name = "Trebuchet?!", url = "https://adventofcode.com/2023/day/1", date = Date(day = 1, year = 2023) ) class Day1(private val input: List<String>) : Puzzle { override fun partOne(): Int = input .map { line -> Pair(line.firstDigit, line.lastDigit) } .sumOf { it.first * 10 + it.second } override fun partTwo(): Int = input .map { line -> Pair(line.firstDigitOrNumber, line.lastDigitOrNumber) } .sumOf { it.first * 10 + it.second } private val String.firstDigit get() = first { it.isDigit() }.digitToInt() private val String.lastDigit get() = last { it.isDigit() }.digitToInt() private val String.firstDigitOrNumber get() = windowedSequence(this.length, 1, true) .firstNotNullOfOrNull { substring -> when { substring.first().isDigit() -> substring.first().digitToInt() else -> letterToDigit.keys.firstOrNull() { substring.startsWith(it) }?.let { letterToDigit[it] } } } ?: error("Contains no number: $this") private val String.lastDigitOrNumber get() = indices.asSequence() .map { this.substring(0..<length - it) } .firstNotNullOfOrNull { substring -> when { substring.last().isDigit() -> substring.last().digitToInt() else -> letterToDigit.keys.firstOrNull() { substring.endsWith(it) }?.let { letterToDigit[it] } } } ?: error("Contains no number: $this") private val letterToDigit = listOf( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" ).mapIndexed { index, s -> s to index + 1 }.toMap() }
3
Kotlin
0
0
9a1f13a9815ab42d7fd1d9e6048085038d26da90
1,824
advent-of-code-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/domnikl/algorithms/select/QuickSelect.kt
domnikl
231,452,742
false
null
package org.domnikl.algorithms.select import kotlin.random.Random fun <T : Comparable<T>> Array<T>.quickSelect(select: Int): T { return this.quickSelect(0, this.size - 1, select) } private fun <T : Comparable<T>> Array<T>.quickSelect(low: Int, high: Int, select: Int): T { require(low <= high) { "low: $low is smaller than high: $high" } val pivotIndex = this.partition(low, high) return when { pivotIndex == select -> { this[pivotIndex] } select < pivotIndex -> { this.quickSelect(low, pivotIndex - 1, select) } else -> { this.quickSelect(pivotIndex + 1, high, select) } } } private fun <T : Comparable<T>> Array<T>.partition(low: Int, high: Int): Int { require(low <= high) { "low: $low is smaller than high: $high" } var pivotIndex = Random.nextInt(low, high + 1) val pivot = this[pivotIndex] var i = low var j = high while (true) { while (this[i] < pivot) { i++ } while (this[j] > pivot) { j-- } if (i >= j) { return pivotIndex } this[i] = this[j].also { this[j] = this[i] } if (pivotIndex == i) { pivotIndex = j } else if (pivotIndex == j) { pivotIndex = i } } }
5
Kotlin
3
13
3b2c191876e58415d8221e511e6151a8747d15dc
1,377
algorithms-and-data-structures
Apache License 2.0
src/Day04/Day04.kt
AllePilli
572,859,920
false
{"Kotlin": 47397}
package Day04 import checkAndPrint import measureAndPrintTimeMillis import readInput fun main() { fun List<String>.prepareInput(): List<Pair<IntRange, IntRange>> = map { line -> line.split(",") .map { part -> part.split("-") .let { (first, second) -> first.toInt()..second.toInt() } } .let { (first, second) -> first to second } } fun part1(input: List<Pair<IntRange, IntRange>>): Int = input.count { (first, second) -> val (longest, shortest) = if (first.last - first.first > second.last - second.first) first to second else second to first longest.first <= shortest.first && longest.last >= shortest.last } fun part2(input: List<Pair<IntRange, IntRange>>): Int = input.count { (first, second) -> val spots = first.toSet() second.firstOrNull { spot -> spot in spots } != null } val testInput = readInput("Day04_test").prepareInput() check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04").prepareInput() measureAndPrintTimeMillis { checkAndPrint(part1(input), 450) } measureAndPrintTimeMillis { checkAndPrint(part2(input), 837) } }
0
Kotlin
0
0
614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643
1,281
AdventOfCode2022
Apache License 2.0
2022/src/Day04.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src fun main() { fun part1(input: List<String>): Int { return input.flatMap { it.split(",") } .asSequence() .map { it.split("-") } .map { it[0].toInt()..it[1].toInt() } .chunked(2) .map { (it[0] intersect it[1]).containsAll(it[0].toList()) || (it[0] intersect it[1]).containsAll(it[1].toList()) } .filter { it } .count() } fun part2(input: List<String>): Int { return input.flatMap { it.split(",") } .asSequence() .map { it.split("-") } .map { it[0].toInt()..it[1].toInt() } .chunked(2) .map { it[0].any { iter -> iter in it[1] } || it[1].any { iter -> iter in it[0] } } .filter { it } .count() } val input = readInput("input4") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
901
AoC
Apache License 2.0
src/main/kotlin/g1501_1600/s1591_strange_printer_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1591_strange_printer_ii // #Hard #Array #Matrix #Graph #Topological_Sort // #2023_06_14_Time_321_ms_(100.00%)_Space_38.7_MB_(100.00%) class Solution { fun isPrintable(targetGrid: Array<IntArray>): Boolean { val colorBound = Array(61) { IntArray(4) } val colors: MutableSet<Int> = HashSet() // prepare colorBound with Max and Min integer for later compare for (i in colorBound.indices) { for (j in colorBound[0].indices) { if (j == 0 || j == 1) { colorBound[i][j] = Int.MAX_VALUE } else { colorBound[i][j] = Int.MIN_VALUE } } } // find the color range for each color // each color i has a colorBound[i] with {min_i, min_j, max_i, max_j} for (i in targetGrid.indices) { for (j in targetGrid[0].indices) { colorBound[targetGrid[i][j]][0] = Math.min(colorBound[targetGrid[i][j]][0], i) colorBound[targetGrid[i][j]][1] = Math.min(colorBound[targetGrid[i][j]][1], j) colorBound[targetGrid[i][j]][2] = Math.max(colorBound[targetGrid[i][j]][2], i) colorBound[targetGrid[i][j]][3] = Math.max(colorBound[targetGrid[i][j]][3], j) colors.add(targetGrid[i][j]) } } val printed = BooleanArray(61) val visited = Array(targetGrid.size) { BooleanArray(targetGrid[0].size) } // DFS all the colors, skip the color already be printed for (color in colors) { if (printed[color]) { continue } if (!dfs(targetGrid, printed, colorBound, visited, color)) { return false } } // if all color has been printed, then return true return true } private fun dfs( targetGrid: Array<IntArray>, printed: BooleanArray, colorBound: Array<IntArray>, visited: Array<BooleanArray>, color: Int ): Boolean { printed[color] = true for (i in colorBound[color][0]..colorBound[color][2]) { for (j in colorBound[color][1]..colorBound[color][3]) { // if i, j is already visited, skip if (visited[i][j]) { continue } // if we find a different color, then check if the color is already printed, if so, // return false // otherwise, dfs the range of the new color if (targetGrid[i][j] != color) { if (printed[targetGrid[i][j]]) { return false } if (!dfs(targetGrid, printed, colorBound, visited, targetGrid[i][j])) { return false } } visited[i][j] = true } } return true } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,979
LeetCode-in-Kotlin
MIT License
kotlin/graphs/matchings/MaxGeneralMatchingV3.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.matchings import java.util.stream.IntStream // https://en.wikipedia.org/wiki/Blossom_algorithm in O(V^3) object MaxGeneralMatchingV3 { fun maxMatching(graph: Array<List<Integer>>): Int { val n = graph.size val match = IntArray(n) Arrays.fill(match, -1) val p = IntArray(n) for (i in 0 until n) { if (match[i] == -1) { var v = findPath(graph, match, p, i) while (v != -1) { val pv = p[v] val ppv = match[pv] match[v] = pv match[pv] = v v = ppv } } } return Arrays.stream(match).filter { x -> x !== -1 }.count() as Int / 2 } fun findPath(graph: Array<List<Integer>>, match: IntArray, p: IntArray, root: Int): Int { Arrays.fill(p, -1) val n = graph.size val bases: IntArray = IntStream.range(0, n).toArray() val used = BooleanArray(n) val q = IntArray(n) var qt = 0 used[root] = true q[qt++] = root for (qh in 0 until qt) { val u = q[qh] for (v in graph[u]) { if (bases[u] == bases[v] || match[u] == v) continue if (v == root || match[v] != -1 && p[match[v]] != -1) { val base = lca(match, bases, p, u, v) val blossom = BooleanArray(n) markPath(match, bases, blossom, p, u, base, v) markPath(match, bases, blossom, p, v, base, u) for (i in 0 until n) if (blossom[bases[i]]) { bases[i] = base if (!used[i]) { used[i] = true q[qt++] = i } } } else if (p[v] == -1) { p[v] = u if (match[v] == -1) return v v = match[v] used[v] = true q[qt++] = v } } } return -1 } fun markPath(match: IntArray, bases: IntArray, blossom: BooleanArray, p: IntArray, u: Int, base: Int, child: Int) { var u = u var child = child while (bases[u] != base) { blossom[bases[match[u]]] = true blossom[bases[u]] = blossom[bases[match[u]]] p[u] = child child = match[u] u = p[match[u]] } } fun lca(match: IntArray, base: IntArray, p: IntArray, a: Int, b: Int): Int { var a = a var b = b val used = BooleanArray(match.size) while (true) { a = base[a] used[a] = true if (match[a] == -1) break a = p[match[a]] } while (true) { b = base[b] if (used[b]) return b b = p[match[b]] } } // Usage example fun main(args: Array<String?>?) { val graph: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(4).toArray { _Dummy_.__Array__() } graph[0].add(1) graph[1].add(0) graph[2].add(1) graph[1].add(2) graph[2].add(0) graph[0].add(2) graph[3].add(0) graph[0].add(3) System.out.println(2 == maxMatching(graph)) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,418
codelibrary
The Unlicense
advent-of-code2015/src/main/kotlin/day11/Advent11.kt
REDNBLACK
128,669,137
false
null
package day11 import split /** --- Day 11: Corporate Policy --- Santa's previous password expired, and he needs help choosing a new one. To help him remember his new password after the old one expires, Santa has devised a method of coming up with a password based on the previous one. Corporate policy dictates that passwords must be exactly eight lowercase letters (for security reasons), so he finds his new password by incrementing his old password string repeatedly until it is valid. Incrementing is just like counting with numbers: xx, xy, xz, ya, yb, and so on. Increase the rightmost letter one step; if it was z, it wraps around to a, and repeat with the next letter to the left until one doesn't wrap around. Unfortunately for Santa, a new Security-Elf recently started, and he has imposed some additional password requirements: Passwords must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. Passwords may not contain the letters i, o, or l, as these letters can be mistaken for other characters and are therefore confusing. Passwords must contain at least two different, non-overlapping pairs of letters, like aa, bb, or zz. For example: hijklmmn meets the first requirement (because it contains the straight hij) but fails the second requirement requirement (because it contains i and l). abbceffg meets the third requirement (because it repeats bb and ff) but fails the first requirement. abbcegjk fails the third requirement, because it only has one double letter (bb). The next password after abcdefgh is <PASSWORD>aa. The next password after ghijklmn is <PASSWORD>cc, because you eventually skip all the passwords that start with ghi..., since i is not allowed. Given Santa's current password (your puzzle input), what should his next password be? */ fun main(args: Array<String>) { println(generateNewPassword("abcdefgh") == "abcdffaa") println(generateNewPassword("ghijklmn") == "<PASSWORD>cc") println(generateNewPassword("vzbxkghb")) println(generateNewPassword("vzbxxyzz")) } fun generateNewPassword(oldPass: String): String { val alphabet = ('a'..'z').toList() fun String.isGoodEnough() = listOf('i', 'o', 'l').count { it in this } == 0 && alphabet.split(3).map { it.joinToString("") }.count { it in this } > 0 && alphabet.map { it.toString().repeat(2) }.count { it in this } >= 2 fun String.incrementWithWrap(): String { fun Char.incrementWithWrap() = if (this == 'z') 'a' to true else this + 1 to false val charArray = toCharArray() for (i in this.length - 1 downTo 0) { val (newValue, isWrapped) = charArray[i].incrementWithWrap() charArray[i] = newValue if (!isWrapped) break } return charArray.joinToString("") } tailrec fun loop(pass: String): String { val newPass = pass.incrementWithWrap() if (newPass.isGoodEnough()) return newPass return loop(newPass) } return loop(oldPass) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
3,082
courses
MIT License
src/main/kotlin/aoc2022/Day17.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import Point import readInput import kotlin.math.max private enum class RockShape(val points: Collection<Point>) { Minus(setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0))), Plus(setOf(Point(1, 0), Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2))), L(setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2))), I(setOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3))), Block(setOf(Point(0, 0), Point(0, 1), Point(1, 0), Point(1, 1))); companion object { val sequence = sequence { while (true) { yield(Minus) yield(Plus) yield(L) yield(I) yield(Block) } } } } private class Rock(val shape: RockShape, top: Int) { var points = shape.points.map { it + Point(2, top + 3) } private set fun moveLeft(blocked: Collection<Point>) { val tmp = points.map { it.move(-1, 0) } if (tmp.all { it.x >= 0 && !blocked.contains(it) }) { this.points = tmp } } fun moveRight(blocked: Collection<Point>) { val tmp = points.map { it.move(1, 0) } if (tmp.all { it.x < 7 && !blocked.contains(it) }) { this.points = tmp } } fun moveDown(blocked: Collection<Point>): Boolean { val tmp = points.map { it.move(0, -1) } val allowed = tmp.all { it.y >= 0 && !blocked.contains(it) } if (allowed) { this.points = tmp } return allowed } } private data class Pattern(val jetIndex: Int, val rockShape: RockShape, val topPoints: List<Int>) { var offset = 0L var rocks = 0L } private fun getHeight(input: List<String>, maxRocks: Long): Long { val jetIterator = sequence { while (true) { yieldAll(input.first().toCharArray().withIndex().toList()) } }.iterator() val topPoints = IntArray(7) { -1 } var blockedPoints = mutableSetOf<Point>() var offset = 0L var rocks = 0L var missingRocks = maxRocks val patterns = mutableSetOf<Pattern>() var patternFound = false RockShape.sequence.takeWhile { missingRocks > 0 }.forEach { shape -> missingRocks-- rocks++ val rock = Rock(shape, topPoints.max() + 1) var moved = true var jetIndex = -1 while (moved) { val nextJet = jetIterator.next() jetIndex = nextJet.index if (nextJet.value == '>') { rock.moveRight(blockedPoints) } else { rock.moveLeft(blockedPoints) } moved = rock.moveDown(blockedPoints) } blockedPoints.addAll(rock.points) for (p in rock.points) { topPoints[p.x] = max(topPoints[p.x], p.y) } if (!patternFound) { val min = topPoints.min() if (min > 2) { val pattern = Pattern(jetIndex, rock.shape, topPoints.clone().asList()) pattern.offset = offset pattern.rocks = rocks if (!patterns.add(pattern)) { val existing = patterns.find { it == pattern }!! val rocksDiff = rocks - existing.rocks val offsetDiff = offset - existing.offset val repeats = (missingRocks) / rocksDiff missingRocks -= (rocksDiff * repeats) offset += offsetDiff * repeats patternFound = true } else { offset += min for (i in topPoints.indices) { topPoints[i] = topPoints[i] - min } blockedPoints = blockedPoints.map { it.move(0, -min) }.filter { it.y >= 0 }.toMutableSet() } } } } return topPoints.max() + offset + 1 } private fun part1(input: List<String>) = getHeight(input, 2022L).toInt() private fun part2(input: List<String>) = getHeight(input, 1000000000000L) fun main() { val testInput = readInput("Day17_test", 2022) check(part1(testInput) == 3068) check(part2(testInput) == 1514285714288L) val input = readInput("Day17", 2022) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
4,329
adventOfCode
Apache License 2.0
day05/src/main/kotlin/Main.kt
ickybodclay
159,694,344
false
null
import java.io.File fun main() { val input = File(ClassLoader.getSystemResource("input.txt").file) // Write solution here! input.readLines().map { line -> val polymerStr = getReactingPolymer(line) println("polymer string = $polymerStr") println("[part1] polymer count = ${polymerStr.length}") var minUnit = ' ' var minLength = Int.MAX_VALUE val alphabet = "abcdefghijklmnopqrstuvwxyz" alphabet.forEach { c -> val testPolymer = line.replace("$c", "", true) //println ("Removing $c : $testPolymer") val resultPolymer = getReactingPolymer(testPolymer) if (resultPolymer.length < minLength) { minUnit = c minLength = resultPolymer.length } } println("[part2] shortest polymer = $minLength by removing $minUnit") } } fun getReactingPolymer(polymer: String) : String { var polymerStr = "" var prevChar = ' ' polymer.forEach { c -> if ((c.isUpperCase() && c.toLowerCase() == prevChar) || (prevChar.isUpperCase() && prevChar.toLowerCase() == c)) { //println("Reaction from $prevChar + $c, removing") polymerStr = polymerStr.substring(0, polymerStr.length - 1) prevChar = if (polymerStr.isNotEmpty()) polymerStr.last() else ' ' } else { polymerStr += c prevChar = c } } return polymerStr }
0
Kotlin
0
0
9a055c79d261235cec3093f19f6828997b7a5fba
1,477
aoc2018
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2021/day18/Day18.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day18 import com.github.michaelbull.advent2021.Puzzle object Day18 : Puzzle<Sequence<SnailfishNumber>, Int>(day = 18) { override fun parse(input: Sequence<String>): Sequence<SnailfishNumber> { return input.map(String::toSnailfishNumber) } override fun solutions() = listOf( ::part1, ::part2 ) fun part1(numbers: Sequence<SnailfishNumber>): Int { return numbers.reduce(SnailfishNumber::plus).magnitude } fun part2(numbers: Sequence<SnailfishNumber>): Int { val list = numbers.toList() val magnitudeSums = list.flatMap { list.mapUniqueMagnitudeSums(it) } return magnitudeSums.maxOrNull()!! } private fun List<SnailfishNumber>.mapUniqueMagnitudeSums(other: SnailfishNumber): List<Int> { return filterUnique(other).map { it.sumMagnitude(other) } } private fun List<SnailfishNumber>.filterUnique(other: SnailfishNumber): List<SnailfishNumber> { return filter { it != other } } private fun SnailfishNumber.sumMagnitude(other: SnailfishNumber): Int { return (this + other).magnitude } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
1,167
advent-2021
ISC License
src/Day18.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private data class Cube( val x: Int, val y: Int, val z: Int ) private fun droplet(input: List<String>): Set<Cube> { return input.map { line -> line.split(",") .map { it.toInt() } }.map { Cube(it[0], it[1], it[2]) }.toSet() } private fun surfaceArea(droplet: Set<Cube>): Int { val xSurface = mutableMapOf<Triple<Int, Int, Int>, Int>() val ySurface = mutableMapOf<Triple<Int, Int, Int>, Int>() val zSurface = mutableMapOf<Triple<Int, Int, Int>, Int>() for (cube in droplet) { xSurface[Triple(cube.x, cube.y, cube.z)] = xSurface.getOrDefault(Triple(cube.x, cube.y, cube.z), 0) + 1 xSurface[Triple(cube.x + 1, cube.y, cube.z)] = xSurface.getOrDefault(Triple(cube.x + 1, cube.y, cube.z), 0) + 1 ySurface[Triple(cube.x, cube.y, cube.z)] = ySurface.getOrDefault(Triple(cube.x, cube.y, cube.z), 0) + 1 ySurface[Triple(cube.x, cube.y + 1, cube.z)] = ySurface.getOrDefault(Triple(cube.x, cube.y + 1, cube.z), 0) + 1 zSurface[Triple(cube.x, cube.y, cube.z)] = zSurface.getOrDefault(Triple(cube.x, cube.y, cube.z), 0) + 1 zSurface[Triple(cube.x, cube.y, cube.z + 1)] = zSurface.getOrDefault(Triple(cube.x, cube.y, cube.z + 1), 0) + 1 } return xSurface.count { it.value == 1 } + ySurface.count { it.value == 1 } + zSurface.count { it.value == 1 } } private fun part1(input: List<String>): Int { val droplet = droplet(input) return surfaceArea(droplet) } private class NeighbourCubeGenerator( private val xRange: IntRange, private val yRange: IntRange, private val zRange: IntRange ) { private val neighbourOffsets = listOf<Triple<Int, Int, Int>>( Triple(1, 0, 0), Triple(-1, 0, 0), Triple(0, 1, 0), Triple(0, -1, 0), Triple(0, 0, 1), Triple(0, 0, -1) ) fun generate(cube: Cube): List<Cube> { val newCubes = mutableListOf<Cube>() for (offset in neighbourOffsets) { val newCube = Cube(cube.x + offset.first, cube.y + offset.second, cube.z + offset.third) if (xRange.contains(newCube.x) && yRange.contains(newCube.y) && zRange.contains(newCube.z)) { newCubes.add(newCube) } } return newCubes } } private fun part2(input: List<String>): Int { val droplet = droplet(input) // boundary is 1 unit more than the edge of the droplet, so we can flood the outside val boundaryMinX = droplet.minOf { it.x } - 1 val boundaryMaxX = droplet.maxOf { it.x } + 1 val boundaryMinY = droplet.minOf { it.y } - 1 val boundaryMaxY = droplet.maxOf { it.y } + 1 val boundaryMinZ = droplet.minOf { it.z } - 1 val boundaryMaxZ = droplet.maxOf { it.z } + 1 val neighbourCubeGenerator = NeighbourCubeGenerator( boundaryMinX..boundaryMaxX, boundaryMinY..boundaryMaxY, boundaryMinZ..boundaryMaxZ, ) val stackToFlood = mutableSetOf(Cube(boundaryMinX, boundaryMinY, boundaryMinZ)) val floodedPositions = mutableSetOf<Cube>() var count = 0 do { val cube = stackToFlood.elementAt(0) stackToFlood.remove(cube) if (!droplet.contains(cube)) { floodedPositions.add(cube) for (neighbourCube in neighbourCubeGenerator.generate(cube)) { if (!floodedPositions.contains(neighbourCube) && !stackToFlood.contains(neighbourCube)) { stackToFlood.add(neighbourCube) } } } count++ } while (stackToFlood.isNotEmpty()) val allCubes = mutableSetOf<Cube>() (boundaryMinX..boundaryMaxX).forEach { x -> (boundaryMinY..boundaryMaxY).forEach { y -> (boundaryMinZ..boundaryMaxZ).forEach { z -> allCubes.add(Cube(x, y, z)) } } } val innerCubes = allCubes - floodedPositions - droplet return surfaceArea(droplet + innerCubes) } fun main() { val input = readInput("Day18") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
4,115
advent-of-code-2022
Apache License 2.0
src/main/kotlin/logic.kt
Shpota
283,824,850
false
null
package com.sashashpota import com.sashashpota.H.* import java.math.BigDecimal import java.math.MathContext import java.math.RoundingMode import java.math.RoundingMode.HALF_UP val basePredicates = listOf<Pair<(Input) -> Boolean, H>>( { i: Input -> i.a && i.b && !i.c } to M, { i: Input -> i.a && i.b && i.c } to P, { i: Input -> !i.a && i.b && i.c } to T ) val customPredicates2 = listOf<Pair<(Input) -> Boolean, H>>( { i: Input -> i.a && i.b && !i.c } to T, { i: Input -> i.a && !i.b && i.c } to M ) + basePredicates val baseFormulas = mapOf<H, (Input) -> BigDecimal>( M to { i: Input -> (i.d + ((i.d * i.e.toBigDecimal()).divide(BigDecimal("10")))) .stripTrailingZeros() }, P to { i: Input -> (i.d + ((i.d * (i.e - i.f).toBigDecimal()).divide( BigDecimal("25.5"), 10, HALF_UP))) .stripTrailingZeros() }, T to { i: Input -> (i.d - ((i.d * i.f.toBigDecimal()).divide(BigDecimal("30"), 10, HALF_UP))) .stripTrailingZeros() } ) val customFormulas1 = baseFormulas + (P to { i: Input -> (2.toBigDecimal() * i.d + ((i.d * i.e.toBigDecimal()).divide(BigDecimal("100")))) .stripTrailingZeros() }) val customFormulas2 = baseFormulas + (M to { i: Input -> (i.f.toBigDecimal() + i.d + (i.d * i.e.toBigDecimal().divide(BigDecimal("100")))) .stripTrailingZeros() }) fun execute( input: Input, predicates: List<Pair<(Input) -> Boolean, H>>, formulas: Map<H, (Input) -> BigDecimal> ): Result { for ((predicate, h) in predicates) { if (predicate(input)) { return Result(h, formulas[h]!!(input)) } } throw UnsupportedOperationException() }
0
Kotlin
0
0
984a3b6a4f69df59bb5792a20da03cbb593af509
1,712
abcdator
Apache License 2.0
src/day7/day07.kt
mmilenkov
573,101,780
false
{"Kotlin": 9427}
package day7 import readLines fun main() { val pattern = Regex("""[$] cd (.*)|(\d+).*""") fun directorySizes(data: List<String>) = buildMap { put("", 0) var currentDirectory = "" for (line in data) { val result = pattern.matchEntire(line) ?: continue // Nothing matches skip result.groups[1]?.value?.let {directory -> //These match part one of the regex. Namely this is a cd currentDirectory = when (directory) { "/" -> "" //Root directory ".." -> currentDirectory.substringBeforeLast("/","") // Clear the current directory else -> if (currentDirectory.isEmpty()) directory else "$currentDirectory/$directory" // Simplifies the above case or it would be goto empty string } } ?: result.groups[2]?.value?.toIntOrNull()?.let { size -> // These match part two of the regex namely this counts file size var directory = currentDirectory while (true) { put(directory, getOrElse(directory) { 0 } + size) // If we don't have it we need to make sure we have some value if (directory.isEmpty()) break directory = directory.substringBeforeLast("/", "") } } } } fun part1() { val data = readLines("day7") println(directorySizes(data).values.sumOf { size -> if (size <= 100000) size else 0 }) } fun part2() { println(directorySizes(readLines("day7")).values .asSequence() .filter { 70000000 - (directorySizes(readLines("day7")).getValue("") - it) >= 30000000 } .min() ) } part1() part2() }
0
Kotlin
0
0
991df03f2dcffc9fa4596f6dbbc4953c95fcd17c
1,769
AdventOfCode2022
Apache License 2.0
src/main/kotlin/days/Day4.kt
nuudles
316,314,995
false
null
package days class Day4 : Day(4) { private fun getPassports(): List<Map<String, String>> = inputString .split("\n\n") .map { passport -> passport .split(" ", "\n") .fold(mutableMapOf()) { map, components -> components .split(":") .let { map[it.first().toString()] = it.last().toString() } map } } fun isValid(key: String, value: String): Boolean = when (key) { "byr" -> value.length == 4 && value.toIntOrNull()?.let { it in 1920..2002 } ?: false "iyr" -> value.length == 4 && value.toIntOrNull()?.let { it in 2010..2020 } ?: false "eyr" -> value.length == 4 && value.toIntOrNull()?.let { it in 2020..2030 } ?: false "hgt" -> Regex("""(\d+)(cm|in)""") .find(value) ?.let { result -> val (number, unit) = result.destructured return when (unit) { "cm" -> number.toInt() in 150..193 "in" -> number.toInt() in 59..76 else -> false } } ?: false "hcl" -> Regex("""#[0-9a-f]{6}""") .matches(value) "ecl" -> arrayOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(value) "pid" -> Regex("""\d{9}""") .matches(value) else -> true } override fun partOne(): Any { return getPassports() .count { passport -> passport.count { requiredFields.contains(it.key) } == requiredFields.size } } override fun partTwo(): Any { return getPassports() .count { passport -> requiredFields .count { field -> passport[field]?.let { isValid(field, it) } ?: false } == requiredFields.size } } companion object { private val requiredFields = arrayOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
2,400
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day25.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
import kotlin.math.log import kotlin.math.pow fun main() { val mapSNAFU = mapOf<Char, Int>('2' to 2, '1' to 1, '0' to 0, '-' to -1, '=' to -2) val SNAFUback = "=-012" fun SNAFU2Dec(input: String): Long{ var res: Long = 0 for ((place, elem) in input.reversed().withIndex()){ res += mapSNAFU.getOrDefault(elem, 0)*(5.toDouble().pow(place.toDouble()).toLong()) } // println("$input -> $res") return res } fun part1(input: List<String>){ println(input.sumOf { SNAFU2Dec(it) }) var res = input.sumOf { SNAFU2Dec(it) } var logR = log(res.toDouble(), 5.0) // while (logR > 0){ // println("$res $logR, ${res / 5.0.pow(logR.toInt().toDouble())} ${logR.toInt().toDouble()} ${(5.0).pow(logR.toInt().toDouble()).toLong()}") // res -= (5.0).pow(logR.toInt().toDouble()).toLong() // logR = log(res.toDouble(), 5.0) // } var i = 15 var resStr = "" while (res > 0){ var m = (res + 2L) % 5L res = (res + 2L) / 5L resStr += SNAFUback[m.toInt()] } println(resStr.reversed()) println(SNAFU2Dec(resStr.reversed())) } val testInput = readInput("Day25") part1(testInput) println(log(47045194.0, 5.0)) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
1,328
aoc22
Apache License 2.0
src/Day02.kt
k3vonk
573,555,443
false
{"Kotlin": 17347}
fun main() { val gameResponseScore = mapOf( "R" to 1, "P" to 2, "S" to 3 ) val gameResult = mapOf( "R" to "R" to 3, "R" to "P" to 6, "R" to "S" to 0, "P" to "R" to 0, "P" to "P" to 3, "P" to "S" to 6, "S" to "R" to 6, "S" to "P" to 0, "S" to "S" to 3 ) val player1Action = mapOf( "A" to "R", "B" to "P", "C" to "S" ) val player2Action = mapOf( "X" to "R", "Y" to "P", "Z" to "S" ) val part2Combo = mapOf( "R" to "Z" to "P", "R" to "Y" to "R", "R" to "X" to "S", "P" to "Z" to "S", "P" to "Y" to "P", "P" to "X" to "R", "S" to "Z" to "R", "S" to "Y" to "S", "S" to "X" to "P" ) fun part1(input: List<String>): Int { var score = 0 for (game in input) { val (player1, player2) = game.split(" ") val a1 = player1Action[player1]!! val a2 = player2Action[player2]!! val gameScore = gameResult[a1 to a2]!! + gameResponseScore[a2]!! score += gameScore } return score } fun part2(input: List<String>): Int { var score = 0 for (game in input) { val (player1, gameFutureState) = game.split(" ") val a1 = player1Action[player1]!! // figure out what player2 plays val a2 = part2Combo[a1 to gameFutureState]!! val gameScore = gameResult[a1 to a2]!! + gameResponseScore[a2]!! score += gameScore } return score } val input = readInput("Day02_test") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
68a42c5b8d67442524b40c0ce2e132898683da61
1,766
AOC-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/HappyString.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1415. The k-th Lexicographical String of All Happy Strings of Length n * @see <a href="https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/"> * Source</a> */ fun interface HappyString { operator fun invoke(n: Int, k: Int): String } class HappyStringDFS : HappyString { override operator fun invoke(n: Int, k: Int): String { val str = charArrayOf('a', 'b', 'c') val kArr = IntArray(1) kArr[0] = k return dfs(str, kArr, '0', 0, n) } private fun dfs(str: CharArray, k: IntArray, prev: Char, index: Int, n: Int): String { if (index == n) { k[0]-- } else { for (i in 0..2) { if (str[i] != prev) { val res = dfs(str, k, str[i], index + 1, n) if (k[0] == 0) return str[i].toString() + res } } } return "" } } class HappyStringMath : HappyString { override operator fun invoke(n: Int, k: Int): String { var kk = k var prem = 1 shl n - 1 if (kk > 3 * prem) { return "" } var ch = ('a' + (kk - 1) / prem).code val sb = StringBuilder(Character.toString(ch)) while (prem > 1) { kk = (kk - 1) % prem + 1 prem = prem shr 1 val aCode = if (ch == 'a'.code) 1 else 0 ch = if ((kk - 1) / prem == 0) 'a'.code + aCode else 'b'.code + if (ch != 'c'.code) 1 else 0 sb.append(ch.toChar()) } return sb.toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,239
kotlab
Apache License 2.0
src/main/kotlin/com/github/mpe85/grampa/rule/TrieRule.kt
mpe85
138,511,038
false
{"Kotlin": 269689, "Java": 1073}
package com.github.mpe85.grampa.rule import com.github.mpe85.grampa.context.ParserContext import com.github.mpe85.grampa.util.checkEquality import com.github.mpe85.grampa.util.stringify import com.ibm.icu.lang.UCharacter import com.ibm.icu.lang.UCharacter.charCount import com.ibm.icu.lang.UCharacter.toString import com.ibm.icu.util.BytesTrie.Result.FINAL_VALUE import com.ibm.icu.util.BytesTrie.Result.INTERMEDIATE_VALUE import com.ibm.icu.util.BytesTrie.Result.NO_MATCH import com.ibm.icu.util.CharsTrieBuilder import com.ibm.icu.util.StringTrieBuilder.Option.FAST import java.util.Objects.hash import kotlin.streams.asSequence import kotlin.streams.toList /** * A case-sensitive trie (prefix tree) rule implementation that matches the input against a dictionary. * * @author mpe85 * @param[T] The type of the stack elements * @param[strings] A collection of strings from which the trie is built up */ internal open class TrieRule<T>(private val strings: Collection<String>) : AbstractRule<T>() { private val trie = CharsTrieBuilder().run { strings.asSequence().map(::map).distinct().forEach { add(it, 0) } build(FAST) } protected open fun map(string: String): String = string /** * Construct a case-sensitive trie. * * @param[strings] A variable number of strings */ constructor(vararg strings: String) : this(strings.toList()) override fun match(context: ParserContext<T>): Boolean = try { var longestMatch = 0 for ((idx, codePoint) in context.restOfInput.codePoints().asSequence().withIndex()) { val foldedCodePoints = map(toString(codePoint)).codePoints().toList() foldedCodePoints.dropLast(1).forEach { trie.nextForCodePoint(it) } val result = trie.nextForCodePoint(foldedCodePoints.last()) if (result in setOf(FINAL_VALUE, INTERMEDIATE_VALUE)) { longestMatch = idx + 1 } if (result in setOf(FINAL_VALUE, NO_MATCH)) { break } } val charCount = context.restOfInput.codePoints().asSequence().take(longestMatch).sumOf { charCount(it) } longestMatch > 0 && context.advanceIndex(charCount) } finally { trie.reset() } override fun hashCode(): Int = hash(super.hashCode(), strings) override fun equals(other: Any?): Boolean = checkEquality(other, { super.equals(other) }, { it.strings }) override fun toString(): String = stringify("strings" to strings) } /** * A case-insensitive trie (prefix tree) rule implementation that matches the input against a dictionary. * * @author mpe85 * @param[T] The type of the stack elements * @param[strings] A collection of strings from which the trie is built up */ internal class IgnoreCaseTrieRule<T>(strings: Collection<String>) : TrieRule<T>(strings) { /** * Construct a case-insensitive trie. * * @param[strings] A variable number of strings */ constructor(vararg strings: String) : this(strings.toList()) override fun map(string: String): String = UCharacter.foldCase(string, true) }
0
Kotlin
1
11
b3638090a700d2f6213b0f4e10d525c0e4444d94
3,126
grampa
MIT License
src/Day01.kt
melo0187
576,962,981
false
{"Kotlin": 15984}
fun main() { fun <T> List<String>.chunkedByBlank(transform: ((String) -> T)) = fold(mutableListOf(mutableListOf<T>())) { acc, line -> when { line.isNotBlank() -> acc.last().add(transform(line)) else -> acc.add(mutableListOf()) } acc }.map { it.toList() }.toList() fun part1(input: List<String>): Int = input.chunkedByBlank(String::toInt) .maxOf { elvesCalories -> elvesCalories.sum() } fun part2(input: List<String>): Int = input.chunkedByBlank(String::toInt) .map { elvesCalories -> elvesCalories.sum() } .sortedDescending() .take(3) .sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
97d47b84e5a2f97304a078c3ab76bea6672691c5
1,011
kotlin-aoc-2022
Apache License 2.0
string-similarity/src/commonMain/kotlin/com/aallam/similarity/internal/Shingle.kt
aallam
597,692,521
false
null
package com.aallam.similarity.internal /** * Similarities that rely on set operations (like cosine similarity or jaccard index). */ internal interface Shingle { /** * Compute and return the profile of string as defined by [Ukkonen](https://www.cs.helsinki.fi/u/ukkonen/TCS92.pdf). * * The profile is the number of occurrences of k-shingles, and is used to compute q-gram similarity, Jaccard index, * etc. * * k-shingling is the operation of transforming a string (or text document) into a set of n-grams, which can be used to * measure the similarity between two strings or documents. * * Generally speaking, a k-gram is any sequence of [k] tokens. * Multiple subsequent spaces are replaced by a single space, and a k-gram is a sequence of k characters. * * Default value of [k] is `3`. A good rule of thumb is to imagine that there are only 20 characters and estimate the * number of k-shingles as 20^k. For small documents like e-mails, k = 5 is a recommended value. For large documents, * such as research articles, k = 9 is considered a safe choice. * * The memory requirement of the profile can be up to [k] * [string]`.length`. * * @param string input string * @param k length of k-shingles * @return the profile of the provided string */ fun profile(string: CharSequence, k: Int = 3): Profile { require(k > 0) { "k should be positive" } val filtered = spaces.replace(string, " ") return filtered.windowed(size = k).groupingBy { it }.eachCount() } companion object : Shingle { /** * Regex for subsequent spaces. */ private val spaces = Regex("\\s+") } } /** * The number of occurrences of k-shingles. */ internal typealias Profile = Map<String, Int>
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
1,848
string-similarity-kotlin
MIT License
src/Lesson4CountingElements/MissingInteger.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Arrays /** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { var smallest = 1 Arrays.sort(A) for (i in A.indices) { if (A[i] > 0 && A[i] == smallest) { smallest++ } else if (A[i] > smallest) { return smallest } } return smallest } /** Write a function: fun solution(A: IntArray): Int that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
891
Codility-Kotlin
Apache License 2.0
src/main/kotlin/days/Day14.kt
butnotstupid
571,247,661
false
{"Kotlin": 90768}
package days class Day14 : Day(14) { private val margin = 1000 private val mapSize = 3 * margin private val sandPoint = Point(0, 500).withMargin(margin) override fun partOne(): Any { val map = Array(mapSize) { CharArray(mapSize) { '.' } } .also { it[sandPoint.row][sandPoint.col] = '+' } parseShapes().forEach { it.traceOnMap(map) } safetyNet(map).traceOnMap(map, '=') return generateSequence { sand(sandPoint, map).also { map[it.row][it.col] = 'o' } } .takeWhile { map[it.row + 1][it.col] != '=' } .count() } override fun partTwo(): Any { val map = Array(mapSize) { CharArray(mapSize) { '.' } } .also { it[sandPoint.row][sandPoint.col] = '+' } parseShapes().forEach { it.traceOnMap(map) } safetyNet(map).traceOnMap(map, '=') return generateSequence { sand(sandPoint, map).also { map[it.row][it.col] = 'o' } } .takeWhile { map[sandPoint.row][sandPoint.col] != 'o' } .count() + 1 } private fun sand(from: Point, map: Array<CharArray>): Point { return generateSequence(from) { restPoint(it, map) } .zipWithNext() .takeWhile { (prev, cur) -> prev != cur } .lastOrNull() ?.second ?: from } private fun restPoint(from: Point, map: Array<CharArray>): Point { return when { map[from.row + 1][from.col] == '.' -> Point(from.row + 1, from.col) map[from.row + 1][from.col - 1] == '.' -> Point(from.row + 1, from.col - 1) map[from.row + 1][from.col + 1] == '.' -> Point(from.row + 1, from.col + 1) else -> from } } private fun parseShapes(): List<Shape> { val map = inputList.map { line -> line.split(" -> ").map { coord -> coord.split(",").let { (col, row) -> Point(row.toInt(), col.toInt()).withMargin(margin) } }.let { Shape(it) } } return map } private fun safetyNet(a: Array<CharArray>): Shape { val (_, toRow, _, _) = a.getBorders("#") return Shape(listOf(Point(toRow + 2, 0), Point(toRow + 2, mapSize - 1))) } private fun printMap(a: Array<CharArray>) { val (fromRow, toRow, fromCol, toCol) = a.getBorders("#o+") for (row in fromRow..toRow) { for (col in fromCol..toCol) { print(a[row][col]) } println() } } private fun Array<CharArray>.getBorders(charsConsidered: String): List<Int> { val considered = charsConsidered.toSet() val (fromRow, toRow) = this.withIndex().mapNotNull { (index, row) -> if (row.any { it in considered }) index else null } .let { rows -> rows.minOf { it } to rows.maxOf { it } } val (fromCol, toCol) = this.flatMap { row -> row.withIndex().mapNotNull { (index, c) -> if (c in considered) index else null } } .let { cols -> cols.minOf { it } to cols.maxOf { it } } return listOf(fromRow, toRow, fromCol, toCol) } data class Point(val row: Int, val col: Int) { fun withMargin(margin: Int) = Point(row + margin, col + margin) } data class Shape(val points: List<Point>) : List<Point> by points { fun traceOnMap(a: Array<CharArray>, withChar: Char = '#') { points.zipWithNext { from, to -> for (row in IntProgression.fromClosedRange( from.row, to.row, if (from.row < to.row) 1 else -1 )) { for (col in IntProgression.fromClosedRange( from.col, to.col, if (from.col < to.col) 1 else -1 )) { a[row][col] = withChar } } } } } }
0
Kotlin
0
0
4760289e11d322b341141c1cde34cfbc7d0ed59b
3,903
aoc-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/day13/Day13.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day13 import java.io.File fun main() { val data = parse("src/main/kotlin/day13/Day13.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 13 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private sealed class Packet : Comparable<Packet> { data class Integer(val value: Int) : Packet() { override fun toString() = value.toString() override operator fun compareTo(other: Packet): Int = when (other) { is Integer -> value.compareTo(other.value) is List -> compareContents(listOf(this), other.values) } } data class List(val values: kotlin.collections.List<Packet>) : Packet() { override fun toString() = values.toString() override operator fun compareTo(other: Packet): Int = when (other) { is Integer -> compareContents(values, listOf(other)) is List -> compareContents(values, other.values) } } companion object { fun of(n: Int) = Integer(n) fun of(vararg elements: Packet) = List(listOf(*elements)) } } private fun compareContents(lhs: List<Packet>, rhs: List<Packet>): Int { for ((a, b) in lhs.zip(rhs)) { val result = a.compareTo(b) if (result != 0) { return result } } return lhs.size.compareTo(rhs.size) } @Suppress("SameParameterValue") private fun parse(path: String): List<Packet> = File(path).readLines() .filterNot { it.isBlank() } .map { it.toPacket() } private fun String.toPacket(): Packet = ParserState(source = this).packet() private data class ParserState( val source: String, var current: Int = 0, ) private fun ParserState.peek(): Char = source[current] private fun ParserState.next(): Char = source[current++] /* * packet ::= list | integer */ private fun ParserState.packet(): Packet { return if (peek() == '[') { list() } else { integer() } } /* * list ::= '[' (packet ',')* packet? ']' */ private fun ParserState.list(): Packet.List { val values = mutableListOf<Packet>() next() // skip '[' while (peek() != ']') { values.add(packet()) if (peek() == ',') { next() } } next() // skip ']' return Packet.List(values) } /* * integer ::= [0-9]+ */ private fun ParserState.integer(): Packet.Integer { var result = 0 while (peek().isDigit()) { result = result * 10 + next().digitToInt() } return Packet.Integer(result) } private fun part1(data: List<Packet>): Int { val indices = mutableListOf<Int>() for ((i, packet) in data.chunked(2).withIndex()) { val (lhs, rhs) = packet if (lhs < rhs) { indices.add(i + 1) } } return indices.sum() } private fun part2(data: List<Packet>): Int { val divider2 = Packet.of(Packet.of(2)) val divider6 = Packet.of(Packet.of(6)) val sorted = (data + listOf(divider2, divider6)).sorted() return (sorted.indexOf(divider2) + 1) * (sorted.indexOf(divider6) + 1) }
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
3,265
advent-of-code-2022
MIT License
src/Day08.kt
Kaaveh
572,838,356
false
{"Kotlin": 13188}
private fun parse(input: List<String>, size: Int): MutableList<MutableList<Int>> { val array = MutableList(size) { MutableList(size) { 0 } } input.forEachIndexed { indexX: Int, row: String -> row.forEachIndexed { indexY, element -> array[indexX][indexY] = element.digitToInt() } } return array } private fun part1(input: List<String>): Int { var total = 0 val size = input.size val array = parse(input, size) for (i in 0 until size) { for (j in 0 until size) { val element = array[i][j] val leftVisible = (0 until j).all { array[i][it] < element } val rightVisible = (j + 1 until array[i].size).all { array[i][it] < element } val topVisible = (0 until i).all { k -> array[k][j] < element } val bottomVisible = (i + 1 until array[i].size).all { k -> array[k][j] < element } if ( leftVisible || rightVisible || topVisible || bottomVisible || i == 0 || j == 0 || i == size - 1 || j == size - 1 ) { total++ } } } return total } private fun part2(input: List<String>): Int { var max = 0 val size = input.size val array = parse(input, size) for (i in 1 until size - 1) { for (j in 1 until size - 1) { val element = array[i][j] val scoreRowBefore = array[i].subList(fromIndex = 0, toIndex = j).reversed().let { var index = it.size for (k in it.indices) { if (it[k] >= element){ index = k + 1 break } } index } val scoreRowAfter = array[i].subList(fromIndex = j + 1, toIndex = array[i].size).let { var index = it.size for (k in it.indices) { if (it[k] >= element){ index = k + 1 break } } index } val scoreColumnBefore = (i - 1 downTo 0).let { var index = 0 for (k in i - 1 downTo 0) { if (array[k][j] < element) { index++ } else if (array[k][j] >= element) { index++ break } else { break } } index } val scoreColumnAfter = true.let { var index = 0 for (k in i + 1 until array[i].size) { if (array[k][j] < element) { index++ } else if (array[k][j] >= element) { index++ break } else { break } } index } val maxTmp = scoreRowBefore * scoreRowAfter * scoreColumnBefore * scoreColumnAfter if (maxTmp > max) max = maxTmp } } return max } fun main() { val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") // println(part1(input)) // println(part2(input)) }
0
Kotlin
0
1
9022f1a275e9c058655898b64c196f7a0a494b48
3,459
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/sorting/RadixSort.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.sorting import kotlin.math.pow fun main() { val arr = mutableListOf( 634, 472, 977, 756, 770, 966, 993, 191, 52, 49, 475, 564, 491, 722, 284, 45, 614, 273, 332, 744, 629, 304, 822, 548, 864, 45, 971, 352, 3, 687 ) radixSort(arr) print(arr) } // O(d * (n + m)) time | O(n + m) space private fun radixSort(arr: MutableList<Int>) { // find max var max = arr[0] arr.forEach { if (it > max) max = it } var digit = 0 while (max / 10.0.pow(digit).toInt() > 0) { countSort(arr, digit++) } } private fun countSort(arr: MutableList<Int>, digit: Int) { // init count with zeros val count = MutableList(10) { 0 } // count val digitColumn = 10.0.pow(digit).toInt() for (el in arr) { val countIdx = (el / digitColumn) % 10 count[countIdx]++ } // cumulate sum for (i in 1..9) { count[i] += count[i - 1] } val n = arr.size val output = MutableList(n) { 0 } for (i in n - 1 downTo 0) { val cntIdx = (arr[i] / digitColumn) % 10 val outputIdx = --count[cntIdx] output[outputIdx] = arr[i] } arr.forEachIndexed { i, _ -> arr[i] = output[i] } }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,259
algs4-leprosorium
MIT License
src/Day01/Day01.kt
rooksoto
573,602,435
false
{"Kotlin": 16098}
package Day01 import profile import readInputActual import readInputTest private const val DAY = "Day01" private const val NEWLINE = "\n" fun main() { fun part1(input: List<String>): Int = toCalorieValues(input) .max() fun part2(input: List<String>): Int = toCalorieValues(input) .sortedDescending() .take(3) .sum() val testInput = readInputTest(DAY) val input = readInputActual(DAY) check(part1(testInput) == 24000) profile(shouldLog = true) { println("Part 1: ${part1(input)}") } // Answer: 74711 @ 13ms check(part2(testInput) == 45000) profile(shouldLog = true) { println("Part 2: ${part2(input)}") } // Answer: 209481 @ 6ms } private fun toCalorieValues( input: List<String> ): List<Int> = input.joinToString(NEWLINE) .split(NEWLINE.repeat(2)) .map { inputString -> inputString.split(NEWLINE) }.map { group -> group.sumOf { item -> item.toIntOrZero() } } private fun String.toIntOrZero(): Int = toIntOrNull() ?: 0
0
Kotlin
0
1
52093dbf0dc2f5f62f44a57aa3064d9b0b458583
1,105
AoC-2022
Apache License 2.0
year2020/day19/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day19/part1/Year2020Day19Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 19: Monster Messages --- You land in an airport surrounded by dense forest. As you walk to your high-speed train, the Elves at the Mythical Information Bureau contact you again. They think their satellite has collected an image of a sea monster! Unfortunately, the connection to the satellite is having problems, and many of the messages sent back from the satellite have been corrupted. They sent you a list of the rules valid messages should obey and a list of received messages they've collected so far (your puzzle input). The rules for valid messages (the top part of your puzzle input) are numbered and build upon each other. For example: 0: 1 2 1: "a" 2: 1 3 | 3 1 3: "b" Some rules, like 3: "b", simply match a single character (in this case, b). The remaining rules list the sub-rules that must be followed; for example, the rule 0: 1 2 means that to match rule 0, the text being checked must match rule 1, and the text after the part that matched rule 1 must then match rule 2. Some of the rules have multiple lists of sub-rules separated by a pipe (|). This means that at least one list of sub-rules must match. (The ones that match might be different each time the rule is encountered.) For example, the rule 2: 1 3 | 3 1 means that to match rule 2, the text being checked must match rule 1 followed by rule 3 or it must match rule 3 followed by rule 1. Fortunately, there are no loops in the rules, so the list of possible matches will be finite. Since rule 1 matches a and rule 3 matches b, rule 2 matches either ab or ba. Therefore, rule 0 matches aab or aba. Here's a more interesting example: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" Here, because rule 4 matches a and rule 5 matches b, rule 2 matches two letters that are the same (aa or bb), and rule 3 matches two letters that are different (ab or ba). Since rule 1 matches rules 2 and 3 once each in either order, it must match two pairs of letters, one pair with matching letters and one pair with different letters. This leaves eight possibilities: aaab, aaba, bbab, bbba, abaa, abbb, baaa, or babb. Rule 0, therefore, matches a (rule 4), then any of the eight options from rule 1, then b (rule 5): aaaabb, aaabab, abbabb, abbbab, aabaab, aabbbb, abaaab, or ababbb. The received messages (the bottom part of your puzzle input) need to be checked against the rules so you can determine which are valid and which are corrupted. Including the rules and the messages together, this might look like: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb Your goal is to determine the number of messages that completely match rule 0. In the above example, ababbb and abbbab match, but bababa, aaabbb, and aaaabbb do not, producing the answer 2. The whole message must match all of rule 0; there can't be extra unmatched characters in the message. (For example, aaaabbb might appear to match rule 0 above, but it has an extra unmatched b on the end.) How many messages completely match rule 0? */ package com.curtislb.adventofcode.year2020.day19.part1 import com.curtislb.adventofcode.common.io.forEachSection import com.curtislb.adventofcode.year2020.day19.rule.parseRule import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 19, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val file = inputPath.toFile() val ruleStrings = mutableMapOf<Int, String>() val messages = mutableListOf<String>() file.forEachSection { lines -> if (ruleStrings.isEmpty()) { for (line in lines) { val (ruleKeyString, ruleString) = line.split(':').map { it.trim() } ruleStrings[ruleKeyString.toInt()] = ruleString } } else { messages.addAll(lines) } } val primaryRule = parseRule(ruleStrings[0]!!, ruleStrings) val primaryRuleRegex = primaryRule.toRegex() return messages.count { primaryRuleRegex.matches(it) } } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
4,176
AdventOfCode
MIT License
src/day02/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day02 import java.io.File const val workingDir = "src/day02" fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") println("Step 1b: ${runStep1(input1)}") println("Step 2a: ${runStep2(sample)}") println("Step 2b: ${runStep2(input1)}") } fun runStep1(input: File): String = input.readLines().filterNot { it.isBlank() }.map { it.split(" ") }.sumOf { (opponent, me) -> val chosenScore = when (me) { "X" -> 1 // Rock "Y" -> 2 // Paper "Z" -> 3 // Scissor else -> TODO() } val won = when (me) { "X" -> when (opponent) { "A" -> 3 "B" -> 0 "C" -> 6 else -> TODO() } "Y" -> when (opponent) { "A" -> 6 "B" -> 3 "C" -> 0 else -> TODO() } "Z" -> when (opponent) { "A" -> 0 "B" -> 6 "C" -> 3 else -> TODO() } else -> TODO() } chosenScore + won }.toString() fun runStep2(input: File): String = input.readLines().filterNot { it.isBlank() }.map { it.split(" ") }.sumOf { (opponent, me) -> val won = when (me) { "X" -> when (opponent) { "A" -> 3 "B" -> 1 "C" -> 2 else -> TODO() } "Y" -> when (opponent) { "A" -> 4 "B" -> 5 "C" -> 6 else -> TODO() } "Z" -> when (opponent) { "A" -> 8 "B" -> 9 "C" -> 7 else -> TODO() } else -> TODO() } won }.toString()
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
1,948
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Tetris.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
import kotlin.streams.toList fun main() = Tetris.solve() private object Tetris { private const val width = 7 private val winds = mutableListOf<Int>() private var fallingRock: FallingRock? = null private val cells = mutableListOf( // Floor MutableList(width) { i -> Cell.StableRock } ) private var rocks = 0 private var turn = 0 private var highestRock = 0 fun solve() { winds.clear() winds.addAll(readInput()) val cache = mutableMapOf<Int, Triple<Int, Int, List<Int>>>() var cycleSize = Int.MAX_VALUE var cycleHeight = 0 val target = 1_000_000_000_000 var cycles = 0L var currentTarget = target while (rocks < currentTarget) { if (cycleSize == Int.MAX_VALUE) { if (fallingRock == null && rocks > 0 && rocks % 5 == 0) { // println("Rock cycle, round $turn, ${turn % winds.size}") val heights = heights() val minHeight = heights().min() val dHeights = heights.map { it - minHeight } val (cachedRocks, cachedMinHeight, cachedDh) = cache.getOrDefault( turn % winds.size, Triple(0, 0, listOf<Int>()) ) if (dHeights == cachedDh) { cycleSize = rocks - cachedRocks cycleHeight = minHeight - cachedMinHeight println("Cycle rocks=${cycleSize} height=$cycleHeight $dHeights") currentTarget = rocks + ((target - rocks) % cycleSize) cycles = (target - rocks) / cycleSize println("Setting new target $currentTarget") } else { cache.put(turn % winds.size, Triple(rocks, minHeight, dHeights)) } //println("$dHeights ${turn % winds.size}") } } tick() } println("Total height: shortcut=$highestRock ${highestRock + cycleHeight * cycles}") } fun heights(): List<Int> { return (0 until width).map { x -> (highestRock downTo 0).first { y -> cells[y][x] == Cell.StableRock } } } private fun tick() { addRockOrFall() blowAtFallingRock() maybeStabilizeFallenRock() turn += 1 } private fun addRockOrFall() { if (fallingRock == null) { val pos = Pos(2, highestRock + 4) fallingRock = FallingRock(rockTypes[rocks % rockTypes.size], pos) extendCells(fallingRock!!.cells().maxOf { it.y }) } else { moveFalling(0, -1) } } private fun moveFalling(dx: Int, dy: Int): Boolean { val initialPos = fallingRock!!.pos val nextRock = FallingRock(fallingRock!!.type, Pos(initialPos.x + dx, initialPos.y + dy)) val moved = !nextRock.cells().any { it.x !in 0 until width || cells[it.y][it.x] == Cell.StableRock } if (moved) { fallingRock = nextRock } return moved } private fun maybeStabilizeFallenRock() { val rockCells = fallingRock!!.cells() val isStable = rockCells.any { cells[it.y - 1][it.x] == Cell.StableRock } if (isStable) { rockCells.forEach { cells[it.y][it.x] = Cell.StableRock } highestRock = maxOf(highestRock, rockCells.maxOf { it.y }) rocks += 1 fallingRock = null } } private fun extendCells(maxY: Int) { while (maxY >= cells.size) { cells.add(MutableList(width) { i -> Cell.Empty }) } } private fun blowAtFallingRock() { moveFalling(winds[turn % winds.size], 0) } private fun visualize() { println("turn $turn") val rockCells = fallingRock?.cells()?.toSet() ?: setOf() for (y in cells.indices.reversed()) { print('|') for (x in cells[y].indices) { if (Pos(x, y) in rockCells) { print('@') } else if (cells[y][x] == Cell.StableRock) { print(if (y > 0) '#' else '-') } else { print('.') } } println('|') } } private fun readInput(): List<Int> = readLine()!!.chars().map { when (it) { '<'.code -> -1 '>'.code -> 1 else -> throw Error("Invalid char $it") } }.toList() private data class Pos(val x: Int, val y: Int) private enum class Cell { Empty, StableRock, } private enum class RockType(val cells: List<Pos>) { HLine(listOf(Pos(0, 0), Pos(1, 0), Pos(2, 0), Pos(3, 0))), Cross(listOf(Pos(1, 0), Pos(0, 1), Pos(1, 1), Pos(2, 1), Pos(1, 2))), RightAngle(listOf(Pos(0, 0), Pos(1, 0), Pos(2, 0), Pos(2, 1), Pos(2, 2))), VLine(listOf(Pos(0, 0), Pos(0, 1), Pos(0, 2), Pos(0, 3))), Square(listOf(Pos(0, 0), Pos(1, 0), Pos(0, 1), Pos(1, 1))) } private data class FallingRock(val type: RockType, val pos: Pos) { fun cells() = type.cells.map { Pos(pos.x + it.x, pos.y + it.y) } } private val rockTypes = listOf(RockType.HLine, RockType.Cross, RockType.RightAngle, RockType.VLine, RockType.Square) }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
5,463
aoc2022
MIT License
src/Day14_p2.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
fun main() { var maxYCntr = 0 /** * Model of the falling sand part 2 * 1) If it can fall straight dawn it falls down until it encounters sand or rock, if no cell or rock it stops at the bottom (maxY) * 2) If it can fall left dawn it falls down left until it encounters sand or rock, if no cell or rock it stops at the bottom (maxY) * 3) idem right down * 4) repeat from 1, until down left, down and down right are blocked, that means the sand is stable. */ fun placeOneUnit(grid: Grid2D<Tile>, minX: Int, maxX: Int, maxY: Int): PlacementResult { fun placementStep(currentX: Int, currentY: Int): PlacementResult { val colCells = grid.getCol(currentX) val maxDownCell = colCells .filter { it.y > currentY } .takeWhile { !it.value.isRock && !it.value.isFilledWithSand && it.y <= maxY } .lastOrNull() if (maxDownCell == null || maxDownCell.y == -1) { println("full. No more sand can be placed") return PlacementResult(stable = false, stop = true) } else if (maxDownCell.y == maxY) { maxDownCell.value.isFilledWithSand = true maxYCntr++ println("MaxY reached for $maxYCntr time. Cell $maxDownCell") return PlacementResult(stable = true, stop = false) } val isStableLeft = grid.getCell(maxDownCell.x - 1, maxDownCell.y + 1) .let { it.value.isRock || it.value.isFilledWithSand } val isStableRight = grid.getCell(maxDownCell.x + 1, maxDownCell.y + 1) .let { it.value.isRock || it.value.isFilledWithSand } return if (!isStableLeft) { placementStep(maxDownCell.x - 1, maxDownCell.y) } else if (!isStableRight) { placementStep(maxDownCell.x + 1, maxDownCell.y) } else { maxDownCell.value.isFilledWithSand = true PlacementResult(stable = true, stop = false) } } return placementStep(500, -1) } fun placeSand( grid: Grid2D<Tile>, minX: Int, maxX: Int, maxY: Int, ): Int { var counter = 0 while (true) { val result = placeOneUnit(grid, minX, maxX, maxY) if (!result.stop) { counter++ } else { return counter } } } fun part2(input: List<String>): Int { // Trajectory like 498,4 -> 498,6 -> 496,6 val rockPaths: List<RockPath> = input.map { it.split(" -> ").map { i -> i.split(",").map { c -> c.toInt() } } } val flattened = rockPaths.flatMap { it }.flatMap { it }.chunked(2) val maxY = flattened.maxOf { it.last() } + 1 // assumption width in both directions will not exceed height, so min and max x can be calculated. val minX = 500 - maxY val maxX = 500 + maxY val list2D = (0..maxY).map { (0..maxX + 1).map { Tile() } } var grid: Grid2D<Tile> = Grid2D(list2D) // fill rocks fillRocks(grid, rockPaths) printGridFn(toTotalGridFn, grid.getNrOfRows(), grid, minX, maxX) var units = placeSand(grid, minX, maxX, maxY) printGridFn(toTotalGridFn, grid.getNrOfRows(), grid, minX, maxX) return units } val testInput = readInput("Day14_test") println(part2(testInput)) val input = readInput("Day14") println(part2(input)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
3,601
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
fun main() { fun part1(input: List<String>): Int { var depth = 0 var position = 0 for (line in input) { val split = line.split(" ") val command = split[0] val value = split[1].toInt() when (command) { "forward" -> position += value "down" -> depth += value "up" -> depth -= value } } return depth * position } fun part2(input: List<String>): Int { var depth = 0 var position = 0 var aim = 0 for (line in input) { val split = line.split(" ") val command = split[0] val value = split[1].toInt() when (command) { "down" -> aim += value "up" -> aim -= value "forward" -> { position += value depth += aim * value } } } return depth * position } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 150) check(part2(testInput) == 900) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
1,301
AdventOfCode2021
Apache License 2.0
Codeforces/1519/B.kt
thedevelopersanjeev
112,687,950
false
null
private fun readLine() = kotlin.io.readLine()!! private fun readInt() = readLine().toInt() private fun readInts() = readLine().split(" ").map { it.toInt() } lateinit var dp: Array<IntArray> fun solve(i: Int, j: Int, n: Int, m: Int, curr: Int): Boolean { if (i <= 0 || j <= 0 || i > n || j > m) return false if (dp[i][j] != -1) return dp[i][j] != 0 if (i == n && j == m) return curr == 0 if (solve(i + 1, j, n, m, curr - j) || solve(i, j + 1, n, m, curr - i)) { dp[i][j] = 1 return true } dp[i][j] = 0 return false } fun main() { val testCases = readInt() for (testCase in 0 until testCases) { val arr = readInts() dp = Array(arr[0] + 1) { IntArray(arr[1] + 1) { -1 } } val good = solve(1, 1, arr[0], arr[1], arr[2]) println(if (good) "YES" else "NO") } }
0
C++
58
146
610520cc396fb13a03c606b5fb6739cfd68cc444
873
Competitive-Programming
MIT License
src/Day04.kt
nZk-Frankie
572,894,533
false
{"Kotlin": 13625}
val FILEDAY04 = readInput("Day04") fun main(){ Part02() } private fun Part01() { var overlapScore = 0 for(i in FILEDAY04) { var SPLITTED = i.split(",") if (checkWithin(SPLITTED.get(0),SPLITTED.get(1))) { overlapScore++ } } println("Total Overlap: "+ overlapScore) } fun checkWithin(s1:String, s2:String):Boolean{ var S1_SPLIT = s1.split("-") var S2_SPLIT = s2.split("-") var r1 = S1_SPLIT.get(1).toInt() - S1_SPLIT.get(0).toInt() + 1 var r2 = S2_SPLIT.get(1).toInt() - S2_SPLIT.get(0).toInt() + 1 if (r1 >= r2) { if (Determine(S1_SPLIT.get(0).toInt(),S1_SPLIT.get(1).toInt(),S2_SPLIT.get(0).toInt(),S2_SPLIT.get(1).toInt())) { println("First is Within") return true } } else{ if (Determine(S2_SPLIT.get(0).toInt(),S2_SPLIT.get(1).toInt(),S1_SPLIT.get(0).toInt(),S1_SPLIT.get(1).toInt())) { println("Second is Within") return true } } println("Not Within") return false } private fun Determine(M1:Int,M2:Int,m1:Int,m2:Int):Boolean { if (m1>=M1 && M2 >= m2) { return true } else { return false } } private fun Part02(){ var overlapScore = 0 for(i in FILEDAY04) { var SPLITTED = i.split(",") if (checkPartialOverlap(SPLITTED.get(0),SPLITTED.get(1))) { overlapScore++ } } println("Total Partial Overlap: "+ overlapScore) } fun checkPartialOverlap(s1:String,s2:String):Boolean { var S1_SPLIT = s1.split("-") var S2_SPLIT = s2.split("-") var r1 = S1_SPLIT.get(1).toInt() - S1_SPLIT.get(0).toInt() + 1 var r2 = S2_SPLIT.get(1).toInt() - S2_SPLIT.get(0).toInt() + 1 if (r1>=r2) { if ((S2_SPLIT.get(0).toInt() >= S1_SPLIT.get(0).toInt() && S1_SPLIT.get(1).toInt() >= S2_SPLIT.get(0).toInt()) || (S2_SPLIT.get(1).toInt() >= S1_SPLIT.get(0).toInt() && S1_SPLIT.get(1).toInt() >= S2_SPLIT.get(1).toInt())) { return true } } else{ if ((S1_SPLIT.get(0).toInt() >= S2_SPLIT.get(0).toInt() && S2_SPLIT.get(1).toInt() >= S1_SPLIT.get(0).toInt()) || (S1_SPLIT.get(1).toInt() >= S2_SPLIT.get(0).toInt() && S2_SPLIT.get(1).toInt() >= S1_SPLIT.get(1).toInt())) { return true } } return false }
0
Kotlin
0
0
b8aac8aa1d7c236651c36da687939c716626f15b
2,502
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2022/Day14.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2022 import utils.InputUtils import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.IntNode import utils.Coordinates import utils.boundingBox import utils.toCoordinates class Cave(initialState: Map<Coordinates, Char>) { val state = initialState.toMutableMap() val maxY = state.keys.maxOf { it.y } override fun toString(): String { val (tl, br) = state.keys.toList().boundingBox() return (tl.y..br.y) .joinToString("\n") { y -> (tl.x..br.x).map { x -> state[Coordinates(x, y)] ?: '.' }.joinToString("") } } private val newPositions = listOf(Coordinates(0, 1), Coordinates(-1, 1), Coordinates(1,1)) private fun fallFrom(start: Coordinates) = generateSequence(start) { last -> newPositions.map { last + it }.firstOrNull { it !in state } }.takeWhile { it.y < maxY + 2 }.last() fun dropSand(coordinates: Coordinates): Boolean { val end = fallFrom(coordinates) if (end.y <= maxY) { state[end] = 'o'; return true;} return false } fun dropSand2(coordinates: Coordinates) { state[fallFrom(coordinates)] = 'o' } } fun main() { val testInput = """498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9""".split("\n") fun getCave(input: List<String>) = input.map { line -> line.splitToSequence(" -> ") .map(String::toCoordinates) .zipWithNext { a, b -> a.lineTo(b) }.flatten() }.flatMap { it }.associateWith { '#' } .let { Cave(it) } val startPosition = Coordinates(500, 0) fun part1(input: List<String>): Int { val cave = getCave(input) var count = 0 while(cave.dropSand(startPosition)) { count++; } println(cave) return count } fun part2(input: List<String>): Int { val cave = getCave(input) var count = 0 do { cave.dropSand2(startPosition) count++; } while (startPosition !in cave.state) println(cave) return count } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 24) val puzzleInput = InputUtils.downloadAndGetLines(2022, 14).toList() println(part1(puzzleInput)) println(part2(testInput)) println(part2(puzzleInput)) } private fun JsonNode.toComp(): Comp = when (this) { is ArrayNode -> toComp() is IntNode -> toComp() else -> throw UnsupportedOperationException("Unexpected node: $this") } private fun ArrayNode.toComp(): Comp { return Comp.Array(this.map { it.toComp() }) } private fun IntNode.toComp(): Comp { return Comp.Integer(intValue()) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,892
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/Day13.kt
jcornaz
573,137,552
false
{"Kotlin": 76776}
import java.lang.StringBuilder object Day13 { fun part1(input: String): Int = input.split("\n\n").withIndex() .filter { (_, both) -> isInCorrectOrder(both.lines().first(), both.lines().last())!! } .sumOf { it.index + 1 } @Suppress("UNUSED_PARAMETER") fun part2(input: String): Int { val dividers = listOf("[[2]]", "[[6]]") val sorted = (input.lines() + dividers) .filter { it.isNotBlank() } .sortedWith { left, right -> isInCorrectOrder(left, right) ?.let { if (it) -1 else 1 } ?: 0 } return dividers.map { sorted.indexOf(it) + 1 }.fold(1) { a, b -> a * b } } fun isInCorrectOrder(left: String, right: String): Boolean? { return if (left.startsWith("[") || right.startsWith("[")) { val leftArray = left.toArray() val rightArray = right.toArray() leftArray.zip(rightArray).forEach { (a, b) -> isInCorrectOrder(a, b)?.let { return it } } isInCorrectOrder(leftArray.size, rightArray.size) } else { isInCorrectOrder(left.toInt(), right.toInt()) } } private fun isInCorrectOrder(left: Int, right: Int): Boolean? = if (left < right) true else if (left > right) false else null private fun String.toArray(): List<String> { if (!startsWith("[")) return listOf(this) return buildList { var nestedLevel = 0 val current = StringBuilder() removePrefix("[") .forEach { char -> if ((char == ',' || char == ']') && nestedLevel == 0 && current.isNotBlank()) { add(current.toString()) current.clear() } else { current.append(char) if (char == '[') { nestedLevel += 1 } else if (char == ']') { nestedLevel -= 1 } } } } } }
1
Kotlin
0
0
979c00c4a51567b341d6936761bd43c39d314510
2,194
aoc-kotlin-2022
The Unlicense
src/main/kotlin/day22/Day22.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day22 import execute import readAllText import wtf typealias Point = Pair<Int, Int> // (row, column) 1-based indexes data class Board(val rows: Map<Int, IntRange>, val cols: Map<Int, IntRange>, val walls: Set<Point>) { val faceSize by lazy { if (rows.keys.any { it > 50 }) 50 else 4 } } sealed interface Op data class Move(val steps: Int) : Op enum class Turn : Op { L, R } fun part1(input: String) = input.split("\n\n") .let { (boardData, pathData) -> parseBoard(boardData, pathData) } .let { (board, path) -> path.fold(Point(1, board.rows[1]!!.first) to 0, board::playPart1) } .let { (pos, dir) -> pos.first * 1000 + pos.second * 4 + dir } fun part2(input: String) = input.split("\n\n") .let { (boardData, pathData) -> parseBoard(boardData, pathData) } .let { (board, path) -> path.fold(Point(1, board.rows[1]!!.first) to 0, board::playPart2) } .let { (pos, dir) -> pos.first * 1000 + pos.second * 4 + dir } private fun Board.playPart1(from: Pair<Point, Dir>, op: Op) = play(from, op, ::stepPart1) private fun Board.playPart2(from: Pair<Point, Dir>, op: Op) = play(from, op, ::stepPart2) private fun Board.play( from: Pair<Point, Dir>, op: Op, step: (Pair<Point, Dir>) -> Pair<Point, Dir> ): Pair<Point, Dir> = when (op) { Turn.L -> from.first to (from.second + 3) % 4 Turn.R -> from.first to (from.second + 1) % 4 is Move -> (1..op.steps).fold(from) { acc, _ -> val fromX = step(acc) if (fromX.first !in walls) fromX else acc } } private fun Board.stepPart1(from: Pair<Point, Dir>): Pair<Point, Dir> = from.let { (pos, dir) -> val (r, c) = pos when (dir) { 0 -> r to (c + 1).keepIn(rows[r]!!) 1 -> (r + 1).keepIn(cols[c]!!) to c 2 -> r to (c - 1).keepIn(rows[r]!!) 3 -> (r - 1).keepIn(cols[c]!!) to c else -> wtf(dir) } to dir } typealias Block = Pair<Int, Int> typealias Dir = Int private val transitions4 = buildMap<Pair<Block, Dir>, (Pair<Point, Dir>) -> Pair<Point, Dir>> { val faceSize = 4 this[0 to 2 to 1] = { it } this[1 to 2 to 3] = { it } this[1 to 0 to 2] = { it } this[1 to 1 to 0] = { it } this[1 to 1 to 2] = { it } this[1 to 2 to 0] = { it } this[1 to 2 to 1] = { it } this[2 to 2 to 3] = { it } this[2 to 2 to 2] = { it } this[2 to 3 to 0] = { it } this[1 to 3 to 0] = { right(it, pivot10BL(faceSize, 1 to 3)) } this[3 to 2 to 1] = { right(it, pivot10TR(faceSize, 2 to 1)).let { right(it, pivot10TR(faceSize, 2 to 0)) } } this[0 to 1 to 3] = { left(it, pivot10BR(faceSize, 0 to 1)) } } private val transitions50 = buildMap<Pair<Block, Dir>, (Pair<Point, Dir>) -> Pair<Point, Dir>> { val faceSize = 50 this[0 to 1 to 2] = { it } this[0 to 2 to 0] = { it } this[0 to 1 to 3] = { it } this[1 to 1 to 1] = { it } this[1 to 1 to 3] = { it } this[2 to 1 to 1] = { it } this[2 to 1 to 0] = { it } this[2 to 0 to 2] = { it } this[2 to 0 to 3] = { it } this[3 to 0 to 1] = { it } this[3 to 1 to 1] = { right(it, pivot10TL(faceSize, 3 to 1)) } this[3 to 1 to 0] = { left(it, pivot10TL(faceSize, 3 to 1)) } this[1 to 2 to 1] = { right(it, pivot10TL(faceSize, 1 to 2)) } this[1 to 2 to 0] = { left(it, pivot10TL(faceSize, 1 to 2)) } this[1 to 0 to 2] = { left(it, pivot10BR(faceSize, 1 to 0)) } this[1 to 0 to 3] = { right(it, pivot10BR(faceSize, 1 to 0)) } this[0 to 3 to 0] = { right(it, pivot10TL(faceSize, 1 to 2)).let { right(it, pivot10TL(faceSize, 2 to 2)) } } this[2 to 2 to 0] = { left(it, pivot10TL(faceSize, 1 to 2)).let { left(it, pivot10BL(faceSize, 0 to 3)) } } this[0 to 0 to 2] = { left(it, pivot10BR(faceSize, 1 to 0)).let { left(it, pivot10TR(faceSize, 2 to -1)) } } this[2 to -1 to 2] = { right(it, pivot10BR(faceSize, 1 to 0)).let { right(it, pivot10BR(faceSize, 0 to 0)) } } this[4 to 0 to 1] = { transpose(it, vector(faceSize, -4 to 2)) } this[-1 to 2 to 3] = { transpose(it, vector(faceSize, 4 to -2)) } this[-1 to 1 to 3] = { right(it, pivot10TL(faceSize, 3 to 1)).let { transpose(it, vector(faceSize, 0 to -4)) } } this[3 to -1 to 2] = { transpose(it, vector(faceSize, 0 to 4)).let { left(it, pivot10TL(faceSize, 3 to 1)) } } } fun vector(faceSize: Int, b: Block) = faceSize * b.first to faceSize * b.second fun transpose(from: Pair<Point, Dir>, v: Point) = from.let { (p, d) -> p.first + v.first to p.second + v.second to d } private fun pivot10TL(faceSize: Int, b: Block): Point = (b.first * faceSize) * 10 + 5 to (b.second * faceSize) * 10 + 5 private fun pivot10BL(faceSize: Int, b: Block): Point = (b.first * faceSize + faceSize) * 10 + 5 to (b.second * faceSize) * 10 + 5 private fun pivot10TR(faceSize: Int, b: Block): Point = (b.first * faceSize) * 10 + 5 to (b.second * faceSize + faceSize) * 10 + 5 private fun pivot10BR(faceSize: Int, b: Block): Point = (b.first * faceSize + faceSize) * 10 + 5 to (b.second * faceSize + faceSize) * 10 + 5 private fun left(from: Pair<Point, Dir>, pivot10: Point): Pair<Point, Dir> { val (pos, dir) = from val (r0, c0) = pos val (rp, cp) = pivot10 val dir1 = (dir + 3) % 4 val r1 = rp - c0 * 10 + cp val c1 = cp + r0 * 10 - rp return r1 / 10 to c1 / 10 to dir1 } private fun right(from: Pair<Point, Dir>, pivot10: Point): Pair<Point, Dir> { val (pos, dir) = from val (r0, c0) = pos val (rp, cp) = pivot10 val dir1 = (dir + 1) % 4 val r1 = rp + c0 * 10 - cp val c1 = cp - r0 * 10 + rp return r1 / 10 to c1 / 10 to dir1 } private fun Board.stepPart2(from: Pair<Point, Dir>): Pair<Point, Dir> { val (pos, dir) = from val (r0, c0) = pos val rb0 = (r0 - 1) / faceSize val cb0 = (c0 - 1) / faceSize var pos1 = when (dir) { 0 -> r0 to c0 + 1 1 -> r0 + 1 to c0 2 -> r0 to c0 - 1 3 -> r0 - 1 to c0 else -> wtf(dir) } var (r, c) = pos1 val rb = if (r == 0) -1 else (r - 1) / faceSize val cb = if (c == 0) -1 else (c - 1) / faceSize return (if (rb == rb0 && cb == cb0) pos1 to dir else if (faceSize == 4) transitions4[rb to cb to dir]?.invoke(pos1 to dir) ?: TODO((rb to cb to dir).toString()) else if (faceSize == 50) transitions50[rb to cb to dir]?.invoke(pos1 to dir) ?: TODO((rb to cb to dir).toString()) else wtf(faceSize)) } private fun parseBoard( boardData: String, pathData: String ): Pair<Board, List<Op>> { val lines = boardData.lines() val walls = buildSet { lines.forEachIndexed { r, line -> line.forEachIndexed { c, p -> if (p == '#') add(Point(r + 1, c + 1)) } } } val rows = lines.mapIndexed { r0, line -> r0 + 1 to line.indexOfFirst { it != ' ' } + 1..line.indexOfLast { it != ' ' } + 1 } .filterNot { (_, r) -> r.isEmpty() } .toMap() val cols = (0..lines.maxOf { it.length }).map { c0 -> c0 + 1 to lines.indexOfFirst { line -> c0 in line.indices && line[c0] != ' ' } + 1.. lines.indexOfLast { line -> c0 in line.indices && line[c0] != ' ' } + 1 } .filterNot { (_, r) -> r.isEmpty() } .toMap() val board = Board(rows, cols, walls) val path = buildList { pathData.trimEnd().forEach { if (it.isDigit() && this.lastOrNull() is Move) add(Move((removeLast() as Move).steps * 10 + it.digitToInt())) else add( when { it.isDigit() -> Move(it.digitToInt()) it == 'L' -> Turn.L it == 'R' -> Turn.R else -> wtf(it) } ) } } return board to path } private fun Int.keepIn(intRange: IntRange): Int = when { this > intRange.last -> intRange.first this < intRange.first -> intRange.last else -> this } fun main() { val input = readAllText("local/day22_input.txt") val test = """ ...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5 """.trimIndent() execute(::part1, test, 6032) execute(::part1, input, 66292) // execute(::part2, test, 5031) execute(::part2, input) }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
8,441
advent-of-code-2022
MIT License
src/main/kotlin/com/adrielm/aoc2020/solutions/day09/Day09.kt
Adriel-M
318,860,784
false
null
package com.adrielm.aoc2020.solutions.day09 import com.adrielm.aoc2020.common.Algorithms import com.adrielm.aoc2020.common.Solution import org.koin.dsl.module class Day09 : Solution<Day09.Input, Long>(9) { override fun solveProblem1(input: Input): Long { return getInvalidNumber(input) } override fun solveProblem2(input: Input): Long { val invalidNumber = getInvalidNumber(input) var leftPointer = 0 var currentSum = 0L for ((rightPointer, currentNumber) in input.numbers.withIndex()) { currentSum += currentNumber while (currentSum > invalidNumber && leftPointer < rightPointer) { currentSum -= input.numbers[leftPointer] leftPointer++ } if (currentSum == invalidNumber) { val window = input.numbers.slice(leftPointer..rightPointer) val minValue = window.minOrNull()!! val maxValue = window.maxOrNull()!! return minValue + maxValue } } return -1 } private fun getInvalidNumber(input: Input): Long { for (i in input.preambleSize..input.numbers.size) { Algorithms.twoSum( input = input.numbers.slice((i - input.preambleSize) until i), target = input.numbers[i] ) ?: return input.numbers[i] } return -1 } class Input( val preambleSize: Int, val numbers: List<Long> ) companion object { val module = module { single { Day09() } } } }
0
Kotlin
0
0
8984378d0297f7bc75c5e41a80424d091ac08ad0
1,614
advent-of-code-2020
MIT License
puzzles/src/main/kotlin/com/kotlinground/puzzles/search/binarysearch/platesbetweencandles/platesBetweenCandles.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.search.binarysearch.platesbetweencandles fun platesBetweenCandles(platesAndCandles: String, queries: Array<IntArray>): IntArray { // This will hold the indices of candles in the plates and candles // This allows us to do basic arithmetic on the indices to find the number of plates. // Also, we perform a binary search on this candle list. // We find the left_pos and right_pos indicating the outside candles positions in the input. // Then, We know that the number of plates is given by the interval between the two // bounding candles subtracted by the number of candles in between. // With the indices left_pos and right_pos, we can // derive the number of plates to be (candles[right_pos] - candles[left_pos]) - (right_pos - left_pos). // Space complexity is O(c) where c is the number of candles. // The worst case is that there are all candles. val candles = arrayListOf<Int>() // Adds all candle indices on the table to the candle list. // Time Complexity is O(n) where n is the number of candles and plates. We have to scan over all plates and candles // to check which is a candle before adding its index. for (index in platesAndCandles.indices) { if (platesAndCandles[index] == '|') { candles.add(index) } } // our result list will store answers to each query val result = arrayListOf<Int>() for ((qLeft, qRight) in queries) { var leftPos = -1 var rightPos = -1 // 1. find the index of the first candle that comes after q_left // the index left_pos in candles of the first candle that is greater than q_left means that whenever // candles[index] >= q_left, we can update left_pos until we find the leftmost index at candles[index] >= q_left // (recurse on left-half). var left = 0 var right = candles.size - 1 while (left <= right) { val mid = left + (right - left) / 2 if (candles[mid] >= qLeft) { right = mid - 1 leftPos = mid } else { left = mid + 1 } } // 2. Find the index of the last candle that comes before q_right // The index right_pos in candles of the last candle that is smaller than q_right means that whenever // candles[index] <= q_right, we can update right_pos until we find the rightmost index // at candles[index] >= q_right (recurse on right-half). left = 0 right = candles.size - 1 while (left <= right) { val mid = left + (right - left) / 2 if (candles[mid] <= qRight) { left = mid + 1 rightPos = mid } else { right = mid - 1 } } // result = range between two outermost candles - candle count in between if (rightPos != -1 && leftPos != -1 && rightPos >= leftPos) { val numberOfPlates = candles[rightPos] - candles[leftPos] - (rightPos - leftPos) result.add(numberOfPlates) } else { result.add(0) } } return result.toIntArray() }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
3,223
KotlinGround
MIT License
src/Day01.kt
Svikleren
572,637,234
false
{"Kotlin": 11180}
fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var caloriesSum = 0 for (oneInput: String in input) { when (oneInput) { "" -> { maxCalories = if (caloriesSum > maxCalories) caloriesSum else maxCalories caloriesSum = 0 } else -> caloriesSum += oneInput.toInt() } } return maxCalories } fun part2(input: List<String>): Int { var caloriesByElf = arrayListOf<Int>() var caloriesSum = 0 for (oneInput: String in input) { when (oneInput) { "" -> { caloriesByElf.add(caloriesSum) caloriesSum = 0 } else -> caloriesSum += oneInput.toInt() } } return caloriesByElf.sortedDescending().subList(0, 3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e63be3f83b96a73543bf9bc00c22dc71b6aa0f57
1,033
advent-of-code-2022
Apache License 2.0
src/main/kotlin/leetcode/ArrangingCoins.kt
ykrytsyn
424,099,758
false
{"Kotlin": 8270}
package leetcode /** * # 441. Arranging Coins * [https://leetcode.com/problems/arranging-coins/](https://leetcode.com/problems/arranging-coins/) * * ### You have n coins and you want to build a staircase with these coins. * ### The staircase consists of k rows where the ith row has exactly i coins. * ### The last row of the staircase may be incomplete. * ### Given the integer n, return the number of complete rows of the staircase you will build. * * ### Constraints: * 1 <= n <= 2^31 - 1 */ class ArrangingCoins { /** * Brute force solution: checking every step one by one while we have enough coins for step's capacity */ fun bruteForce(n: Int): Int { var coins = n if (coins <= 1) { return coins } var completedSteps = 0 var currentStep = 1 while (currentStep <= coins) { completedSteps = currentStep coins -= currentStep currentStep++ } return completedSteps } /** * Find the maximum K such that (K*(K+1))/2 <= N * Using Long type due to constraints */ fun binarySearch(n: Int): Int { var left: Long = 0 var right = n.toLong() var k: Long var curr: Long while (left <= right) { k = left + (right - left) / 2 curr = k * (k + 1) / 2 if (curr == n.toLong()) { return k.toInt() } if (n < curr) { right = k - 1 } else { left = k + 1 } } return right.toInt() } }
0
Kotlin
0
0
0acf2a677f8b4a1777b12688cf48bf420353e040
1,629
leetcode-in-kotlin
Apache License 2.0
src/d04/Day04.kt
Ezike
573,181,935
false
{"Kotlin": 7967}
package d04 import readInput fun main() { fun run(m1: String, m2: String, s1: String, s2: String) = s1.toInt() >= m1.toInt() && s2.toInt() <= m2.toInt() || m1.toInt() >= s1.toInt() && m2.toInt() <= s2.toInt() fun run2(m1: String, m2: String, s1: String, s2: String) = (m1.toInt()..m2.toInt()) .windowed(2, partialWindows = true) .any { it.intersect( (s1.toInt()..s2.toInt()) .windowed(2, partialWindows = true) .flatten() .toSet() ).isNotEmpty() } fun run2Better(m1: String, m2: String, s1: String, s2: String) = s1.toInt() <= m2.toInt() && s2.toInt() >= m1.toInt() val input = readInput("d04/Day04").flatMap { it.split(",") } fun part1(): MutableList<String> { val result = mutableListOf<String>() for (i in input.indices step 2) { val (a, b) = input[i].split("-") val (c, d) = input[i + 1].split("-") if (run(a, b, c, d)) { result.add("${input[i]}, ${input[i + 1]}") } } return result } fun part2(): MutableList<String> { val result = mutableListOf<String>() for (i in input.indices step 2) { val (a, b) = input[i].split("-") val (c, d) = input[i + 1].split("-") if (run2Better(a, b, c, d)) { result.add("${input[i]}, ${input[i + 1]}") } } return result } println(part1().size) println(part2().size) }
0
Kotlin
0
0
07ed8acc2dcee09cc4f5868299a8eb5efefeef6d
1,643
advent-of-code
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day9.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.addTo import com.s13g.aoc.resultFrom import kotlin.math.abs import kotlin.math.sign /** * --- Day 9: Rope Bridge --- * https://adventofcode.com/2022/day/9 */ class Day9 : Solver { override fun solve(lines: List<String>): Result { val input = lines.map { it.split(" ") }.map { Pair(it[0], it[1].toInt()) }.toList() return resultFrom(simSnakeOfSize(2, input), simSnakeOfSize(10, input)) } private fun simSnakeOfSize(size: Int, instrs: List<Pair<String, Int>>): Int { val snake = (1..size).map { XY(0, 0) }.toList() val tailVisited = mutableSetOf(snake.last().copy()) val deltas = mapOf( "R" to XY(1, 0), "L" to XY(-1, 0), "U" to XY(0, -1), "D" to XY(0, 1) ) for (instr in instrs) { for (step in 1..instr.second) { snake.first().addTo(deltas[instr.first]!!) for (i in 1 until snake.size) move(snake[i - 1], snake[i]) tailVisited.add(snake.last().copy()) } } return tailVisited.size } private fun move(hPos: XY, tPos: XY) { if (maxOf(abs(hPos.x - tPos.x), abs(hPos.y - tPos.y)) >= 2) tPos.addTo( XY((hPos.x - tPos.x).sign, (hPos.y - tPos.y).sign) ) } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,320
euler
Apache License 2.0
src/main/kotlin/leetcode/TwoSum.kt
ykrytsyn
424,099,758
false
{"Kotlin": 8270}
package leetcode /** * # 1. Two Sum * [https://leetcode.com/problems/two-sum/](https://leetcode.com/problems/two-sum/) * * ### Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. * ### You may assume that each input would have exactly one solution, and you may not use the same element twice. * ### You can return the answer in any order. * */ class TwoSum { /** * Brute Force */ fun bruteForce(nums: IntArray, target: Int): IntArray? { for (i in nums.indices) { for (j in i + 1 until nums.size) { if (nums[j] == target - nums[i]) { return intArrayOf(i, j) } } } // In case there is no solution, we'll just return null return null } /** * Two-pass Hash Table */ fun twoPassHashTable(nums: IntArray, target: Int): IntArray? { val map: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { map[nums[i]] = i } for (i in nums.indices) { val complement = target - nums[i] if (map.containsKey(complement) && map[complement] != i) { return intArrayOf(i, map[complement]!!) } } // In case there is no solution, we'll just return null return null } /** * One-pass Hash Table */ fun onePassHashTable(nums: IntArray, target: Int): IntArray? { val map: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { val complement = target - nums[i] if (map.containsKey(complement)) { return intArrayOf(map[complement]!!, i) } map[nums[i]] = i } // In case there is no solution, we'll just return null return null } }
0
Kotlin
0
0
0acf2a677f8b4a1777b12688cf48bf420353e040
1,889
leetcode-in-kotlin
Apache License 2.0
src/main/kotlin/day19.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
var distinctCombinations = 0L fun day19 (lines: List<String>) { val workflows = parseWorkFlows(lines.filter { it.isNotEmpty() }) val parts = parsePartRatings(lines.filter { it.isNotEmpty() }) val acceptedPartsRating = parts.filter { isPartAccepted(workflows, it) }. map { it.xRating + it.mRating + it.aRating + it.sRating}.sum() println("Day 19 part 1: $acceptedPartsRating") findAcceptedCombinations(1, 4000, 1, 4000, 1, 4000, 1, 4000, "in", workflows) println("Day 19 part 2: $distinctCombinations") println() } fun findAcceptedCombinations( minX: Long, maxX: Long, minM: Long, maxM: Long, minA: Long, maxA: Long, minS: Long, maxS: Long, workFlowName: String, workflows: MutableMap<String, List<WorkflowStep>> ) { if (workFlowName == "A") { distinctCombinations += ((minX..maxX).count() * 1L * (minM..maxM).count() * 1L * (minA..maxA).count() * 1L * (minS..maxS).count() * 1L) return } else if (workFlowName == "R") { return } val currentWorkFlow = workflows[workFlowName]!! //var noOfAccepted = 1L var updatedMinX = minX var updatedMaxX = maxX var updatedMinM = minM var updatedMaxM = maxM var updatedMinA = minA var updatedMaxA = maxA var updatedMinS = minS var updatedMaxS = maxS for (i in currentWorkFlow.indices) { val step = currentWorkFlow[i] if (step.condition != null) { if (step.condition == '<') { if (step.category!! == 'x') { findAcceptedCombinations(updatedMinX, step.conditionNumber!! - 1, updatedMinM, updatedMaxM, updatedMinA, updatedMaxA, updatedMinS, updatedMaxS, step.destination, workflows) updatedMinX = step.conditionNumber } else if (step.category == 'm') { findAcceptedCombinations(updatedMinX, updatedMaxX, updatedMinM, step.conditionNumber!! - 1, updatedMinA, updatedMaxA, updatedMinS, updatedMaxS, step.destination, workflows) updatedMinM = step.conditionNumber } else if (step.category == 'a') { findAcceptedCombinations(updatedMinX, updatedMaxX, updatedMinM, updatedMaxM, updatedMinA, step.conditionNumber!! - 1, updatedMinS, updatedMaxS, step.destination, workflows) updatedMinA = step.conditionNumber } else if (step.category == 's') { findAcceptedCombinations(updatedMinX, updatedMaxX, updatedMinM, updatedMaxM, updatedMinA, updatedMaxA, updatedMinS, step.conditionNumber!! - 1, step.destination, workflows) updatedMinS = step.conditionNumber } continue } else if (step.condition == '>') { if (step.category!! == 'x') { findAcceptedCombinations(step.conditionNumber!! + 1, updatedMaxX, updatedMinM, updatedMaxM, updatedMinA, updatedMaxA, updatedMinS, updatedMaxS, step.destination, workflows) updatedMaxX = step.conditionNumber } else if (step.category == 'm') { findAcceptedCombinations(updatedMinX, updatedMaxX, step.conditionNumber!! + 1, updatedMaxM, updatedMinA, updatedMaxA, updatedMinS, updatedMaxS, step.destination, workflows) updatedMaxM = step.conditionNumber } else if (step.category == 'a') { findAcceptedCombinations(updatedMinX, updatedMaxX, updatedMinM, updatedMaxM, step.conditionNumber!! + 1, updatedMaxA, updatedMinS, updatedMaxS, step.destination, workflows) updatedMaxA = step.conditionNumber } else if (step.category == 's') { findAcceptedCombinations(updatedMinX, updatedMaxX, updatedMinM, updatedMaxM, updatedMinA, updatedMaxA, step.conditionNumber!! + 1, updatedMaxS, step.destination, workflows) updatedMaxS = step.conditionNumber } continue } } else { findAcceptedCombinations(updatedMinX, updatedMaxX, updatedMinM, updatedMaxM, updatedMinA, updatedMaxA, updatedMinS, updatedMaxS, step.destination, workflows) } } } fun isPartAccepted(workflows: MutableMap<String, List<WorkflowStep>>, part: Part): Boolean { var currentWorkFlow = workflows["in"]!! while(true) { for (i in currentWorkFlow.indices) { val step = currentWorkFlow[i] if (step.condition != null) { val valueToCheck = when(step.category!!) { 'x' -> part.xRating 'm' -> part.mRating 'a' -> part.aRating else -> part.sRating } if (step.condition == '<' && valueToCheck > step.conditionNumber!!) { continue } else if (step.condition == '>' && valueToCheck < step.conditionNumber!!) { continue } } return when (val destination = step.destination) { "A" -> true "R" -> false else -> { currentWorkFlow = workflows[destination]!! break } } } } } fun parsePartRatings(lines: List<String>): MutableList<Part> { val parts = mutableListOf<Part>() lines.filter { it.startsWith("{") }.forEach { line -> val matches = Regex("[0-9]+").findAll(line) val numbers = matches.map { Integer.parseInt(it.value) }.toList() parts.add(Part(numbers[0], numbers[1], numbers[2], numbers[3])) } return parts } fun parseWorkFlows(lines: List<String>): MutableMap<String, List<WorkflowStep>> { val workflows = mutableMapOf<String, List<WorkflowStep>>() lines.filterNot { it.startsWith("{") }.map{ it.dropLast(1) }.forEach { line -> val workflow = mutableListOf<WorkflowStep>() val name = line.split("{")[0] val steps = line.split("{")[1].split(",") steps.forEach { step -> if (step.contains(":")) { val category = step[0] val condition = step[1] val conditionNumber = (step.filter { it.isDigit() }.toLong()) val destination = step.split(":")[1] workflow.add(WorkflowStep(condition, category, conditionNumber, destination)) } else { workflow.add(WorkflowStep(null, null, null, step)) } } workflows[name] = workflow } return workflows } data class Part(val xRating: Int, val mRating: Int, val aRating: Int, val sRating: Int) data class WorkflowStep(val condition: Char?, val category: Char?, val conditionNumber: Long?, val destination: String)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
6,915
advent_of_code_2023
MIT License
src/main/kotlin/com/pandarin/aoc2022/Day3.kt
PandarinDev
578,619,167
false
{"Kotlin": 6586}
package com.pandarin.aoc2022 import java.util.stream.Collectors fun main() { val inputLines = Common.readInput("/day3.txt").split("\n").filter { it.isNotEmpty() } val itemPriorities = generateItemPriorities() // First part var totalPriority = 0 for (line in inputLines) { val halfLength = line.length / 2 val firstCompartment = line.substring(0, halfLength) val secondCompartment = line.substring(halfLength) val matchingItems = findMatchingItems(firstCompartment, secondCompartment) totalPriority += matchingItems.sumOf { itemPriorities[it]!! } } println("Part1: $totalPriority") // Second part totalPriority = 0 for ((first, second, third) in inputLines.chunked(3)) { val matchingItems = findMatchingItems(first, second, third) totalPriority += matchingItems.sumOf { itemPriorities[it]!! } } println("Part2: $totalPriority") } fun findMatchingItems(vararg items: String): Set<Char> { return items[0].chars() .mapToObj { it.toChar() } .filter { char: Char -> items.all { it.contains(char) } } .collect(Collectors.toUnmodifiableSet()) } fun generateItemPriorities(): Map<Char, Int> { val itemPriorities = mutableMapOf<Char, Int>() // Lowercase letters for ((index, char) in ('a'..'z').withIndex()) { itemPriorities[char] = index + 1 } // Uppercase letters for ((index, char) in ('A'..'Z').withIndex()) { itemPriorities[char] = index + 27 } return itemPriorities }
0
Kotlin
0
0
42c35d23129cc9f827db5b29dd10342939da7c99
1,569
aoc2022
MIT License
BackEnd/src/main/kotlin/com/sorbonne/daar/algorithms/kmp/KMPAlgorithm.kt
MalickLSy
622,912,085
false
null
package com.sorbonne.daar.algorithms.kmp import java.util.* /** * Author <NAME> */ class KMPAlgorithm { fun search(pattern: String, text: String) : Int { val textLen = text.length val factorLen : Int = pattern.length val carryOver = computeCarryOverArray(pattern) var i = 0 var j = 0; while(i<textLen){ if(text[i]==pattern[j]){ i++ j++ if(j==factorLen){ return (i-factorLen); } }else{ i = (i - carryOver[j]); j = 0 } } return -1; } fun computeCarryOverArray(pattern: String) : IntArray { val factorLen = pattern.length var carryOver = IntArray(factorLen + 1) carryOver[0] = -1 carryOver[factorLen] = 0 for (i in 1..(factorLen - 1)) { /* step 1 */ carryOver[i] = longestPrefixSuffix(pattern.substring(0,i)) /* step 2 */ if (pattern[carryOver[i]] == pattern[i] && carryOver[carryOver[i]] == -1) { carryOver[i] = -1 } /* step 3 */ if(carryOver[i] < 0){ continue; } if (pattern[carryOver[i]] == pattern[i] && carryOver[carryOver[i]] != -1) { carryOver[i] = carryOver[carryOver[i]] } } return carryOver; } fun longestPrefixSuffix(s: String): Int { val n = s.length if (n < 2) { return 0 } var len = 0 var i = 1 while (i < n) { if (s[i] == s[len]) { ++len ++i } else { i = i - len + 1 len = 0 } } return len } }
0
Kotlin
0
0
b22e9e4f1410a63cf689ed66fa88e0a84a20f2a0
1,873
search-engine-book
MIT License
src/Utils.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
import java.io.File /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() fun String.allInts() = allIntsInString(this) fun allIntsInString(line: String): List<Int> { return """-?\d+""".toRegex().findAll(line) .map { it.value.toInt() } .toList() } fun <T> List<T>.nth(n: Int): T = this[n % size] inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int { for (i in this.indices.reversed()) { if (predicate(this[i])) { return i } } return -1 } data class Point(var x: Int = 0, var y: Int = 0) { operator fun plus(other: Point): Point { return Point(this.x + other.x, this.y + other.y) } fun adjacents(): Set<Point> = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1) ) fun set(x: Int, y: Int) { this.x = x this.y = y } operator fun plusAssign(p: Point) { x += p.x y += p.y } operator fun minus(point: Point): Point { return Point(x + point.x, y - point.y) } } inline fun List<List<Char>>.forEach(block: (row: Int, col: Int) -> Unit) { for (i in indices) { val inner = this[i] for (j in inner.indices) { block(i, j) } } } fun List<List<Char>>.maxOf(block: (row: Int, col: Int) -> Int): Int { var max = 0 forEach { row, col -> val value = block(row, col) max = if (value > max) value else max } return max } fun List<List<Char>>.count(block: (row: Int, col: Int) -> Boolean): Int { var count = 0 forEach { row, col -> count += if (block(row, col)) 1 else 0 } return count }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
1,805
aoc-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2018/Day25.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 25 - Four-Dimensional Adventure * * Problem Description: http://adventofcode.com/2018/day/25 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day25/ */ package com.ginsberg.advent2018 import java.lang.Math.abs import java.util.ArrayDeque class Day25(rawInput: List<String>) { private val points: List<Point4d> = rawInput.map { Point4d.of(it) } fun solvePart1(): Int = constellations(mapNeighbors()).count() private fun mapNeighbors(): Map<Point4d, Set<Point4d>> = points.map { point -> Pair(point, points.filterNot { it == point }.filter { point.distanceTo(it) <= 3 }.toSet()) }.toMap() private fun constellations(neighbors: Map<Point4d, Set<Point4d>>): Sequence<Set<Point4d>> = sequence { val allPoints = neighbors.keys.toMutableList() while (allPoints.isNotEmpty()) { val point = allPoints.removeAt(0) val thisConstellation = mutableSetOf(point) val foundNeighbors = ArrayDeque<Point4d>(neighbors.getValue(point)) while (foundNeighbors.isNotEmpty()) { foundNeighbors.removeFirst().also { allPoints.remove(it) // Not the basis of a new constellation thisConstellation.add(it) // Because it is part of our constellation // And all this point's neighbors are therefore part of our constellation too foundNeighbors.addAll(neighbors.getValue(it).filterNot { other -> other in thisConstellation }) } } // We've run out of found neighbors to check, this is a constellation. yield(thisConstellation) } } private data class Point4d(val x: Int, val y: Int, val z: Int, val t: Int) { fun distanceTo(other: Point4d): Int = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) + abs(t - other.t) companion object { fun of(input: String): Point4d { val (x, y, z, t) = input.split(",").map { it.trim().toInt() } return Point4d(x, y, z, t) } } } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
2,233
advent-2018-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountBalls.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL import kotlin.math.max /** * 1742. Maximum Number of Balls in a Box * @see <a href="https://leetcode.com/problems/maximum-number-of-balls-in-a-box">Source</a> */ fun interface CountBalls { operator fun invoke(lowLimit: Int, highLimit: Int): Int companion object { const val ARR_SIZE = 46 } } class CountBallsBruteforce : CountBalls { override operator fun invoke(lowLimit: Int, highLimit: Int): Int { val cnt = IntArray(CountBalls.ARR_SIZE) var max = 0 for (i in lowLimit..highLimit) { var num = i var sum = 0 while (num > 0) { sum += num % DECIMAL num /= DECIMAL } max = max(++cnt[sum], max) } return max } } class CountBalls2 : CountBalls { override operator fun invoke(lowLimit: Int, highLimit: Int): Int { val box = IntArray(CountBalls.ARR_SIZE) var lo = lowLimit var id = 0 while (lo > 0) { // compute box id for lowLimit. id += lo % DECIMAL lo /= DECIMAL } ++box[id] for (i in lowLimit + 1..highLimit) { // compute all other box ids. var digits = i while (digits % DECIMAL == 0) { // for ball numbers with trailing 0's, decrease 9 for each 0. id -= 9 digits /= DECIMAL } ++box[++id] } return box.max() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,143
kotlab
Apache License 2.0
src/Day06.kt
mzlnk
573,124,510
false
{"Kotlin": 14876}
fun main() { fun part1(input: List<String>): Int { val line = input.first() val checker = HashSet<Char>() for (i in 0 until (line.length - 3)) { for (j in 0..3) { checker.add(line[i + j]) } if (checker.size == 4) { return i + 4 } checker.clear() } return -1 } fun part2(input: List<String>): Int { val line = input.first() val checker = HashSet<Char>() for (i in 0 until (line.length - 13)) { for (j in 0..13) { checker.add(line[i + j]) } if (checker.size == 14) { return i + 14 } checker.clear() } return -1 } // test if implementation meets criteria from the description, like: val testInput1 = readInput("Day06_test01") val testInput2 = readInput("Day06_test02") val testInput3 = readInput("Day06_test03") val testInput4 = readInput("Day06_test04") check(part1(testInput1) == 5) check(part1(testInput2) == 6) check(part1(testInput3) == 10) check(part1(testInput4) == 11) check(part2(testInput1) == 23) check(part2(testInput2) == 23) check(part2(testInput3) == 29) check(part2(testInput4) == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5
1,428
advent-of-code-2022
Apache License 2.0
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Quick_Sort/Quick_Sort.kt
rajatenzyme
325,100,742
false
{"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189}
/* QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot.It's Best case complexity is n*log(n) & Worst case complexity is n^2. */ //partition array fun quick_sort(A: Array<Int>, p: Int, r: Int) { if (p < r) { var q: Int = partition(A, p, r) quick_sort(A, p, q - 1) quick_sort(A, q + 1, r) } } //assign last value as pivot fun partition(A: Array<Int>, p: Int, r: Int): Int { var x = A[r] var i = p - 1 for (j in p until r) { if (A[j] <= x) { i++ exchange(A, i, j) } } exchange(A, i + 1, r) return i + 1 } //swap fun exchange(A: Array<Int>, i: Int, j: Int) { var temp = A[i] A[i] = A[j] A[j] = temp } fun main(arg: Array<String>) { print("Enter no. of elements :") var n = readLine()!!.toInt() println("Enter elements : ") var A = Array(n, { 0 }) for (i in 0 until n) A[i] = readLine()!!.toInt() quick_sort(A, 0, A.size - 1) println("Sorted array is : ") for (i in 0 until n) print("${A[i]} ") } /*-------OUTPUT-------------- Enter no. of elements :6 Enter elements : 4 8 5 9 2 6 Sorted array is : 2 4 5 6 8 9 */
0
C++
0
0
65a0570153b7e3393d78352e78fb2111223049f3
1,259
Coding-Journey
MIT License
src/questions/AssignCookies.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import kotlin.test.assertEquals /** * Assume you are an awesome parent and want to give your children some cookies. * But, you should give each child at most one cookie. * Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; * and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, * and the child i will be content. * Your goal is to maximize the number of your content children and output the maximum number. * * [Source](https://leetcode.com/problems/assign-cookies/) */ @UseCommentAsDocumentation private fun findContentChildren(g: IntArray, s: IntArray): Int { if (s.isEmpty()) return 0 // Sort g.sort() s.sort() // Store index of g that was satisfied val result = mutableSetOf<Int>() for (i in 0..s.lastIndex) { // every cookie for (j in 0..g.lastIndex) { // loop over kids if (!result.contains(j) && g[j] <= s[i]) { // hasn't already been satisfied and can be satisfied result.add(j) // give cookie break } } } return result.size } private fun findContentChildrenOptimal(g: IntArray, s: IntArray): Int { if (s.isEmpty()) return 0 // Sort g.sort() s.sort() var count = 0 for (i in 0..s.lastIndex) { // every cookie val greed = g.getOrNull(count) ?: return count // try to satisfy the NEXT easiest/lowest greed factor first if (greed <= s[i]) count++ } return count } fun main() { assertEquals( 2, findContentChildrenOptimal(g = intArrayOf(10, 9, 8, 7), s = intArrayOf(5, 6, 7, 8)) ) assertEquals( 4, findContentChildrenOptimal(g = intArrayOf(10, 9, 8, 7), s = intArrayOf(10, 9, 8, 7)) ) assertEquals( 1, findContentChildrenOptimal(g = intArrayOf(1, 2, 3), s = intArrayOf(1, 1)) ) assertEquals( 2, findContentChildrenOptimal(g = intArrayOf(1, 2), s = intArrayOf(1, 2, 3)) ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,073
algorithms
MIT License
app/src/main/kotlin/day07/Day07.kt
meli-w
433,710,859
false
{"Kotlin": 52501}
package day07 import common.InputRepo import common.readSessionCookie import common.solve import kotlin.math.abs fun main(args: Array<String>) { val day = 7 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay07Part1, ::solveDay07Part2) } fun solveDay07Part1(input: List<String>): Int { var lastPosition = 0 var useFuel = -1 input .first() .split(",") .map { it.toInt() } .sorted() .let { lastPosition = it.last() it } .groupBy { it } .mapValues { (_, value) -> value.size } .let { map -> repeat(lastPosition) { position -> var fuel = 0 map.forEach { (innerPosition, count) -> fuel += abs((innerPosition - position) * count) } if (useFuel == -1 || useFuel > fuel) { useFuel = fuel } } } return useFuel } fun solveDay07Part2(input: List<String>): Int { var lastPosition = 0 var useFuel = -1 input .first() .split(",") .map { it.toInt() } .sorted() .let { lastPosition = it.last() it } .groupBy { it } .mapValues { (_, value) -> value.size } .let { map -> repeat(lastPosition) { position -> var fuel = 0 map.forEach { (innerPosition, count) -> val steps = abs(innerPosition - position) fuel += (steps * (steps + 1)) / 2 * count } if (useFuel == -1 || useFuel > fuel) { useFuel = fuel } } } return useFuel }
0
Kotlin
0
1
f3b96c831d6c8e21de1ac866cf9c64aaae2e5ea1
1,811
AoC-2021
Apache License 2.0
AdventOfCode2018/src/main/kotlin/net/twisterrob/challenges/adventOfCode2018/day7/Solution.kt
TWiStErRob
136,539,340
false
{"Kotlin": 104880, "Java": 11319}
@file:Suppress("SpreadOperator") package net.twisterrob.challenges.adventOfCode2018.day7 import java.io.File fun main(vararg args: String) { val file = args.first() val fileContents = File(file).readText() solve(fileContents) } fun solve(input: String): String { val linePattern = Regex("""^Step ([A-Z]) must be finished before step ([A-Z]) can begin.$""") fun MatchResult.groupAsStep(group: Int) = this.groups[group]!!.value[0] fun parseLine(line: String): Pair<Char, Char> = linePattern.matchEntire(line)!!.let { match -> match.groupAsStep(1) to match.groupAsStep(2) } val constraints = input .lines() .filter(String::isNotEmpty) .map(::parseLine) return solve(*constraints.toTypedArray()) } fun solve(vararg partConstraints: Pair<Char, Char>): String = findOrder(*partConstraints).joinToString(separator = "") /** * @see [https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm] */ private fun findOrder(vararg edges: Pair<Char, Char>): List<Char> { class Graph(vararg edges: Pair<Char, Char>) { private val graph = mutableSetOf(*edges) operator fun minusAssign(edge: Pair<Char, Char>) { graph -= edge } fun hasIncomingEdges(node: Char) = graph.any { it.second == node } // this blows up the O complexity, but the solvable input is small fun dependentsFrom(node: Char) = graph.filter { it.first == node } fun hasAnyEdges() = graph.isNotEmpty() } val graph = Graph(*edges) val allNodes = edges.flatMap { listOf(it.first, it.second) }.toSet() // SortedSet to satisfy "If more than one step is ready, choose the step which is first alphabetically." val possibleNextNodes = allNodes.filterNot(graph::hasIncomingEdges).toSortedSet() val result = mutableListOf<Char>() while (possibleNextNodes.isNotEmpty()) { val node = possibleNextNodes.first() possibleNextNodes -= node result += node val nextEdges = graph.dependentsFrom(node) nextEdges.forEach { edge -> graph -= edge if (!graph.hasIncomingEdges(edge.second)) { possibleNextNodes += edge.second } } } if (graph.hasAnyEdges()) { error("cycle") } else { return result } }
1
Kotlin
1
2
5cf062322ddecd72d29f7682c3a104d687bd5cfc
2,370
TWiStErRob
The Unlicense