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/aoc2017/PermutationPromenade.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.rotate import komu.adventofcode.utils.swap private val regexSpin = Regex("""s(\d+)""") private val regexExchange = Regex("""x(\d+)/(\d+)""") private val regexPartner = Regex("""p(\w)/(\w)""") private const val DEFAULT_PROGRAMS = "abcdefghijklmnop" fun dance(input: String, programs: String = DEFAULT_PROGRAMS, loops: Int = 1): String { val ops = Op.parseList(input) val dance = PermutationPromenade(programs) repeat(loops % dancePeriod(ops, programs)) { for (op in ops) op.func(dance) } return dance.toString() } private fun dancePeriod(ops: List<Op>, programs: String): Int { val dance = PermutationPromenade(programs) var counter = 0 while (true) { for (op in ops) op.func(dance) counter++ if (dance.toString() == programs) return counter } } private class Op(val func: PermutationPromenade.() -> Unit) { companion object { fun parseList(str: String): List<Op> = str.trim().split(",").map { Op.parse(it) } fun parse(str: String): Op { regexSpin.matchEntire(str)?.let { m -> val x = m.groupValues[1].toInt() return Op { spin(x) } } regexExchange.matchEntire(str)?.let { m -> val a = m.groupValues[1].toInt() val b = m.groupValues[2].toInt() return Op { exchange(a, b) } } regexPartner.matchEntire(str)?.let { m -> val a = m.groupValues[1].first() val b = m.groupValues[2].first() return Op { partner(a, b) } } error("invalid input '$str'") } } } private class PermutationPromenade(programs: String) { val state = programs.toCharArray().toMutableList() fun spin(x: Int) { state.rotate(x) } fun exchange(a: Int, b: Int) { state.swap(a, b) } fun partner(a: Char, b: Char) { state.swap(state.indexOf(a), state.indexOf(b)) } override fun toString() = state.joinToString("") }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,176
advent-of-code
MIT License
src/Day05.kt
Oli2861
572,895,182
false
{"Kotlin": 16729}
fun prepareInput(input: List<String>): Pair<List<Triple<Int, Int, Int>>, MutableList<ArrayDeque<Char>>> { val splitIndex = input.indexOfFirst { it.isEmpty() } - 1 val instructionString = input.subList(splitIndex + 2, input.size) val instructions: List<Triple<Int, Int, Int>> = toInstructions(instructionString) val storage: List<String> = input.subList(0, splitIndex) val stackList = toStackList(storage) return Pair(instructions, stackList) } fun toStackList(storage: List<String>): MutableList<ArrayDeque<Char>> { val stackList: MutableList<ArrayDeque<Char>> = MutableList(9) { ArrayDeque<Char>() } for (storageRow in storage) { for ((stackNum, index) in (1 until storageRow.length step 4).withIndex()) { val curr = storageRow[index] if (curr.isLetter()) stackList[stackNum].add(curr) } } return stackList } fun toInstructions(input: List<String>): List<Triple<Int, Int, Int>> { return input.map { row -> val onlyDigits = row.filter { it.isDigit() || it == ' ' }.split(' ').filter { it.matches(Regex("[0-9]+")) } return@map Triple( onlyDigits[0].toInt(), onlyDigits[1].toInt(), onlyDigits[2].toInt() ) } } fun simulateCrateMovement(input: List<String>, canMoveMultiple: Boolean = false): String { val (instructions, stackList) = prepareInput(input) for ((index, instruction) in instructions.withIndex()) { val (amount, startIndex, destinationIndex) = instruction val startStack = stackList[startIndex - 1] val destinationStack = stackList[destinationIndex - 1] if (canMoveMultiple) { val payload = startStack.slice(0 until amount) for (i in 0 until amount) { startStack.removeFirst() } destinationStack.addAll(0, payload) } else { for (i in 0 until amount) { val payload = startStack.removeFirst() destinationStack.addFirst(payload) } } } val firstEntries = mutableListOf<Char>() stackList.forEach { firstEntries.add(it.first()) } return firstEntries.joinToString("") } fun main() { val input = readInput("Day05_test") val result = simulateCrateMovement(input) println(result) check(result == "BSDMQFLSP") val result2 = simulateCrateMovement(input, true) println(result2) check(result2 == "PGSQBFLDP") }
0
Kotlin
0
0
138b79001245ec221d8df2a6db0aaeb131725af2
2,462
Advent-of-Code-2022
Apache License 2.0
src/Day05/Day05.kt
G-lalonde
574,649,075
false
{"Kotlin": 39626}
package Day05 import readInput import java.util.regex.Pattern fun main() { fun stackCrates(string: String, piles: List<Stack<Char>>) { val regex = """\[(.*?)\]""" val pattern = Pattern.compile(regex) val matcher = pattern.matcher(string) while (matcher.find()) { val group = matcher.group(1) val index = matcher.start(1) piles[(index - 1) / 4].push(group[0]) } } fun part1(input: List<String>): String { val indexOfPiles = input.indexOfFirst { it.startsWith(" 1") } val pileCount = input[indexOfPiles].split(" ").last().toInt() val piles = mutableListOf<Stack<Char>>() for (i in 0 until pileCount) { piles.add(Stack()) } input.subList(0, indexOfPiles).asReversed().forEach { stackCrates(it, piles) } val regex = "\\d+".toRegex() input.subList(indexOfPiles + 2, input.size).forEach { val (numberOfOperation, from, to) = regex.findAll(it).map { it.value.toInt() } .toList() for (i in 0 until numberOfOperation) { val value = piles[from - 1].pop() if (value != null) { piles[to - 1].push(value) } } } var result = "" for (i in 0 until pileCount) { result += piles[i].peek() } return result } fun part2(input: List<String>): String { val indexOfPiles = input.indexOfFirst { it.startsWith(" 1") } val pileCount = input[indexOfPiles].split(" ").last().toInt() val piles = mutableListOf<Stack<Char>>() for (i in 0 until pileCount) { piles.add(Stack()) } input.subList(0, indexOfPiles).asReversed().forEach { stackCrates(it, piles) } val regex = "\\d+".toRegex() input.subList(indexOfPiles + 2, input.size).forEach { val (numberOfOperation, from, to) = regex.findAll(it).map { it.value.toInt() } .toList() val tempStack = Stack<Char>() for (i in 0 until numberOfOperation) { val value = piles[from - 1].pop() if (value != null) { tempStack.push(value) } } for (i in 0 until numberOfOperation) { val value = tempStack.pop() if (value != null) { piles[to - 1].push(value) } } } var result = "" for (i in 0 until pileCount) { result += piles[i].peek() } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05/Day05_test") check(part1(testInput) == "CMZ") { "Got instead : ${part1(testInput)}" } check(part2(testInput) == "MCD") { "Got instead : ${part2(testInput)}" } val input = readInput("Day05/Day05") println("Answer for part 1 : ${part1(input)}") println("Answer for part 2 : ${part2(input)}") } class Stack<T> { private val list = mutableListOf<T>() fun push(element: T) { list.add(element) } fun pop(): T? { return if (list.isEmpty()) null else list.removeAt(list.size - 1) } fun peek(): T? { return list.lastOrNull() } }
0
Kotlin
0
0
3463c3228471e7fc08dbe6f89af33199da1ceac9
3,425
aoc-2022
Apache License 2.0
src/com/aaron/helloalgorithm/algorithm/数组/_1_两数之和.kt
aaronzzx
431,740,908
false
null
package com.aaron.helloalgorithm.algorithm.数组 import com.aaron.helloalgorithm.algorithm.LeetCode import com.aaron.helloalgorithm.algorithm.Printer /** * # 1. 两数之和 * * 给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target * 的那两个整数,并返回它们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 * * 你可以按任意顺序返回答案。 * * 示例 1: * * ``` * 输入:nums = [2,7,11,15], target = 9 * 输出:[0,1] * 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 * ``` * * 示例 2: * * ``` * 输入:nums = [3,2,4], target = 6 * 输出:[1,2] * ``` * * 示例 3: * * ``` * 输入:nums = [3,3], target = 6 * 输出:[0,1] * ``` * * 来源:力扣(LeetCode) * * 链接:[https://leetcode-cn.com/problems/two-sum] * * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author <EMAIL> * @since 2021/11/18 */ class _1_两数之和 private val NUMS = intArrayOf(21, 11, 43, 25, 6, 1, 76) private const val TARGET = 101 fun LeetCode.数组.run_1_两数之和_暴力枚举( nums: IntArray = com.aaron.helloalgorithm.algorithm.数组.NUMS, target: Int = com.aaron.helloalgorithm.algorithm.数组.TARGET ) { val indices = LeetCode.数组._1_两数之和_暴力枚举(nums, target) Printer.print( title = "两数之和-暴力枚举", input = "nums = ${nums.contentToString()}, target = $target", output = "${indices.contentToString()}" ) } fun LeetCode.数组.run_1_两数之和_哈希表( nums: IntArray = com.aaron.helloalgorithm.algorithm.数组.NUMS, target: Int = com.aaron.helloalgorithm.algorithm.数组.TARGET ) { val indices = LeetCode.数组._1_两数之和_哈希表(nums, target) Printer.print( title = "两数之和-哈希表", input = "nums = ${nums.contentToString()}, target = $target", output = "${indices.contentToString()}" ) } /** * # 解法:暴力枚举 * * 选定一个值,然后遍历后面所有值,分别相加判断是否等于期望和。很显然就需要两个指针 i 和 j , * 外层循环 i 为了找到选定值,内层循环 j 为了找到被加值。 * * T(n) = O(n^2), S(n) = O(1) */ fun LeetCode.数组._1_两数之和_暴力枚举(nums: IntArray, target: Int): IntArray { for (i in nums.indices) { for (j in (i + 1)..nums.lastIndex) { if (nums[i] + nums[j] == target) { return intArrayOf(i, j) } } } return intArrayOf() } /** * # 解法:哈希表 * * 由于期望和是已知条件,并且遍历过程中被加值也是已知条件(`nums[i]`),可以得出 * `选定值 = target - nums[i]` ,因此当每次循环时可以将 `nums[i]` 存于哈希表中, * 这样选定值就可以从哈希表中去匹配,当匹配成功后取出索引进行返回。 * * 另外选定值不可以作为 map 的 value ,如果作为 value ,当查找时本质上是通过遍历 * 整个哈希表,这样效率其实并没有变化,而作为 key ,map 实际是将 key hash 过后 * 变为指定索引,那么通过 key 来查找时就相当于直接使用索引查找。 * * T(n) = O(n), S(n) = O(n) */ fun LeetCode.数组._1_两数之和_哈希表(nums: IntArray, target: Int): IntArray { val map = hashMapOf<Int, Int>() for (i in nums.indices) { if (map.containsKey(target - nums[i])) { return intArrayOf(map[target - nums[i]]!!, i) } map[nums[i]] = i } return intArrayOf() }
0
Kotlin
0
0
2d3d823b794fd0712990cbfef804ac2e138a9db3
3,778
HelloAlgorithm
Apache License 2.0
src/day06/Day06.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day06 import readInput fun main() { val input = readInput(parent = "src/day06", name = "Day06_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartOne(input: List<String>)= solve(input, 4) private fun solvePartTwo(input: List<String>) = solve(input, 14) private fun solve(input: List<String>, distinctCharacters: Int): Int { var lastSeen = mutableListOf<Char>() val numberOfEachLetter = mutableMapOf<Char, Int>() for ((i, c) in input[0].withIndex()) { numberOfEachLetter[c] = if (numberOfEachLetter.contains(c)) { numberOfEachLetter[c]!! + 1 } else { 1 } if (numberOfEachLetter.size == distinctCharacters) { return i + 1 } if (lastSeen.size < distinctCharacters - 1) { lastSeen.add(c) } else { val firstC = lastSeen.first() val toReduce = numberOfEachLetter[firstC]!! if (toReduce > 1) { numberOfEachLetter[firstC] = toReduce - 1 } else { numberOfEachLetter.remove(firstC) } lastSeen = (lastSeen.drop(1) + listOf(c)).toMutableList() } } return -1 }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
1,251
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/bhsoft/decisiontree/SampleApp.kt
bholota
103,860,306
false
null
package com.bhsoft.decisiontree /** * Kotlin implementation of classification decision tree learning based on * https://github.com/random-forests/tutorials/blob/master/decision_tree.py */ class DecisionTree(val headers: Array<String>) { private var trainedTree: GraphNode? = null /** * Counts how many times particular class occurs in provided data table * @return map with label as key and count as value */ fun classCount(rows: Array<Array<Value>>): MutableMap<String, Int> { var classCounter = mutableMapOf<String, Int>() for (row in rows) { val label = (row.last() as Text).text if (!classCounter.containsKey(label)) { classCounter[label] = 0 } classCounter[label] = classCounter[label]!! + 1 } return classCounter } /** * Splits data based on provided question * @return pair that contains matching and non matching elements arrays */ fun split(rows: Array<Array<Value>>, question: Question): Pair<Array<Array<Value>>, Array<Array<Value>>> { var trueRows = mutableListOf<Array<Value>>() var falseRows = mutableListOf<Array<Value>>() for (row in rows) { if (question.match(row)) { trueRows.add(row) } else { falseRows.add(row) } } return Pair(trueRows.toTypedArray(), falseRows.toTypedArray()) } /** * Information gain calculation with gini impurity * @return gini impurity for data */ fun gini(left: Array<Array<Value>>, right: Array<Array<Value>>, currentUncertainty: Float): Float { val p = left.size.toFloat() / (left.size.toFloat() + right.size) return currentUncertainty - p * calculateImpurity(left) - (1 - p) * calculateImpurity(right) } /** * Calculate impurity for gini algorithm * @return impurity for data */ private fun calculateImpurity(rows: Array<Array<Value>>): Float { val counts = classCount(rows) var impurity = 1f for (count in counts) { val probabilityLabel = count.value / rows.size.toFloat() impurity -= probabilityLabel * probabilityLabel } return impurity } /** * Find best split that will be best information gain * @return pair with info gain and question */ fun findBestSplit(rows: Array<Array<Value>>): Pair<Float, Question?> { var bestGain = 0f var bestQuestion: Question? = null var currentUncertanity = calculateImpurity(rows) val featureCount = rows[0].size - 2 // last feature is label for (col in 0..featureCount) { val values = rows.map { it[col] }.distinct() for (v in values) { val question = Question(headers[col], col, v) val trueFalseRows = split(rows, question) if (trueFalseRows.first.isEmpty() or trueFalseRows.second.isEmpty()) { continue } val gain = gini(trueFalseRows.first, trueFalseRows.second, currentUncertanity) if (gain >= bestGain) { bestGain = gain bestQuestion = question } } } return Pair(bestGain, bestQuestion) } /** * @return trained tree for provided data */ fun trainTree(rows: Array<Array<Value>>): GraphNode { val (gain, question) = findBestSplit(rows) if (gain == 0f) { return Leaf(classCount(rows)) } val (trueRows, falseRows) = split(rows, question!!) val trueBranch = trainTree(trueRows) val falseBranch = trainTree(falseRows) return Branch(question, trueBranch, falseBranch) } /** * Classify provided data row * @return predictions */ fun classify(row: Array<Value>, node: GraphNode): MutableMap<String, Int> { return when (node) { is Leaf -> node.predictions is Branch -> { return if (node.question.match(row)) { classify(row, node.trueBranch) } else { classify(row, node.falseBranch) } } } } /** * Prints trained tree * * It will crash if there is no trained tree in instance * @see train * @see printTree * @throws NullPointerException */ fun printTrainedTree(spacing: String = "") { printTree(trainedTree!!, spacing) } /** * Prints provided tree * @see printTrainedTree */ fun printTree(node: GraphNode, spacing: String = "") { if (node is Leaf) { println(spacing + "Predict " + node.predictions) return } node as Branch println(spacing + node.question) println(spacing + "-->True:") printTree(node.trueBranch, spacing + " ") println(spacing + "-->False:") printTree(node.falseBranch, spacing + " ") } /** * Prints provided leaf data */ fun printLeaf(frequencyOfOccurence: Map<String, Int>): Map<String, String> { val total = frequencyOfOccurence.size.toFloat() val probabilities: MutableMap<String, String> = mutableMapOf() for ((key, value) in frequencyOfOccurence) { probabilities[key] = (value.toFloat() / total * 100f).toInt().toString() + "%" } return probabilities } /** * Prints predictions for provided data with trained tree model */ fun printPredictions(rows: Array<Array<Value>>) { for (row in rows) { println(printLeaf(classify(row, trainedTree!!))) } } /** * Trains internal tree model with provided data */ fun train(trainingRows: Array<Array<Value>>) { trainedTree = trainTree(trainingRows) } } fun main(vararg args: String) { run { val headers = arrayOf("color", "diameter", "label") val trainData = arrayOf( arrayOf(Text("Green"), Numeric(3f), Text("Apple")), arrayOf(Text("Yellow"), Numeric(3f), Text("Apple")), arrayOf(Text("Red"), Numeric(1f), Text("Grape")), arrayOf(Text("Yellow"), Numeric(3f), Text("Lemon")) ) val decisionTree = DecisionTree(headers) decisionTree.train(trainData) decisionTree.printTrainedTree() println("----") decisionTree.printPredictions(trainData) } run { // todo: other test data } }
0
Kotlin
0
0
8578d44459e4f28285df8dc1c087995b20593bff
6,657
KotlinDecisionTree
MIT License
src/Day10.kt
freszu
573,122,040
false
{"Kotlin": 32507}
fun main() { fun xOverCycles(lines: List<String>) = lines.map { val split = it.split(" ") split.first() to split.getOrNull(1)?.toInt() } .fold(listOf(1)) { acc, (op, arg) -> when (op) { "noop" -> acc + (acc.last()) "addx" -> acc + acc.last() + (acc.last() + requireNotNull(arg)) else -> error("Unknown op $op") } } fun part1(xInCycles: List<Int>) = xInCycles.foldIndexed(0) { index, acc, v -> val cycle = index + 1 if (cycle in (20..220 step 40)) acc + v * cycle else acc } fun part2(xInCycles: List<Int>): List<String> { // 40x6 CRT val crt = Array(6) { crtRow -> CharArray(40) { crtColumn -> val spriteAt = xInCycles[crtRow * 40 + crtColumn] - 1 val drawn = if (crtColumn in spriteAt..spriteAt + 2) '#' else '.' drawn } } return crt.map { it.joinToString("") } } val testInput = xOverCycles(readInput("Day10_test")) val input = xOverCycles(readInput("Day10")) check(part1(testInput) == 13140) println(part1(input)) val part2expectedTest = "##..##..##..##..##..##..##..##..##..##..\n" + "###...###...###...###...###...###...###.\n" + "####....####....####....####....####....\n" + "#####.....#####.....#####.....#####.....\n" + "######......######......######......####\n" + "#######.......#######.......#######....." check(part2(testInput).joinToString("\n") == part2expectedTest) println( part2(input).joinToString("\n") .replace("#", "█") .replace(".", " ") ) }
0
Kotlin
0
0
2f50262ce2dc5024c6da5e470c0214c584992ddb
1,747
aoc2022
Apache License 2.0
src/Day11.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
import kotlin.math.floor data class Monkey( val id: Int, val items: ArrayDeque<Long>, val operation: (Long) -> Long, val divideByThree: Boolean, val divisor: Int, val nextIdTrue: Int, val nextIdFalse: Int ) { var inspections = 0L var correctionMod = 0L fun accept(throwItem: ThrowItem) { if (throwItem.id != id) { error("Got wrong throw") } items.addLast(throwItem.worryLevel) } fun inspectItems(): List<ThrowItem> { val result = mutableListOf<ThrowItem>() val iterator = items.iterator() while (iterator.hasNext()) { var worryLevel = iterator.next() inspections++ iterator.remove() worryLevel = operation(worryLevel) if (correctionMod > 0) worryLevel %= correctionMod if (divideByThree) { worryLevel = floor(worryLevel / 3F).toLong() } val test = worryLevel % divisor == 0L if (test) { result.add(ThrowItem(nextIdTrue, worryLevel)) } else { result.add(ThrowItem(nextIdFalse, worryLevel)) } } return result } override fun toString(): String { return "items=$items, inspections=$inspections" } } data class ThrowItem(val id: Int, val worryLevel: Long) fun parseMonkeys(input: List<String>, divideByThree: Boolean): Map<Int, Monkey> { val monkeys = HashMap<Int, Monkey>() val iterator = input.iterator() val monkeyId = """Monkey ([0-9]+):""".toRegex() while (iterator.hasNext()) { val line = iterator.next() val matchResult = monkeyId.find(line) if (matchResult != null) { val id = matchResult.groups[1]!!.value.toInt() val itemList = iterator.next().split(":")[1].split(",") val items = ArrayDeque(itemList.map { it.trim().toLong() }.toList()) val operationText = iterator.next().split("=")[1].trim() val operation = if (operationText.contains("+")) { val arg = operationText.substring(operationText.indexOf("+") + 1).trim().toInt() val func: (Long) -> Long = { arg + it } func } else if (operationText.contains("*")) { val arg = operationText.substring(operationText.indexOf("*") + 1).trim() if (arg == "old") { val func: (Long) -> Long = { it * it } func } else { val func: (Long) -> Long = { arg.toLong() * it } func } } else { error("Cannot parse operation: '$operationText'") } val divisor = iterator.next().split("by")[1].trim().toInt() val trueMonkey = iterator.next().split("monkey")[1].trim().toInt() val falseMonkey = iterator.next().split("monkey")[1].trim().toInt() // println("id=$id, items=$items, operation=$operation, divisor=$divisor, true=$trueMonkey, false=$falseMonkey") monkeys[id] = Monkey(id, items, operation, divideByThree, divisor, trueMonkey, falseMonkey) } } return monkeys } fun playOneRound(ids: List<Int>, game: Map<Int, Monkey>) { for (id in ids) { val monkey = game[id] val items = monkey!!.inspectItems() for (item in items) { game[item.id]!!.accept(item) } } } fun main() { fun part1(input: List<String>): Long { val game = parseMonkeys(input, true) val ids = game.keys.toList().sorted() repeat(20) { playOneRound(ids, game) } // println(game) val sorted = game.values.sortedByDescending { monkey -> monkey.inspections } return sorted[0].inspections * sorted[1].inspections } fun part2(input: List<String>): Long { val game = parseMonkeys(input, false) val mod = game.values.map { monkey -> monkey.divisor }.reduce { acc, i -> acc * i }.toLong() game.values.forEach{ monkey -> monkey.correctionMod = mod } val ids = game.keys.toList().sorted() repeat(10_000) { playOneRound(ids, game) } // println(game) val sorted = game.values.sortedByDescending { monkey -> monkey.inspections } return sorted[0].inspections * sorted[1].inspections } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") check(part1(input) == 118674L) check(part2(input) == 32333418600L) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
4,759
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/sorting/QuickSelectProblem.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.sorting fun main() { println(quickselect(mutableListOf(7, 2, 5, 1, 9, 3), 3)) } fun quickselect(array: MutableList<Int>, k: Int): Int { // solve using quick sort method // do the partition logic until partition/pivot + 1 == k // return partition var pivot = 0 return quickSelectHelper(array, 0, array.size - 1, k, pivot) } fun quickSelectHelper(array: MutableList<Int>, left: Int, right: Int, k: Int, pivot: Int): Int { if (right > left) { val tempPivot = partition(array, left, right) if (tempPivot + 1 == k) return tempPivot else { quickSelectHelper(array, left, pivot - 1, k, tempPivot) quickSelectHelper(array, pivot + 1, right, k, tempPivot) return pivot } } else { return -1 } } fun partition(array: MutableList<Int>, left: Int, right: Int): Int { var low = left var high = right val pivotItem = array[left] while (low < high) { while (array[low] <= pivotItem) { low++ } while (array[high] > pivotItem) { high-- } val temp = array[low] array[low] = array[high] array[high] = temp } array[low] = array[high] array[high] = pivotItem return high }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,320
DS_Algo_Kotlin
MIT License
src/Day05.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
import java.util.* import kotlin.io.path.createTempDirectory fun main() { fun parseCrates(input: List<String>): List<MutableList<Char>> { val crates = input.reversed().drop(1) val cratesStr = input.last() val cratesCount = cratesStr.trim().split(" ").last().toInt() return (1..cratesCount).map { n -> val index = cratesStr.indexOf(n.toString()) crates.mapNotNull { it.getOrNull(index)?.takeIf(Char::isLetter) }.toMutableList() } } fun move(commandStr: String, crates: List<MutableList<Char>>, keepOrder: Boolean = false) { val (count, from, to) = Regex("move (\\d+) from (\\d+) to (\\d+)") .matchEntire(commandStr)?.groupValues?.drop(1)?.map(String::toInt)!! var elementsToMove = buildList { repeat(count) { add(crates[from - 1].removeLast()) } } if (keepOrder) elementsToMove = elementsToMove.reversed() elementsToMove.forEach(crates[to - 1]::add) } fun part1(input: List<String>, keepOrder: Boolean = false): String { val createsInput = input.takeWhile(String::isNotBlank) val crates = parseCrates(createsInput) input.drop(createsInput.size + 1).forEach { move(it, crates, keepOrder) } return crates.fold("") { acc, cur -> acc + cur.last() } } fun part2(input: List<String>) = part1(input, true) val input = readInput("day5") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
1,478
advent-of-code-2022
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[1004]最大连续1的个数 III.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个由若干 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。 // // 返回仅包含 1 的最长(连续)子数组的长度。 // // // // 示例 1: // // 输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 //输出:6 //解释: //[1,1,1,0,0,1,1,1,1,1,1] //粗体数字从 0 翻转到 1,最长的子数组长度为 6。 // // 示例 2: // // 输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 //输出:10 //解释: //[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] //粗体数字从 0 翻转到 1,最长的子数组长度为 10。 // // // // 提示: // // // 1 <= A.length <= 20000 // 0 <= K <= A.length // A[i] 为 0 或 1 // // Related Topics 双指针 Sliding Window // 👍 232 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun longestOnes(A: IntArray, K: Int): Int { //滑动窗口 时间复杂度 O(n) var left = 0 var res = 0 var k = K for (right in 0 until A.size ){ //如果等于 0 已经遇 边界 if (A[right] == 0){ if (k==0){ //已经填充完成 //看当前窗口有多少个1 while (A[left] == 1){ left++ } //执行完成继续 left++ }else{ //继续填充 k-- } } //更新最大值 res = Math.max(res,right-left+1) } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,673
MyLeetCode
Apache License 2.0
src/day05/day05.kt
PS-MS
572,890,533
false
null
package day05 import java.io.File fun main() { fun part1(input: String): String { val (boxes, commandLines) = input.split("\r\n\r\n") val columns = boxes.lines().map { it.chunked(4) }.map { it.map { box -> box.trim() } } val columnLists: MutableList<MutableList<String>> = mutableListOf() columns.last().forEach { _ -> columnLists.add(mutableListOf()) } columns.reversed().forEachIndexed { rowIndex, row -> if(rowIndex != 0) { row.forEachIndexed { index, box -> if (box.isNotBlank()) { columnLists[index].add(box) } } } } commandLines.lines().forEach { val (x, y, z) = it.split(" ").mapNotNull { value -> value.toIntOrNull() } //move x from y to z repeat(x) { val box = columnLists[y - 1].removeLast() columnLists[z - 1].add(box) } } return String(columnLists.map { it.last()[1] }.toCharArray()) } fun part2(input: String): String { val (boxes, commandLines) = input.split("\r\n\r\n") val columns = boxes.lines().map { it.chunked(4) }.map { it.map { box -> box.trim() } } val columnLists: MutableList<MutableList<String>> = mutableListOf() columns.last().forEach { _ -> columnLists.add(mutableListOf()) } columns.reversed().forEachIndexed { rowIndex, row -> if(rowIndex != 0) { row.forEachIndexed { index, box -> if (box.isNotBlank()) { columnLists[index].add(box) } } } } commandLines.lines().forEach { val (x, y, z) = it.split(" ").mapNotNull { value -> value.toIntOrNull() } //move x from y to z val boxes = with(columnLists[y - 1]) { val pickup = takeLast(x) repeat(x) { removeLast() } pickup } columnLists[z - 1].addAll(boxes) } return String(columnLists.map { it.last()[1]}.toCharArray()) } // test if implementation meets criteria from the description, like: val testInput = File("src", "day05/test.txt").readText() val p1Test = part1(testInput) println("p1 test = $p1Test") check(p1Test == "CMZ") val p2Test = part2(testInput) println("p2 test = $p2Test") check(part2(testInput) == "MCD") val input = File("src", "day05/real.txt").readText() val p1Real = part1(input) println("p1 real = $p1Real") val p2Real = part2(input) println("p2 real = $p2Real") }
0
Kotlin
0
0
24f280a1d8ad69e83755391121f6107f12ffebc0
2,751
AOC2022
Apache License 2.0
app/src/main/java/com/droidhats/mapprocessor/PathAlgorithm.kt
RobertBeaudenon
232,313,026
false
null
package com.droidhats.mapprocessor import kotlin.math.pow import kotlin.math.sqrt /** * Function that returns a string of path elements that would display the shortest path between 2 elements * in a graph of path Nodes. * @param start starting element * @param end ending element * @param pathElements graph of connected Nodes * @return SVG path elements as a string */ fun getShortestPath(start: MapElement, end: MapElement, pathElements: MutableList<Node>): String { val startPoint: Node = findNearestPoint(start, pathElements) val endPoint: Node = findNearestPoint(end, pathElements) if (startPoint.circle.equals(endPoint.circle)) { var string: String = endPoint.circle.toString() + Circle(end.getCenter().first, end.getCenter().second, 5.0) string += Path.createPath(endPoint.circle.getCenter(), end.getCenter()) return string } val visited: MutableList<Node> = mutableListOf() startPoint.value = 0.0 visited.add(startPoint) for (point in startPoint.neighbors) { val dist = getDistance(startPoint, point) point.value = dist point.shortestPath = mutableListOf() point.shortestPath.add(startPoint.circle) } for(point in startPoint.neighbors) { dijsktra(point, endPoint, visited) } if(endPoint.shortestPath.size == 0) { var x: Int = 0 while (x < pathElements.size) { if(pathElements[x].circle.equals(startPoint.circle) || pathElements[x].circle.equals(endPoint.circle)) { pathElements.removeAt(x) } x++ } return getShortestPath(start, end, pathElements) } endPoint.shortestPath.add(endPoint.circle) var string = pathToString(endPoint.shortestPath) string += startPoint.circle string += endPoint.circle return string } /** * This recursive function implements the main functionality of the Dijkstra algorithm for finding the * shortest path. If it identifies a shorter path to a node, it will append itself to it, in the hopes * of reaching the end point. As a result, the end point will have the shortest path to it. * @param currentPoint the current node * @param endPoint the end node * @param visited the list of nodes already visited */ fun dijsktra(currentPoint: Node, endPoint: Node, visited: MutableList<Node>) { if (currentPoint.circle.equals(endPoint.circle)) return visited.add(currentPoint) for (point in currentPoint.neighbors) { val dist = getDistance(point, currentPoint) + currentPoint.value if (point.value == -1.0) { point.value = dist point.shortestPath = copyList(currentPoint.shortestPath) point.shortestPath.add(currentPoint.circle) } if (point.value > dist) { point.value = dist point.shortestPath = copyList(currentPoint.shortestPath) point.shortestPath.add(currentPoint.circle) dijsktra(point, endPoint, visited) } point.visitedBy.add(currentPoint) } for (point in currentPoint.neighbors) { if (!isInList(point, visited)){ dijsktra(point, endPoint, visited) } } } /** * Takes a list of circle elements (points) and returns a string of path elements between them * @param nodeList list of circles to connect in a path * @return returns a string of the path elements */ fun pathToString(nodeList: List<Circle>): String { val string: StringBuilder = StringBuilder() var x: Int = 0 while (x < nodeList.size - 1) { val path = Path.createPath(nodeList[x].getCenter(), nodeList[x + 1].getCenter()) string.append(path) x++ } // Get the start and end point of the last drawn path and use them to draw the arrow head paths val lastDrawnPathStartPoint = nodeList[x-1] val lastDrawnPathEndPoint = nodeList[x] val arrowHeadPaths: List<String> = getArrowHeadPaths(lastDrawnPathStartPoint, lastDrawnPathEndPoint) // Append the two arrow heads' paths to the string to be drawn on the map. string.append(arrowHeadPaths[0]) string.append(arrowHeadPaths[1]) return string.toString() } /** * Takes the start and end point of a path and returns a list of strings represnting paths for * two arrow heads originating from the end of the path * @param startPoint The start point of the navigation path * @param endPoint The end point of the navigation path * @return returns a list of two strings of the arrow heads path elements */ fun getArrowHeadPaths(startPoint: Circle, endPoint: Circle) : List<String> { // Get the x and y coordinates of the start and end points of the path val x1: Double = startPoint.getCenter().first val y1: Double = startPoint.getCenter().second val x2: Double = endPoint.getCenter().first val y2: Double = endPoint.getCenter().second // The value of cosine at 45 degrees val cos = 0.707 // The lengths of the path between the start and end points val pathLength: Double = sqrt(((x2-x1).pow(2)+(y2-y1).pow(2))) // The lengths of the path between the end point and the arrow head point val arrowLength = 25.0 // Calculate the x and y coordinates for the two arrow head points. val x3: Double = x2 + (arrowLength/pathLength)*((x1-x2)*cos + (y1-y2)*cos) val y3: Double = y2 + (arrowLength/pathLength)*((y1-y2)*cos - (x1-x2)*cos) val x4: Double = x2 + (arrowLength/pathLength)*((x1-x2)*cos - (y1-y2)*cos) val y4: Double = y2 + (arrowLength/pathLength)*((y1-y2)*cos + (x1-x2)*cos) // Use the x and y coordinates to create arrow head circles. val firstArrowEnd = Circle(x3, y3, 2.0 ) val secondArrowEnd = Circle(x4, y4, 2.0 ) // Draw two paths each connecting the end point of the navigation path to one of the arrow head ends val firstArrowPath = Path.createPath(endPoint.getCenter(), firstArrowEnd.getCenter()) val secondArrowPath = Path.createPath(endPoint.getCenter(), secondArrowEnd.getCenter()) return listOf(firstArrowPath.toString(), secondArrowPath.toString()) } /** * Copies a list of references to Nodes (the Nodes don't get duplicated), so that every node has a unique list * of nodes representing its shortest path * @param list of circles (point) to copy * @return a new list of circles */ fun copyList(list: List<Circle>): MutableList<Circle> { val mutList: MutableList<Circle> = mutableListOf() for (node in list) { mutList.add(node) } return mutList } /** * Checks whether a Node is in a list of Nodes * @param point Node to check whether it is in a list * @param list to check if the point is in it * @return whether the Node is in the list */ fun isInList(point: Node, list: List<Node>): Boolean { for (node in list) { if(point.circle.equals(node.circle)) return true } return false } /** * Find the nearest point in a list of Nodes to a MapElement * @param mapElement map element to find the closest node to * @param pathElements list of path elements to search in * @return Closest Node to mapElement */ fun findNearestPoint(mapElement: MapElement, pathElements: List<Node>): Node { var nearestNode: Node = pathElements[0] var smallestDistance: Double = getDistance(mapElement, nearestNode) for (node in pathElements) { val distanceToNode = getDistance(mapElement, node) if(distanceToNode < smallestDistance) { nearestNode = node smallestDistance = distanceToNode } } return nearestNode } /** * Get distance between map element and a node */ fun getDistance(mapElement: MapElement, nodeB: Node): Double { return getDistance(mapElement.getCenter(), nodeB.circle.getCenter()) } /** * Get distance between 2 nodes */ fun getDistance(nodeA: Node, nodeB: Node): Double { return getDistance(nodeA.circle.getCenter(), nodeB.circle.getCenter()) } /** * The Node class which consists of a vertex (Circle) and its neighbors. It holds a value which is the * shortest distance to it, the shortest path to it from a start node, and a list of nodes that have visited * this node */ class Node(val circle: Circle, var neighbors: MutableList<Node>) { var value: Double = -1.0 var shortestPath: MutableList<Circle> = mutableListOf() var visitedBy: MutableList<Node> = mutableListOf() }
4
Kotlin
4
7
ea136a60a71f5d393f4a5688e86b9c56c6bea7b6
8,394
SOEN390-CampusGuideMap
MIT License
src/main/kotlin/days/aoc2020/Day23.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2020 import days.Day class Day23: Day(2020, 23) { override fun partOne(): Any { val solution = solve(inputString, 100, 9) return solution.joinToString("").toInt() } override fun partTwo(): Any { return solve(inputString, 10000000, 1000000).subList(0,2).let { it[0].toLong() * it[1] } } // 389125467 // [2,5,8,6,4,7,10,9,1,11] // array is a map from any cup label to its clockwise neighbor fun solve(startingString: String, steps: Int, overallSize: Int): List<Int> { val nextCups = Array(overallSize+1) { it + 1 } val starter = startingString.map { Character.digit(it, 10) } starter.forEachIndexed { index, i -> nextCups[i] = starter.getOrElse(index+1) { if (overallSize > 9) 10 else starter[0] } } if (overallSize > 10) { nextCups[overallSize] = starter[0] } var currentCup = starter[0] for (i in 1..steps) { val drawnCups = listOf(nextCups[currentCup], nextCups[nextCups[currentCup]], nextCups[nextCups[nextCups[currentCup]]]) var destination = currentCup - 1 while (drawnCups.contains(destination) || destination < 1) { if (destination > 1) { destination-- } else { destination = overallSize } } nextCups[currentCup] = nextCups[drawnCups[2]] nextCups[drawnCups[2]] = nextCups[destination] nextCups[destination] = drawnCups[0] currentCup = nextCups[currentCup] } currentCup = 1 return (1..8).map { val result = nextCups[currentCup] currentCup = result result } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,793
Advent-Of-Code
Creative Commons Zero v1.0 Universal
2015/Day12/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File fun main() { fun part1(input: List<String>): Int { val jason = input[0] var sum = 0 var index = 0 while (index < jason.length) { val c = jason[index] when (c) { in setOf('-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9') -> { var value = "$c" index++ while (index < jason.length && jason[index] in '0'..'9') { value += jason[index] index++ } sum += value.toInt() } '\"' -> { while (index < jason.length && jason[index] != '\"') { index++ } index++ } else -> index++ } } return sum } fun part2(input: List<String>): Int { var jason = input[0] val openBrackets = mutableListOf<Pair<Int, Int>>() var sum = 0 var index = 0 while (index < jason.length) { val c = jason[index] when (c) { in setOf('-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9') -> { var value = "$c" index++ while (index < jason.length && jason[index] in '0'..'9') { value += jason[index] index++ } sum += value.toInt() } '\"' -> { while (index < jason.length && jason[index] != '\"') { index++ } index++ } '{' -> { openBrackets.add(Pair(index, sum)) sum = 0 index++ } '}' -> { val (startIndex, previousSum) = openBrackets.removeLast() val objStr = jason.substring(startIndex, index + 1) if (objStr.contains(":\"red\"")) { sum = previousSum } else { sum += previousSum } jason = jason.substring(0, startIndex) + jason.substring(index + 1) index = startIndex } else -> index++ } } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 12) check(part2(testInput) == 9) val input = readInput("Day12_data") println("Part 1 answer: ${part1(input)}") println("Part 2 answer: ${part2(input)}") } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
2,965
AdventOfCode
MIT License
src/main/kotlin/Day6.kt
i-redbyte
433,743,675
false
{"Kotlin": 49932}
fun main() { val data = readInputFile("day6") val lines = data.joinToString("") .split(",") fun part1(): Long { val initialData = LongArray(9) { 0 } lines.map { it.toInt() } .forEach { initialData[it]++ } return calculateLanternfish(80, initialData) } fun part2(): Long { val initialData = LongArray(9) { 0 } lines.map { it.toLong() } .forEach { initialData[it.toInt()] += 1L } return calculateLanternfish(256, initialData) } println("Result part1: ${part1()}") println("Result part2: ${part2()}") } fun calculateLanternfish(n: Int, d: LongArray): Long { var data = d var next = LongArray(9) { 0 } var tmp: LongArray for (i in 1..n) { next[8] = data[0] next[7] = data[8] next[6] = data[0] + data[7] next[5] = data[6] next[4] = data[5] next[3] = data[4] next[2] = data[3] next[1] = data[2] next[0] = data[1] tmp = next next = data data = tmp } return data.sum() }
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
1,099
AOC2021
Apache License 2.0
src/main/kotlin/aoc2023/Day18.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import PointL import areaWithin import readInput @OptIn(ExperimentalStdlibApi::class) object Day18 { /** * @param input the puzzle input * @param getDelta a function to transform a given input line into a [PointL]-Delta (to get to the next point) */ private fun solve(input: List<String>, getDelta: (String) -> PointL): Long { var current = PointL(0L, 0L) val edges = buildList { add(current) addAll(input.map { line -> current += getDelta(line); current }) } val border = edges.windowed(2, 1).sumOf { it.first().distanceTo(it.last()) } // Pick's theorem is actually A = inner + border/2 - 1 // -> adding 2 (+1 instead of -1) seems to get the correct answers, probably due to the corners somehow return edges.areaWithin() + border / 2 + 1 } fun part1(input: List<String>) = solve(input) { line -> val split = line.split(" ") val direction = split[0] val length = split[1].toLong() when (direction) { "U" -> PointL(0, -length) "D" -> PointL(0, length) "L" -> PointL(-length, 0) "R" -> PointL(length, 0) else -> throw IllegalArgumentException("Unknown direction: $direction") } }.toInt() fun part2(input: List<String>) = solve(input) { line -> // drop '(#' and ')' val color = line.substring(line.lastIndexOf('(')).drop(2).take(6) val direction = color.last() val length = color.take(5).hexToLong() // 0 means R, 1 means D, 2 means L, and 3 means U. when (direction) { '3' -> PointL(0, -length) '1' -> PointL(0, length) '2' -> PointL(-length, 0) '0' -> PointL(length, 0) else -> throw IllegalArgumentException("Unknown direction: $direction") } } } fun main() { val testInput = readInput("Day18_test", 2023) check(Day18.part1(testInput) == 62) check(Day18.part2(testInput) == 952408144115L) val input = readInput("Day18", 2023) println(Day18.part1(input)) println(Day18.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
2,172
adventOfCode
Apache License 2.0
src/day25/Day25.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day25 import readInput class Day25 { fun part1(): String { val readInput = readInput("day25/input") return part1(readInput) } fun part2(): String { val readInput = readInput("day25/input") return part2(readInput) } fun part1(input: List<String>): String { val sum = input.map { it.toCharArray().reversed() }.map { toIntArray(it) } .map { toDecimal(it) }.sum() return toSnuf(sum) } private fun toSnuf(value: Long): String { val result = mutableListOf<Char>() var rest = value while (rest > 0) { val mod = myMod(rest) rest = myRest(rest, mod) result.add(0, toChar(mod)) } return result.joinToString("", "", "") } private fun myMod(v: Long): Long { val result = v % 5 return (if (result > 2) (result - 5) else result) } private fun myRest(v: Long, m: Long): Long { return (v / 5L) + fix(m) } private fun fix(v: Long): Long = (if (v < 0) 1 else 0) private fun toDecimal(it: LongArray): Long = it.mapIndexed { index, i -> Math.pow(5.0, index.toDouble()).toLong() * i }.sum() private fun toIntArray(c: List<Char>): LongArray = c.map { toInt(it) }.toLongArray() private fun toInt(c: Char): Long = when (c) { '1' -> 1L '2' -> 2L '0' -> 0L '-' -> -1L '=' -> -2L else -> throw IllegalArgumentException("Unknown value $c") } private fun toChar(l: Long): Char = when (l) { 1L -> '1' 2L -> '2' 0L -> '0' -1L -> '-' -2L -> '=' else -> throw IllegalArgumentException("Unknown value $l") } fun part2(input: List<String>): String = "" }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
1,787
adventofcode-2022
Apache License 2.0
src/algorithms/sorting/merge_sort/MergeSort.kt
abdurakhmonoff
353,686,707
false
null
package algorithms.sorting.merge_sort /** * Implementation of the merge sort algorithm for sorting a list of integers in ascending order. */ class MergeSort { /** * Recursively sorts the given list by dividing it into halves and merging them. * * @param array the list to sort * @return the sorted list */ fun mergeSort(array: List<Int>): List<Int> { // Base case: if array has only one number, it is already sorted if (array.size == 1) { return array } // Divide the array into two halves and recursively sort each half val left = array.subList(0, array.size / 2) val right = array.subList(array.size / 2, array.size) return merge(mergeSort(left), mergeSort(right)) } /** * Merges two sorted lists into a single sorted list. * * @param left the first sorted list * @param right the second sorted list * @return the merged sorted list */ private fun merge(left: List<Int>, right: List<Int>): List<Int> { val result = ArrayList<Int>() var leftIndex = 0 var rightIndex = 0 // Iterate through both lists, comparing the numbers and adding the smaller one to the result list while (leftIndex < left.size && rightIndex < right.size) { if (left[leftIndex] < right[rightIndex]) { result.add(left[leftIndex]) leftIndex++ } else { result.add(right[rightIndex]) rightIndex++ } } // Add any remaining numbers from the left and right lists val leftRemaining = left.subList(leftIndex, left.size) val rightRemaining = right.subList(rightIndex, right.size) result.addAll(leftRemaining) result.addAll(rightRemaining) return result } } fun main() { val mergeSort = MergeSort() val numbers = ArrayList(listOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0)) println(mergeSort.mergeSort(numbers)) }
0
Kotlin
40
107
cd9746d02b34b54dd0cf8c8dacc2fb91d2a3cc07
2,031
data-structures-and-algorithms-kotlin
MIT License
src/Day10.kt
juliantoledo
570,579,626
false
{"Kotlin": 34375}
fun main() { fun solve(input: List<String>): Int { var cycle = 0 var register = 1 var strengthSum = 0 var matrix = MutableList<String>(240) { "." } fun addCycle() { if (cycle <=240) { if (cycle % 40 in (register - 1..register + 1)) { matrix[cycle] = "#" } } cycle++ if (cycle in listOf<Int>(20, 60, 100, 140, 180, 220)) { strengthSum += cycle * register } } input.forEach { line -> val command = line.split(" ") when (command[0]) { "noop" -> { addCycle() } "addx" -> { repeat(2) { addCycle() } register += command[1].toInt() } } } matrix.chunked(40).forEach{ item -> println(item.joinToString(separator = "")) } return strengthSum } println("Test:") val test = solve(readInput("Day10_test")) check(test == 13140) println("Part1: $test") println("") println("Part1: " + solve(readInput("Day10_input"))) }
0
Kotlin
0
0
0b9af1c79b4ef14c64e9a949508af53358335f43
1,274
advent-of-code-kotlin-2022
Apache License 2.0
src/main/java/challenges/coderbyte/FindIntersection.kt
ShabanKamell
342,007,920
false
null
package challenges.coderbyte /* Have the function FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted). Your goal is to return a comma-separated string containing the numbers that occur in elements of strArr in sorted order. If there is no intersection, return the string false. For example: if strArr contains ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] the output should return "1,4,13" because those numbers appear in both strings. The array given will not be empty, and each string inside the array will be of numbers sorted in ascending order and may contain negative numbers. */ object FindIntersection { private fun solve(strArr: Array<String>): String { val a = strArr[0].split(", ").map { it.toInt() } val b = strArr[1].split(", ").map { it.toInt() } val result = intersection(a, b) return if (result.isEmpty()) false.toString() else result.joinToString(",") } private fun intersection(a: List<Int>, b: List<Int>): List<Int> { val result = mutableListOf<Int>() var i = 0 var j = 0 val aSize = a.size val bSize = b.size while (i < aSize && j < bSize) { when { a[i] == b[j] -> { result.add(a[i]) i++ j++ } a[i] < b[j] -> { i++ } a[i] > b[j] -> { j++ } } } return result } // "1, 3, 4, 7, 13" // "1, 2, 4, 13, 15" @JvmStatic fun main(args: Array<String>) { println(solve(arrayOf("1, 3, 4, 7, 13", "1, 2, 4, 13, 15"))) // 1,4,13 println(solve(arrayOf("1, 3, 9, 10, 17, 18", "1, 4, 9, 10"))) // 1,9,10 println(solve(arrayOf("1, 2, 3", "4, 5, 6"))) // false } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,071
CodingChallenges
Apache License 2.0
src/main/java/com/luckystar/advent2020/Advent7.kt
alexeymatveevp
48,393,486
false
{"Java": 199293, "Kotlin": 8971}
package com.luckystar.advent2020 fun main() { val file = object {}.javaClass.getResource("/2020/input_7.txt").readText() var rules = file.split("\r\n") rules = rules.filter { rule -> !rule.contains("no other bags") } val regex = """^(\w+ \w+) bags contain (.*)\.$""".toRegex() val rightRegex = """^(\d) (\w+ \w+) bags?$""".toRegex() val flatRules = rules.map { rule -> val (left, right) = regex.find(rule)!!.destructured right.split(", ").map { g -> val (num, bag) = rightRegex.find(g)!!.destructured Triple(left, num.toInt(), bag) } }.flatten() // part 1 val mapRight = flatRules.groupBy { r -> r.third } var deps = mapRight.getValue("shiny gold"); val uniqueBags = mutableSetOf<String>() while (deps.isNotEmpty()) { val lefts = deps.map { d -> d.first } uniqueBags.addAll(lefts) deps = lefts.map { l -> mapRight.get(l) }.filterNotNull().flatten() } println(uniqueBags.size) // part 2 val mapLeft = flatRules.groupBy { r -> r.first } var deps2 = mapLeft.getValue("shiny gold").map { t -> Triple(t.first, t.second, t.third) }; var numberOfBags = 0 while (deps2.isNotEmpty()) { numberOfBags += deps2 .map { q -> val first = mapLeft.get(q.third) Pair(first, q.second) } .filter { p -> p.first == null } .map { p -> p.second } .sum() deps2 = deps2 .map { q -> Pair(mapLeft.get(q.third), q.second) } .filter { p -> p.first != null } .flatMap { p -> numberOfBags += p.second p.first!!.map { t -> Triple(t.first, t.second * p.second, t.third) } } } println(numberOfBags) } data class Quadruple<T1, T2, T3, T4>(val first: T1, val second: T2, val third: T3, val fourth: T4)
0
Java
0
1
d140ee8328003e79fbd2e0997cc7a8adf0e59ab2
1,953
adventofcode
Apache License 2.0
src/main/kotlin/com/staricka/adventofcode2023/days/Day14.kt
mathstar
719,656,133
false
{"Kotlin": 107115}
package com.staricka.adventofcode2023.days import com.staricka.adventofcode2023.framework.Day import com.staricka.adventofcode2023.util.Grid import com.staricka.adventofcode2023.util.GridCell import com.staricka.adventofcode2023.util.StandardGrid enum class Rock(override val symbol: Char): GridCell { ROUND('O'), SQUARE('#'), BLANK('.'); companion object { fun fromChar(c: Char): Rock { return when(c) { 'O' -> ROUND '#' -> SQUARE '.' -> BLANK else -> throw Exception() } } } } fun Grid<Rock>.rollNorth() { for (x in minX..maxX) { for (y in minY..maxY) { if (this[x,y] == Rock.ROUND) { var dest = x while (dest > 0 && this[dest-1,y] == Rock.BLANK) dest-- this[x,y] = Rock.BLANK this[dest,y] = Rock.ROUND } } } } fun Grid<Rock>.rollEast() { for (y in (minY..maxY).reversed()) { for (x in minX..maxX) { if (this[x,y] == Rock.ROUND) { var dest = y while (dest < maxY && this[x,dest+1] == Rock.BLANK) dest++ this[x,y] = Rock.BLANK this[x,dest] = Rock.ROUND } } } } fun Grid<Rock>.rollSouth() { for (x in (minX..maxX).reversed()) { for (y in minY..maxY) { if (this[x,y] == Rock.ROUND) { var dest = x while (dest < maxX && this[dest+1,y] == Rock.BLANK) dest++ this[x,y] = Rock.BLANK this[dest,y] = Rock.ROUND } } } } fun Grid<Rock>.rollWest() { for (y in minY..maxY) { for (x in minX..maxX) { if (this[x,y] == Rock.ROUND) { var dest = y while (dest > 0 && this[x,dest-1] == Rock.BLANK) dest-- this[x,y] = Rock.BLANK this[x,dest] = Rock.ROUND } } } } enum class RollDirection { NORTH, WEST, SOUTH, EAST; fun next(): RollDirection { return entries[(ordinal + 1) % entries.size] } fun rollGrid(grid: Grid<Rock>) { when(this) { NORTH -> grid.rollNorth() WEST -> grid.rollWest() SOUTH -> grid.rollSouth() EAST -> grid.rollEast() } } } fun Grid<Rock>.load(): Int { return cells().filter { (_,_,v) -> v == Rock.ROUND }.sumOf { (x,_,_) -> maxX - x + 1 } } class Day14: Day { override fun part1(input: String): Int { val grid = StandardGrid.build(input, Rock::fromChar) grid.rollNorth() return grid.load() } override fun part2(input: String): Int { val grid = StandardGrid.build(input, Rock::fromChar) val history = LinkedHashMap<Pair<Grid<Rock>, RollDirection>, Long>() val totalRotations = 1000000000L * 4 - 1 var loopStart = -1L var direction = RollDirection.entries.last() for (rollCount in 0..totalRotations) { direction = direction.next() direction.rollGrid(grid) val historyKey = Pair(grid.clone(), direction) if (history.containsKey(historyKey)) { loopStart = history[historyKey]!! break } history[historyKey] = rollCount } val loopLength = history.size - loopStart val index = ((totalRotations - loopStart) % loopLength + loopStart).toInt() val finalGrid = history.keys.toList()[index].first return finalGrid.load() } }
0
Kotlin
0
0
8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa
3,624
adventOfCode2023
MIT License
demo-plural-sight-gradle/src/main/kotlin/demo/objects/teste2.kt
antoniolazaro
257,624,848
false
null
package demo.objects import java.io.File import java.util.Scanner import kotlin.math.pow import java.util.* import kotlin.math.sqrt fun main(args: Array<String>) { createAEuphoniousWord() } fun sum(a: Int, b: Int): Int = a + b val mul2 = { a: Int, b: Int -> a * b } private fun lambdasDemo() { println(sum(1, 2)) println(mul2(2, 3)) } fun compose(g: (Int) -> Int, h: (Int) -> Int): (Int) -> Int { return {i-> h(i)} } /* Groundhogs like to throw fun parties, and at their parties, they like to eat Reeses peanut butter cups. But not too many Reeses or they will feel sick! A successful groundhog party should have between 10 and 20 Reeses peanut butter cups, inclusive unless it is the weekend. In this case they need 15 to 25 Reeses peanut butter cups, inclusive. Write a Kotlin program that reads two values: the first is the number of Reeses peanut butter cups; the second is a boolean representing whether it is the weekend. The program must print the boolean value that tells us whether the party is successful. */ fun groundHogsAtTheParty(){ val scanner = Scanner(System.`in`) val input = scanner.nextLine().split(" ") val quant = input[0].toInt() val isWeekend = input[1].toBoolean() if(isWeekend){ print(quant in 15..25) }else{ print(quant in 10..20) } } /* All the letters of the English alphabet are divided into vowels and consonants. The vowels are: a, e, i, o, u, y. The remaining letters are consonants. A word is considered euphonious if it has not three or more vowels or consonants in a row. Otherwise, it is considered discordant. Your task is to create euphonious words from discordant. You can insert any letters inside word. You should output the minimum number of characters needed to create a euphonious word from a given word. For example, word "schedule" is considered discordant because it has three consonants in a row - "sch". To create a euphonious word you need to add any vowel between 's' and 'c' or between 'c' and 'h'. Exemplo: wwwwwwwwwwwwwwwwwwwwwwwwwwwww */ fun createAEuphoniousWord(){ val word = readLine()!!.toLowerCase() val lastIndex = word.toCharArray().lastIndex var total = 0 var index = 0 while(index < lastIndex){ var ok = false while ((index + 2 <= lastIndex && testIsVowels(word[index]) && testIsVowels(word[index + 1]) && testIsVowels(word[index + 2])) || (index + 2 <= lastIndex && (!testIsVowels(word[index]) && !testIsVowels(word[index + 1]) && !testIsVowels(word[index + 2])))) { index+=2 total++ ok = true continue } if(!ok){ index++ } } println(total) } fun testIsVowels(c: Char): Boolean{ return when(c){ 'a','e','i','o','u','y' -> true else -> false } } /* Write a program that reads four numbers (height, twice length, width) and uses all of them as fields of a data class which is Box. Use copy() function in order to create a second box with a different length value (from input). As a result, there must be two boxes. Print them both. */ data class Box(val height: Int, val length: Int, val width: Int) fun copyUsage(){ val scanner = Scanner(System.`in`) val numbers = scanner.nextLine().split(" ").map(String::toInt) val box1 = Box(numbers[0],numbers[1],numbers[3]) val box2 = box1.copy(length = numbers[2]) println(box1) println(box2) } fun Int.lastDigit() : Int = this.toString().last().toString().toInt() /* Write a program that reads the distance between the two cities in miles and the travel time by bus in hours, and outputs the average speed of the bus. */ fun speedAverage(){ val scanner = Scanner(System.`in`) val distance = scanner.nextDouble() val time = scanner.nextDouble() print(distance/time) } /* Write a program that reads a character and checks if it is a capital letter or a digit from 1 to 9. The program must print either true or false. */ fun capitalLetterOrDigit(){ val scanner = Scanner(System.`in`) val letter = scanner.nextLine().first().toChar() print(letter.isUpperCase() || (letter.toInt() in 49..57) ) } /* Write a program that reads three characters and checks if they are ordered according to the Unicode table, and if each next character immediately follows the previous one (i.e. 'a', 'b', 'c' or 'x', 'y', 'z') according to the alphabet. The program must print either true or false. */ fun testCharsOrder(){ val scanner = Scanner(System.`in`) val letters = scanner.nextLine().split(" ") print(letters[1].first().toChar() == letters[0].first().toChar() + 1 && letters[2].first().toChar() == letters[1].first().toChar() + 1) } /* Write a program that reads two Latin letters as characters and compares them ignoring cases. If these characters represent the same letter printtrue , otherwise false. */ fun testChars(){ val scanner = Scanner(System.`in`) val letters = scanner.nextLine().split(" ") print(letters[0].toLowerCase() == letters[1].toLowerCase()) } /* Write a program that reads three numbers and checks if they all are different (i.e. no number equals to any other). The program is to output true or false. */ fun areTheNumbersDifferent(){ val scanner = Scanner(System.`in`) val numbers = scanner.nextLine().split(" ").map(String::toInt) print(numbers[0] != numbers[1] && numbers[0] != numbers[2] && numbers[1] != numbers[2]) } /* Write a program that reads numbers a, b, c and checks if any pair of parameters (ab, ac, or bc) sums to 20. */ fun checkTheSum(){ val scanner = Scanner(System.`in`) val numbers = scanner.nextLine().split(" ").map(String::toInt) print((numbers[0]+numbers[1] == 20) || (numbers[0]+numbers[2] == 20) || (numbers[1]+numbers[2] == 20)) } /* There is a non-negative integer N (0 ≤ N ≤ 1000000). Find the number of tens in it (i.e. next to last digit of the number). If there is no next to last digit, you can consider that the number of tens equals to zero. */ fun numberOfTens(){ val scanner = Scanner(System.`in`) val input = scanner.nextInt() if(input.toString().length > 1){ println(input.toString()[input.toString().lastIndex-1]) }else{ println(0) } } /* Write a program that finds the frequency of occurrences of substring in given string. Input data format The first input line contains a string, the second one contains a substring. */ fun numberOfOccurrences(){ var text = readLine()!! val subText = readLine()!! var count = 0 while(text.contains(subText) && text.length >= subText.length){ count++ text = text.substringAfter(subText) } print(count) } /* GC-content is an important feature of the genome sequences and is defined as the percentage ratio of the sum of all guanines and cytosines to the overall number of nucleic bases in the genome sequence. Write a program, which calculates the percentage of G characters (guanine) and C characters (cytosine) in the entered string. Your program should be case independent. For example, in the string "acggtgttat" the percentage of characters G and C equals to 410⋅100=40.0 \dfrac4{10} \cdot 100 = 40.0 104​⋅100=40.0, where 4 is the number of symbols G and C, and 10 is the length of the string. */ fun thePercentageOfGAndCCharacters(){ val input = readLine()!! println(((input.toLowerCase().filter { c-> c == 'c' || c == 'g' }.length.toDouble()/input.length.toDouble()) * 100).toDouble()) } /* Write a program that reads two lines and then two numbers and outputs them in the same order, each in a new line. */ fun convertText(){ val word1 = readLine()!! val word2 = readLine()!! val numbers = readLine()!!.split(" ").map(String::toInt) print("$word1\n$word2\n${numbers[0]}\n${numbers[1]}") } /* Write a program that reads five words from the standard input and outputs each word in a new line. First, you need to print all the words from the first line, then from the second (from left to right). The words can be placed in the input stream in any way. To solve the problem, use Scanner . */ fun printEachWordInANewLine(){ val scanner = Scanner(System.`in`) var words:List<String> = mutableListOf() while(words.size < 5) { val input = scanner.nextLine() words = words + input.split(" ") } if(words.size > 5) { words = words.subList(0,5) } words.forEach { i -> println(i) } } /* Write a program that reads four integer numbers from one line and prints them each in a new line. In the input, numbers are separated by one or more spaces. */ fun input(){ Scanner(System.`in`).nextLine().replace(" "," ").split(" ").filter { s-> s.trim().isNotBlank() }.map(String::toInt).forEach{i->println(i)} } /* There is a string and a number N. Print the N-th symbol of the string. The example shows how the result should look like. hello world 1 Symbol # 1 of the string "hello world" is 'h' */ fun stringTemplate(){ val scanner = Scanner(System.`in`) val input = scanner.nextLine() val index = scanner.nextInt() val letter = input[index] print("Symbol # $index of the string \"$input\" os '$letter'") } /* You need to write a program that prints date and time in a special format. Hours, minutes and seconds are split by a colon, and day, month and year are split by a slash. Take a look at the examples below. */ fun dateAndTimeFormatting(){ val scanner = Scanner(System.`in`) val h = scanner.nextInt() val m = scanner.nextInt() val s = scanner.nextInt() val d = scanner.nextInt() val mo = scanner.nextInt() val y = scanner.nextInt() print("$h:$m:$s $d/$m$y") } /* Let's try to build a small version of the Battleship game. There is a field with 5 rows (X) and 5 columns (Y), 25 cells in total. Write a program that reads coordinates (X, Y) of three one-cell-sized ships and prints all the available rows (X) and columns (Y) for new ships. It means that new ships can be placed only in rows and columns which are vacant. All the input coordinates are separated with space. Separate the output in the same way. Print rows (X) and columns (Y) in two different rows. */ fun battleshipGame(){ val scanner = Scanner(System.`in`) val numbers = scanner.nextLine().split(" ").map(String::toInt) var matrix = Array(5,{IntArray(5)}) for (i in 0..4) { for (j in 0..4) { matrix[i][j] = 0 } } matrix[numbers[0]-1][numbers[1]-1] = 1 matrix[numbers[2]-1][numbers[3]-1] = 2 matrix[numbers[4]-1][numbers[5]-1] = 3 var matrixX = mutableListOf<Int>() var matrixY = mutableListOf<Int>() loop@ for (i in 0..4) { for (j in 0..4) { if(matrix[i][j] != 0){ continue@loop; } } matrixX.add(i + 1) } println() loop@ for (i in 0..4) { for (j in 0..4) { if(matrix[j][i] != 0){ continue@loop; } } matrixY.add(i + 1) } printMatrix(matrixX) println() printMatrix(matrixY) } fun printMatrix(m: MutableList<Int>){ for(i in 0..m.lastIndex){ if(i != m.lastIndex){ print("${m[i]} ") }else{ print("${m[i]}") } } } /* Write a program that reads a word and prints the number of characters that appear only once. */ fun uniqueCharacters(){ val input = Scanner(System.`in`) val letter = input.next().toLowerCase() var total = 0 primeiro@ for(indice in letter.toCharArray().indices){ val currentChar = letter[indice] var quantidade = 0 for(char in letter.toCharArray()){ if(char == currentChar){ quantidade++ if(quantidade > 1){ continue@primeiro } } } total++ } println(total) } /* Getting letters from the Alphabet */ fun gettingLettersFromTheAlphabet(){ val input = Scanner(System.`in`) val letter = input.next().toLowerCase() val char = letter.single() for(l in 'a'..char-1){ print(l) } } /* Imagine you implement a web service to pay for video games. There is a text field where a user inputs their card number. A card number is a string like "AAAA AAAA AAAA AAAA", where A is any digit. Please note that a correct card number contains three spaces as in the template. Create a function that returns the card number as a Long or produces any exception when the card number is incorrect. */ fun parseCardNumber(cardNumber: String): Long { if(cardNumber.length != 15){ throw Exception("Erro no formato do card number") } return cardNumber.replace(" ","").toLong() } fun squaresOfNnaturalNumbers(){ val scanner = Scanner(System.`in`) val number = scanner.nextInt() var value = 1 var square = value*value do{ println(square) value++ square = value*value }while(square < number) } fun whileCollatzConjecture(){ val scanner = Scanner(System.`in`) var number = scanner.nextInt() print(" $number") while(number != 1){ if(number % 2 == 0){ number = (number / 2).toInt() }else{ number = number * 3 + 1 } print(" $number") } } /* As the input, the program gets a sequence of non-negative integers; each integer is written in a separate line. The sequence contains an integer 0. After reading 0 the program is to end its work and output the length of the sequence (do not count the final 0). */ fun lenghtOfSequence(){ val scanner = Scanner(System.`in`) var count = 0 do{ var number = scanner.nextInt() count++ }while(number != 0) println(count-1) } /* Write a program that reads an array of integers and two numbers n and m. The program is to check that n and m never occur next to each other (in any order) in the array. */ fun checkTheNumbers(){ val scanner = Scanner(System.`in`) val size = scanner.nextLine().toInt() val numbers = scanner.nextLine().split(" ").map(String::toInt) val twoValues = scanner.nextLine().split(" ").map(String::toInt) val n = twoValues[0] val m = twoValues[1] var msg = "YES" for(indice in 0..numbers.lastIndex){ if(indice+1 < numbers.size) { if ((numbers[indice] == n && numbers[indice + 1] == m) || (numbers[indice] == m && numbers[indice + 1] == n)) { msg = "NO" break } } } println(msg) } fun countTriple(){ val scanner = Scanner(System.`in`) val size = scanner.nextLine().toInt() val numbers = scanner.nextLine().split(" ").map(String::toInt) var totalTriples = 0 for(indice in 0..numbers.size){ if(indice+2 < numbers.size) { if (numbers[indice + 1] == numbers[indice] + 1 && numbers[indice + 2] == numbers[indice] + 2) { totalTriples++ } else if (numbers[indice + 1] == numbers[indice] - 1 && numbers[indice + 2] == numbers[indice] - 2) { totalTriples++ } } } println(totalTriples) } fun readFile2(){ print(File("/media/popete/dados/workspace-kotlin/kotlin-lab.git/demo-plural-sight-gradle/src/main/resources/teste2.txt").readLines().get(0).split(" ").size) } fun readFile(){ var maxWord = 0 var maxWordTxt = "" for(line in File("/media/popete/dados/workspace-kotlin/kotlin-lab.git/demo-plural-sight-gradle/src/main/resources/teste.txt").readLines()){ if(line.length > maxWord){ maxWordTxt = line maxWord = line.length } } print(maxWordTxt.length) } fun forTest2(){ val scanner = Scanner(System.`in`) val size = scanner.nextLine().toInt() val numbers = scanner.nextLine().split(" ").map(String::toInt) var maxSequence = 0 var last:Int = -1 var maxValue = -1 for(value in numbers){ if(value >= last){ maxSequence++ if(maxSequence > maxValue){ maxValue = maxSequence } }else{ maxSequence = 1 } last = value } println(maxValue) } fun math(){ val scanner = Scanner(System.`in`) val a = scanner.nextInt() val b = scanner.nextInt() val c = scanner.nextInt() val d = scanner.nextInt() for(x in 0..1000){ val root = a * x.toDouble().pow(3) + b * x.toDouble().pow(2) + c * x + d println(if(root.toDouble() == 0.0) x else "") } } fun forTest(){ for (i in 1..3) { for (j in 1..i) { print(j) } } } fun repeatTest2(){ val scanner = Scanner(System.`in`) val repeatTimes = scanner.nextInt() var maxNumber = -1 repeat(repeatTimes) { val value = scanner.nextInt() if (value % 4 == 0 && value > maxNumber) { maxNumber = value } } print(maxNumber) } fun repeatTest(){ val scanner = Scanner(System.`in`) val repeatTimes = scanner.nextInt() val arrayA = mutableListOf<Int>() val arrayB = mutableListOf<Int>() val arrayC = mutableListOf<Int>() val arrayD = mutableListOf<Int>() repeat(repeatTimes){ val input = scanner.nextInt() when(input){ 2 -> arrayD.add(input) 3 -> arrayC.add(input) 4 -> arrayB.add(input) 5 -> arrayA.add(input) } } print("${arrayD.size} ${arrayC.size} ${arrayB.size} ${arrayA.size}") } fun boxes() { val scanner = Scanner(System.`in`) val x1 = scanner.nextInt() val x2 = scanner.nextInt() val x3 = scanner.nextInt() val y1 = scanner.nextInt() val y2 = scanner.nextInt() val y3 = scanner.nextInt() val sumX = sqrt(x1.toDouble().pow(2) + x2.toDouble().pow(2) + x3.toDouble().pow(2)) val sumY = sqrt(y1.toDouble().pow(2) + y2.toDouble().pow(2) + y3.toDouble().pow(2)) if (sumX > sumY) { println("Box 1 > Box 2") } else if (sumX < sumY) { println("Box 1 < Box 2") } else if (sumX == sumY) { println("Box 1 = Box 2") } else { println("Incomparable") } val a = scanner.nextInt() val b = scanner.nextInt() val c = scanner.nextInt() val d = scanner.nextInt() for(x in 0..1000){ val root = a * x.toDouble().pow(3) + b * x.toDouble().pow(2) + c * x + d println(if(root.toInt() == 0) println(x) else println("")) } } private fun letters() { val letters = mutableMapOf<String, Int>() val scan = Scanner(System.`in`) var major = "stop" var valorMaior = -1 var word = scan.nextLine() while (!word.equals("stop", ignoreCase = true)) { var valorAtual = 1 if (letters[word] != null) { valorAtual = letters[word]!! + 1 } letters[word] = valorAtual if (valorAtual > valorMaior) { major = word valorMaior = valorAtual } word = scan.nextLine() } if (letters.isEmpty()) { print(null) } else { print(major) } println(greetNeo()) } private fun teste() { val scanner = Scanner(System.`in`) val parameterName = scanner.nextLine() val parameterValue = scanner.nextInt() when (parameterName) { "startingAmount" -> println(finalAmount(startingAmount = parameterValue)) "yearPercent" -> println(finalAmount(yearPercent = parameterValue)) "years" -> println(finalAmount(years = parameterValue)) } val valor = scanner.nextInt() println(if (valor in -15..12 || valor in 14..17 || valor > 19) "True" else "False") } fun checkEqual(s1: String, s2: String, ignoreCase: Boolean = false): Boolean{ return true} fun numbers(a: Int = 0, b: Int, c: Int) = a+b+c fun numbers1(a: Int = 0, b: Int = 0, c: Int) = a+b+c fun numbers2(a: Int = 0, b: Int, c: Int = 0) = a+b+c fun numbers3(a: Int, b: Int = 0, c: Int) = a+b+c fun numbers4(a: Int, b: Int, c: Int = 0) = a+b+c fun numbers5(a: Int, b: Int = 0, c: Int = 0) = a+b+c fun greetNeo() = greetUser(name = "Anderson", honorific = "Mr", greet = "Hello") fun greetUser( name: String, admin: Boolean = false, smith: Boolean = false, honorific: String = "", greet: String = "Greetings" ): String { return if (!admin && !smith) { "$greet, $honorific $name" } else { "Matrix Error" } } fun finalAmount(startingAmount: Int = 1000, yearPercent: Int = 5, years: Int = 10): Int = (startingAmount * (1 + (yearPercent.toDouble() / 100)).toDouble().pow(years.toDouble())).toInt() fun identity(number: Int) = number fun half(number: Int) = (number/2).toInt() fun zero(number: Int) = 0 fun generate(functionName: String): (Int) -> Int { when (functionName) { "identity" -> return { number -> (identity(number)) } "half" -> return { number -> half(number) } "zero" -> return { number -> zero(number) } else -> throw RuntimeException("Error") } }
0
Kotlin
0
0
9e673057c3255be66fd67479b8198fa129463d95
21,225
kotlin-lab
Apache License 2.0
src/main/kotlin/org/kotrix/discrete/automata/GrammarToNFA.kt
JarnaChao09
285,169,397
false
{"Kotlin": 446442, "Jupyter Notebook": 26378}
package org.kotrix.discrete.automata /** * Helper function to wrap output in visual line breaks * * @param title title of the specific section * @param separator string to use as the line break string * @param n length of the line break * @param block block of code to run in between the line breaks */ fun wrap(title: String, separator: String = "-", n: Int = 20, block: () -> Unit): Unit { println(title) repeat(n) { print(separator) } println() block() repeat(n) { print(separator) } println() } /** * Enum for differentiating the token type * * ID: identifiers * EQ: equal size * OR: pipe * AC: character that is inside the alphabet * AS: accepting state * NL: newline */ enum class TokenType { ID, EQ, OR, AC, AS, NL, } /** * Class for storing the tokens in the lexer * * @property value the lexeme of the token * @property type the type of the token, see [TokenType] */ data class Token(val value: String, val type: TokenType) /** * Sealed interface for the Grammar Abstract Syntax Tree (AST) Structure * * @property next the next node in the AST (more of a vine instead of a tree) */ sealed interface Grammar { var next: Grammar? } /** * AST node for an identifier * * @property name the name of the identifier */ data class Ident(val name: String, override var next: Grammar? = null) : Grammar { override fun toString(): String = "$name${next?.toString() ?: ""}" } /** * AST node for an alphabetic character * * @property character the character this node represents, stored as a string for easier conversions */ data class AlphabetCharacter(val character: String, override var next: Grammar? = null) : Grammar { override fun toString(): String = "$character${next?.toString() ?: ""}" } /** * AST node for marking a state as an accepting state */ data class AcceptingState(override var next: Grammar? = null) : Grammar { override fun toString(): String = "AcceptingState${next?.toString() ?: ""}" } /** * AST node for a production rule * * @property identifier the left hand side of the =, the recursive variable * @property rule a list of all grammar strings to use as the production rule */ data class Rule(val identifier: Grammar, val rule: List<Grammar>, override var next: Grammar? = null) : Grammar { override fun toString(): String = "$identifier = ${rule.joinToString(separator = " | ")}${ if (next != null) { "\n${next.toString()}" } else { "" } }" } /** * Function to lex the inputted grammar string based on an alphabet and accepting state string into a list of tokens * used for parsing. This function will get the string into a more unified structure (ignoring whitespaces) * * @param input the inputted grammar string * @param alphabet a set of characters considered the alphabet * @param acceptingState the string which will be used to denote states as accepting states * @return list of tokens */ fun lex(input: String, alphabet: Set<Char>, acceptingState: String): List<Token> { return buildList { var i = 0 while (i < input.length) { val c = input[i] when (c) { ' ' -> {} in alphabet -> add(Token("$c", TokenType.AC)) '\n' -> add(Token("\\n", TokenType.NL)) '|' -> add(Token("$c", TokenType.OR)) '=' -> add(Token("$c", TokenType.EQ)) else -> { val s = buildString { append(c) i++ while (i < input.length && (input[i] !in alphabet && input[i] != '\n' && input[i] != '|' && input[i] != '=' && input[i] != ' ')) { append(input[i++]) } i-- } add( Token( s, if (s == acceptingState) { TokenType.AS } else { TokenType.ID } ) ) } } i++ } } } /** * Class to hold the current parsing state * * @param tokens list of tokens to be parsed * @param index current token being parsed */ data class ParserState(val tokens: List<Token>, val index: Int) { val value: Token? get() = if (index < tokens.size) { tokens[index] } else { null } val nextState: ParserState get() = ParserState(tokens, index + 1) } // Recursive Descent Parser /** * Handles identifiers, alphabet characters, and the accepting state marker * * atom -> identifier | alphabet_character | accepting_state * identifier -> non_alphabet_character * * @param state current state of the parser * @return the partially constructed grammar AST and updated parser state */ fun atom(state: ParserState): Pair<Grammar, ParserState> { var currentState = state var ret: Grammar? = null var curr: Grammar? = null while ((currentState.value?.type?.equals(TokenType.ID) == true) || (currentState.value?.type?.equals(TokenType.AC) == true) || (currentState.value?.type?.equals(TokenType.AS) == true) ) { val value = currentState.value!! when (value.type) { TokenType.ID -> { if (ret == null) { ret = Ident(value.value) curr = ret } else { curr!!.next = Ident(value.value) curr = curr.next } } TokenType.AC -> { if (ret == null) { ret = AlphabetCharacter(value.value) curr = ret } else { curr!!.next = AlphabetCharacter(value.value) curr = curr.next } } TokenType.AS -> { if (ret == null) { ret = AcceptingState() curr = ret } else { curr!!.next = AcceptingState() curr = curr.next } } else -> { error("error state 1") } } currentState = currentState.nextState } return (ret ?: error("error state 2")) to currentState } /** * Handles production rules * * Rule -> identifier '=' atom ('|' atom)* * * @param state current state of the parser * @return the partially constructed grammar AST and updated parser state */ fun rule(state: ParserState): Pair<Grammar, ParserState> { var (expr: Grammar, currentState) = atom(state) if (currentState.value?.type?.equals(TokenType.EQ) == true) { val rules = buildList { do { currentState = currentState.nextState val (c, s) = atom(currentState) add(c) currentState = s } while (currentState.value?.type?.equals(TokenType.OR) == true) } expr = Rule(expr, rule = rules) } return expr to currentState } /** * Runner function to perform the recursive descent parsing and to build the rule's vine (linked list) * * @param input list of tokens to be parsed * @return fully constructed grammar AST */ fun parse(input: List<Token>): Grammar { val state = ParserState(input, -1) var ret: Grammar? = null var curr: Grammar? = null var currentState = state do { currentState = currentState.nextState val (tr, ts) = rule(currentState) currentState = ts if (ret == null) { ret = tr curr = ret } else { curr!!.next = tr curr = curr.next } } while (currentState.value?.type?.equals(TokenType.NL) == true) return ret!! } /** * Class to hold NFA nodes * * @param stateID id of the specific state * @param transitions labelled transitions from state to state * @param lambdaTransitions labelled lambda transitions from state to state */ data class NFANode( val stateID: String, val transitions: Map<String, Set<String>>, val lambdaTransitions: Set<String> = setOf(), ) /** * NFA structure class * * @param startState state designated as start state * @param acceptStates set of states designated as final states * @param nfaNodes map of state id to node object */ class NFA(val startState: String, val acceptStates: Set<String>, val nfaNodes: Map<String, NFANode>) { /** * Tests if the NFA accepts the inputted string * * @param value the inputted string to test * @return true if accepted, false if not */ fun accepts(value: String): Boolean { // set of all states to check with a cursor // the cursor states where in the value string the current "state" is at var currentStates = setOf(startState to 0) // once a state's cursor exceeds the length of the inputted string, it is in a finished state val finishedStates = mutableSetOf<String>() // run the automaton until there are no states to run for while (currentStates.isNotEmpty()) { currentStates = buildSet { for ((currentState, currentIndex) in currentStates) { // if the current cursor location is still within the string, determine the next transition // otherwise, add the string to the finish states, no more symbols can be inputted into the machine if (currentIndex < value.length) { val node = nfaNodes[currentState]!! for ((transitionString, destinationNode) in node.transitions) { if (currentIndex + transitionString.length <= value.length && value.substring(currentIndex..<currentIndex + transitionString.length) == transitionString) { destinationNode.forEach { add(it to currentIndex + transitionString.length) } } } addAll(node.lambdaTransitions.map { it to currentIndex }) } else { finishedStates.add(currentState) } } } } // check if any of the finished states are in the accept states return finishedStates.any { it in acceptStates } } /** * @return string representation of the NFA */ override fun toString(): String { return buildString { append("Start State: ${this@NFA.startState} | Accept States: ${this@NFA.acceptStates}") append('\n') for ((lhs, node) in this@NFA.nfaNodes) { append(" $lhs -> $node") append('\n') } } } } /** * Converts from Grammar AST to NFA object * * @param grammar grammar to convert * @param startState state ID of the start state * @param defaultAcceptState state ID of the accept state * @return fully constructed NFA */ fun grammar2NFA(grammar: Grammar, startState: String, defaultAcceptState: String = "X"): NFA { // head of the grammar vine var current: Grammar? = grammar // set of all accepting states val acceptingStateSet = mutableSetOf(defaultAcceptState) // creation of map of state id to nfa object val nfaMap = buildMap { // add a default accept state to be used in certain cases [covered later] put(defaultAcceptState, NFANode(defaultAcceptState, emptyMap(), emptySet())) while (current != null) { // current set of lambda transitions val currentLambdaTransitions = mutableSetOf<String>() // current set of labelled transitions // set of nodes a transition goes to as this is an NFA val currentTransitions = mutableMapOf<String, Set<String>>() // current node in the vine val c = current // traverse to the next node in the vine current = current?.next when (c) { // if the current node is a rule is Rule -> { // checking if the left hand side of the '=' is an identifier (resolver phase) val currentState = when (val id = c.identifier) { is Ident -> id.name else -> error("lhs of a = must be an identifier") } // for every grammar node in the rule for (g in c.rule) { when (g) { // set this current state as an accepting state is AcceptingState -> acceptingStateSet.add(currentState) // set this current state to have a lambda transition to the identifier is Ident -> currentLambdaTransitions.add(g.name) // construct the full alphabet multi-character transition is AlphabetCharacter -> { var currentChar: Grammar? = g var sum = "" while (currentChar != null) { when (currentChar) { // if the current character is an alphabet character, add it to the running sum is AlphabetCharacter -> { sum += currentChar.character currentChar = currentChar.next // if the next character is null, this is a terminal branch, add a transition to the default accept state to follow the right linear grammar syntax if (currentChar == null) { currentTransitions[sum] = currentTransitions.getOrDefault(sum, emptySet()) union setOf(defaultAcceptState) } } // current character is an identifier // assume this is the end of the string as the grammar parser can only handle right linear grammars // add a transition to the identifier is Ident -> { currentTransitions[sum] = currentTransitions.getOrDefault(sum, emptySet()) union setOf(currentChar.name) currentChar = currentChar.next } // rules cannot be nested else -> error("cannot nest rule") } } } // rules cannot be nested is Rule -> error("cannot nest rule") } // tie the state id to the constructed NFA object put(currentState, NFANode(currentState, currentTransitions, currentLambdaTransitions)) } } // at top level, the grammar should only be consisting of rules else -> error("top level should be rule") } } } // given the start state, set of accepting states, and nfa map, construct the NFA object return NFA(startState, acceptingStateSet, nfaMap) } /** * Helper function to enumerate over all strings in the alphabet up to a certain length * * \forall w : w \in L \and |w| \le n * * @param size max length of the string * @param alphabet set of all alphabet characters * @return sequence of all enumerated strings */ fun enumerate(size: Int, alphabet: Set<Char>): Sequence<String> { return sequence { // memory of previous strings yielded in the enumeration var prev = listOf("") // repeat until the string is the desired length repeat(size) { // yield the next permutation of the string with the alphabet and memoize the result to be use in the next loop prev = buildList { for (str in prev) { for (alphabetCharacter in alphabet) { val tmp = str + alphabetCharacter add(tmp) yield(tmp) } } } } } } fun main() { var i = 0 val currentGrammar = mutableListOf<String>() var currentAlphabet = setOf('0', '1') var currentStartState = "S" var currentAcceptingState = "X" var currentAcceptedStrings = listOf<String>() var currentRejectedStrings = listOf<String>() while (true) { print("[${i++ + 1}]>>> ") val line = readln() when (val l = line.trim()) { ":f", ":F", ":fail" -> wrap("Rejected Strings") { currentRejectedStrings.forEach(::println) } ":h", ":H", ":help" -> println( """ Grammar to NFA automation program v0.0.1 Commands: :a / :A / :alpha c1 c2 ... cn - sets the alphabet to the set of c1 c2 ... cn (must be space separated) :d / :D / :delete index - removes the production rule at the specified index (0-based indexing) :e / :E / :exec n - executes the current grammar with an enumeration of all strings consisting of strings of length n :f / :F / :fail - lists all strings that failed the last exeuction of the grammar :h / :H / :help - prints out this help message :l / :L / :list - prints out the current grammar :p / :P / :pass - lists all strings that passed the last execution of the grammar :q / :Q / :quit - quits the REPL :r / :R / :reset - clears the current grammar of all production rules :s / :S / :start str - sets the start string to the value of str :u / :U / :undo - removes the last production rule :x / :X / :accept str - sets the accepting string to the value of str All other strings that do not start with : are considered production rules in the grammar Current Limitations: Very sparse syntax error checking in grammar strings Overriding of production rules is not possible No error checking when using commands, may hard crash """.trimIndent() ) ":l", ":L", ":list" -> currentGrammar.forEachIndexed { index, s -> println("$index: $s") } ":p", ":P", ":pass" -> wrap("Accepted Strings") { currentAcceptedStrings.forEach(::println) } ":q", ":Q", ":quit" -> kotlin.system.exitProcess(0) else -> l.split(" ").run { when (this[0]) { ":a", ":A", ":alpha" -> currentAlphabet = this.drop(1).map { it[0] }.toSet() ":d", ":D", ":delete" -> currentGrammar.removeAt(this[1].toInt()) ":e", ":E", ":exec" -> { val n = this.getOrElse(1) { "5" }.toInt() val tokens = lex( currentGrammar.joinToString(separator = "\n", prefix = "", postfix = ""), currentAlphabet, currentAcceptingState ) val tree = parse(tokens).also { wrap("Grammar") { println(it) } } val nfa = grammar2NFA(tree, currentStartState).also { wrap("NFA") { println(it) } } enumerate(n, currentAlphabet).partition { nfa.accepts(it) }.run { currentAcceptedStrings = first currentRejectedStrings = second } } ":r", ":R", ":reset" -> currentGrammar.clear() ":s", ":S", ":start" -> currentStartState = this[1] ":u", ":U", ":undo" -> currentGrammar.removeLast() ":x", ":X", ":accept" -> currentAcceptingState = this[1] else -> if (l.startsWith(":")) { println("Invalid Command \"$l\"") } else { currentGrammar += l } } } } } }
0
Kotlin
1
5
c5bb19457142ce1f3260e8fed5041a4d0c77fb14
21,383
Kotrix
MIT License
2022/src/main/kotlin/Day21.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import Day21.Operation.* object Day21 { fun part1(input: String): Long { val monkeys = parseMonkeys(input).associateBy { it.name } return getYell("root", monkeys) } fun part2(input: String): Long { val monkeyMap = parseMonkeys(input).filter { it.name != "humn" }.associateBy { it.name } val yellMap = mutableMapOf<String, Long>() fillYellMap("root", monkeyMap, yellMap) val root = monkeyMap["root"] as Monkey.OperationMonkey if (root.b in yellMap) { return findHumanYell(root.a, monkeyMap, yellMap, yellMap[root.b]!!) } else { return findHumanYell(root.b, monkeyMap, yellMap, yellMap[root.a]!!) } } private fun findHumanYell( monkeyName: String, monkeyMap: Map<String, Monkey>, yellMap: Map<String, Long>, result: Long ): Long { if (monkeyName == "humn") { return result } val monkey = monkeyMap[monkeyName] as Monkey.OperationMonkey if (monkey.a in yellMap) { val yellA = yellMap[monkey.a]!! val resultUndone = monkey.reverseForB(yellA, result) return findHumanYell(monkey.b, monkeyMap, yellMap, resultUndone) } else { val yellB = yellMap[monkey.b]!! val resultUndone = monkey.reverseForA(yellB, result) return findHumanYell(monkey.a, monkeyMap, yellMap, resultUndone) } } // Given a full set of data, what does this monkey yell? private fun getYell( monkeyName: String, monkeyMap: Map<String, Monkey>, yellMap: MutableMap<String, Long> = mutableMapOf(), ): Long { return yellMap.getOrPut(monkeyName) { when (val monkey = monkeyMap[monkeyName]!!) { is Monkey.ValueMonkey -> monkey.value is Monkey.OperationMonkey -> monkey.operation( getYell(monkey.a, monkeyMap, yellMap), getYell(monkey.b, monkeyMap, yellMap) ) } } } // Given a set of data minus humn, how much can we pre-calculate the monkeys yelling? private fun fillYellMap( monkeyName: String, monkeyMap: Map<String, Monkey>, yellMap: MutableMap<String, Long> = mutableMapOf(), ): Long? { if (monkeyName !in yellMap) { when (val monkey = monkeyMap[monkeyName] ?: return null) { is Monkey.ValueMonkey -> yellMap[monkeyName] = monkey.value is Monkey.OperationMonkey -> { val yellA = fillYellMap(monkey.a, monkeyMap, yellMap) val yellB = fillYellMap(monkey.b, monkeyMap, yellMap) yellMap[monkeyName] = monkey.operation( yellA ?: return null, yellB ?: return null ) } } } return yellMap[monkeyName] } private val VALUE_MONKEY = Regex("(\\w{4}): (\\d+)") private val OPERATION_MONKEY = Regex("(\\w{4}): (\\w{4}) (.) (\\w{4})") private fun parseMonkeys(input: String): List<Monkey> { return input.splitNewlines() .map { val valueMatch = VALUE_MONKEY.matchEntire(it) if (valueMatch != null) { return@map Monkey.ValueMonkey(valueMatch.groupValues[1], valueMatch.groupValues[2].toLong()) } val (name, a, opStr, b) = OPERATION_MONKEY.matchEntire(it)!!.destructured val operation = when (opStr) { "+" -> PLUS "-" -> MINUS "*" -> TIMES "/" -> DIV else -> throw IllegalArgumentException("Unknown operation: $opStr") } return@map Monkey.OperationMonkey(name, a, b, operation) } } enum class Operation { PLUS, MINUS, TIMES, DIV } sealed class Monkey { abstract val name: String data class ValueMonkey(override val name: String, val value: Long) : Monkey() data class OperationMonkey( override val name: String, val a: String, val b: String, val operation: Operation, ) : Monkey() { fun operation(a: Long, b: Long): Long { return when (operation) { PLUS -> a + b MINUS -> a - b TIMES -> a * b DIV -> a / b } } fun reverseForA(b: Long, result: Long): Long { return when (operation) { PLUS -> result - b MINUS -> result + b TIMES -> result / b DIV -> result * b } } fun reverseForB(a: Long, result: Long): Long { return when (operation) { PLUS -> result - a MINUS -> a - result TIMES -> result / a DIV -> a / result } } } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
4,465
advent-of-code
MIT License
src/day23/day23.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day23 import readInput private fun parse(input: List<String>): HashMap<Int, HashSet<Int>> { fun HashMap<Int, HashSet<Int>>.addItem(row: Int, col: Int) { val values = getOrDefault(row, hashSetOf()) values.add(col) put(row, values) } val result = HashMap<Int, HashSet<Int>>() for ((rowIndex, row) in input.withIndex()) { for ((colIndex, item) in row.withIndex()) { if (item == '#') result.addItem(rowIndex, colIndex) } } return result } fun HashMap<Int, HashSet<Int>>.isNorthFree(row: Int, col: Int): Boolean { val north = get(row - 1).orEmpty() return north.isEmpty() || (north.contains(col) || north.contains(col - 1) || north.contains(col + 1)).not() } fun HashMap<Int, HashSet<Int>>.isSouthFree(row: Int, col: Int): Boolean { val south = get(row + 1).orEmpty() return south.isEmpty() || (south.contains(col) || south.contains(col - 1) || south.contains(col + 1)).not() } fun HashMap<Int, HashSet<Int>>.isWestFree(row: Int, col: Int): Boolean { return (get(row - 1).orEmpty().contains(col - 1) || get(row).orEmpty().contains(col - 1) || get(row + 1).orEmpty().contains(col - 1)).not() } fun HashMap<Int, HashSet<Int>>.isEastFree(row: Int, col: Int): Boolean { return (get(row - 1).orEmpty().contains(col + 1) || get(row).orEmpty().contains(col + 1) || get(row + 1).orEmpty().contains(col + 1)).not() } fun HashMap<Int, HashSet<Int>>.isNoOneAround(row: Int, col: Int): Boolean { return isNorthFree(row, col) && isSouthFree(row, col) && isWestFree(row, col) && isEastFree(row, col) } private const val MOVES_NUMBER = 4 fun HashMap<Int, HashSet<Int>>.findMove(round: Int, row: Int, col: Int): Pair<Int, Int>? { val moves = listOf( Pair({ this.isNorthFree(row, col) }, Pair(row - 1, col)), Pair({ this.isSouthFree(row, col) }, Pair(row + 1, col)), Pair({ this.isWestFree(row, col) }, Pair(row, col - 1)), Pair({ this.isEastFree(row, col) }, Pair(row, col + 1)) ) var counter = round % MOVES_NUMBER for (index in 0 until MOVES_NUMBER) { val potentialMove = moves[counter] if (potentialMove.first.invoke()) { return potentialMove.second } counter = (counter + 1) % MOVES_NUMBER } return null } private fun moves(elves: HashMap<Int, HashSet<Int>>, maxRounds: Int): Pair<Int, HashMap<Int, HashSet<Int>>> { var round = 0 while (round < maxRounds) { val proposeMoves = HashMap<Pair<Int, Int>, MutableList<Pair<Int, Int>>>() for ((rowIndex, row) in elves) { for (colIndex in row) { if (elves.isNoOneAround(rowIndex, colIndex)) continue elves.findMove(round, rowIndex, colIndex)?.run { val values = (proposeMoves[this] ?: mutableListOf()).apply { add(Pair(rowIndex, colIndex)) } proposeMoves.put(this, values) } } } var wasMove = false for ((key, value) in proposeMoves) { if (value.size == 1) { wasMove = true elves[value[0].first]?.remove(value[0].second) val values = elves.getOrDefault(key.first, hashSetOf()) values.add(key.second) elves[key.first] = values } } round++ if (!wasMove) return Pair(round, elves) } return Pair(round, elves) } private fun findMax(elves: HashMap<Int, HashSet<Int>>): Int { var top = Int.MAX_VALUE var bottom = Int.MIN_VALUE var left = Int.MAX_VALUE var right = Int.MIN_VALUE for ((key, values) in elves) { for (colIndex in values) { top = key.coerceAtMost(top) bottom = key.coerceAtLeast(bottom) left = colIndex.coerceAtMost(left) right = colIndex.coerceAtLeast(right) } } var result = (right - left + 1) * (bottom - top + 1) for ((_, value) in elves) { result -= value.size } return result } private const val MAX_MOVES_FIRST = 10 private fun part1(input: List<String>): Int { val elves = parse(input) val movesResult = moves(elves, MAX_MOVES_FIRST) return findMax(movesResult.second) } private const val MAX_MOVE_SECOND = 10000 private fun part2(input: List<String>): Int { val elves = parse(input) val movesResult = moves(elves, MAX_MOVE_SECOND) return movesResult.first } fun main() { val input = readInput("day23/input") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
4,716
aoc-2022
Apache License 2.0
src/main/kotlin/com/github/freekdb/aoc2019/Day03.kt
FreekDB
228,241,398
false
null
package com.github.freekdb.aoc2019 import java.io.File private const val DIRECTION_UP = 'U' private const val DIRECTION_DOWN = 'D' private const val DIRECTION_LEFT = 'L' private const val DIRECTION_RIGHT = 'R' // Heavily inspired by <NAME>: // https://github.com/tginsberg/advent-2019-kotlin/blob/master/src/main/kotlin/com/ginsberg/advent2019/Day03.kt // https://adventofcode.com/2019/day/3 fun main(arguments: Array<String>) { val inputPath = if (arguments.isEmpty()) "input/day-03--input.txt" else arguments[0] findCrossingDistance(inputPath) } private fun findCrossingDistance(inputPath: String) { val inputLines = File(inputPath) .readLines() .filter { it.isNotEmpty() } val path1 = parsePath(inputLines[0]) val path2 = parsePath(inputLines[1]) val intersections = path1.intersect(path2) val crossingDistance = solvePart1(intersections) println("Crossing distance: $crossingDistance") val combinedSteps = solvePart2(intersections, path1, path2) println("Combined steps: $combinedSteps") } private fun parsePath(path: String): List<Point2D> { var currentPoint = Point2D.ORIGIN return path.split(",").flatMap { val direction = it.first() val distance = it.drop(1).toInt() val segment = (0 until distance).map { val nextPoint = when (direction) { DIRECTION_UP -> currentPoint.up() DIRECTION_DOWN -> currentPoint.down() DIRECTION_LEFT -> currentPoint.left() DIRECTION_RIGHT -> currentPoint.right() else -> throw IllegalArgumentException("Invalid direction: $direction") } currentPoint = nextPoint nextPoint } segment } } private fun solvePart1(intersections: Set<Point2D>): Int = intersections.map { it.distanceTo(Point2D.ORIGIN) }.min() ?: -1 private fun solvePart2(intersections: Set<Point2D>, path1: List<Point2D>, path2: List<Point2D>): Int = intersections.map { 2 + path1.indexOf(it) + path2.indexOf(it) }.min() ?: -1
0
Kotlin
0
1
fd67b87608bcbb5299d6549b3eb5fb665d66e6b5
2,107
advent-of-code-2019
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/dynamicprogramming/KnapSackProblem.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.dynamicprogramming import kotlin.math.max fun main() { val items = mutableListOf<List<Int>>() items.add(listOf(2, 2)) items.add(listOf(3, 3)) items.add(listOf(4, 10)) items.add(listOf(5, 7)) items.add(listOf(2, 4)) println(knapsackProblem(items, 7)) } fun knapsackProblem(items: List<List<Int>>, capacity: Int): Pair<Int, List<Int>> { val knapSack = List(items.size + 1) { MutableList<Int>(capacity + 1) { 0 } } for (i in 1 until items.size + 1) { val currentWeight = items[i - 1][1] val currentValue = items[i - 1][0] for (c in 0 until capacity + 1) { if (currentWeight > c) { knapSack[i][c] = knapSack[i - 1][c] } else { val potentialMax = knapSack[i - 1][c - currentWeight] + currentValue knapSack[i][c] = max(potentialMax, knapSack[i - 1][c]) } } } return getKnapSackItems(knapSack, knapSack[items.size][capacity], items) } fun getKnapSackItems(knapSack: List<MutableList<Int>>, weight: Int, items: List<List<Int>>): Pair<Int, List<Int>> { val sequence = mutableListOf<Int>() val pair = Pair(weight, sequence) var i = knapSack.size - 1 var c = knapSack[0].size - 1 while (i > 0) { if (knapSack[i][c] == knapSack[i-1][c]) { i-- } else { sequence.add(i - 1) c -= items[i-1][1] i-- } if (c == 0) { break } } return pair }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,559
DS_Algo_Kotlin
MIT License
src/main/kotlin/dev/tasso/adventofcode/_2021/day02/Day02.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2021.day02 import dev.tasso.adventofcode.Solution import kotlin.math.absoluteValue class Day02 : Solution<Int> { override fun part1(input: List<String>): Int { // Split the input into lists of horizontal and vertical movements val (horizontalMovements, verticalMovements) = input.partition { it.startsWith("forward") } // We can only go forward, so strip the direction text, and sum all the values to get the total val horizontalTotal = horizontalMovements.map { it.removePrefix("forward ") } .sumOf { it.toInt() } // Up is positive, down is negative. Strip the direction text if we're going up, or replace with a negative sign. // Then, sum all the values to get the total val verticalTotal = verticalMovements.map { it.removePrefix("up ") } .map { it.replace("down ", "-") } .sumOf { it.toInt() } return horizontalTotal * verticalTotal.absoluteValue } override fun part2(input: List<String>): Int { var horizontalPosition = 0 var verticalPosition = 0 var aim = 0 for(command in input) { if(command.startsWith("forward ")) { val forwardDistance = command.removePrefix("forward ").toInt() horizontalPosition += forwardDistance verticalPosition += forwardDistance * aim } else if (command.startsWith("up ") || command.startsWith("down ")){ val verticalDistance = command.removePrefix("up ").replace("down ", "-").toInt() aim += verticalDistance } } return horizontalPosition * verticalPosition.absoluteValue } }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
1,739
advent-of-code
MIT License
year2023/day07/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day07/part2/Year2023Day07Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- To make things a little more interesting, the Elf introduces one additional rule. Now, `J` cards are jokers - wildcards that can act like whatever card would make the hand the strongest type possible. To balance this, `J` cards are now the weakest individual cards, weaker even than 2. The other cards stay in the same order: `A`, `K`, `Q`, `T`, 9, 8, 7, 6, 5, 4, 3, 2, `J`. `J` cards can pretend to be whatever card is best for the purpose of determining hand type; for example, `QJJQ2` is now considered four of a kind. However, for the purpose of breaking ties between two hands of the same type, `J` is always treated as `J`, not the card it's pretending to be: `JKKK2` is weaker than `QQQQ2` because `J` is weaker than `Q`. Now, the above example goes very differently: ``` 32T3K 765 T55J5 684 KK677 28 KTJJT 220 QQQJA 483 ``` - `32T3K` is still the only one pair; it doesn't contain any jokers, so its strength doesn't increase. - `KK677` is now the only two pair, making it the second-weakest hand. - `T55J5`, `KTJJT`, and `QQQJA` are now all four of a kind! `T55J5` gets rank 3, `QQQJA` gets rank 4, and `KTJJT` gets rank 5. With the new joker rule, the total winnings in this example are 5905. Using the new joker rule, find the rank of every hand in your set. What are the new total winnings? */ package com.curtislb.adventofcode.year2023.day07.part2 import com.curtislb.adventofcode.common.io.mapLines import com.curtislb.adventofcode.year2023.day07.cards.Hand import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2023, day 7, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val hands = inputPath.toFile().mapLines { Hand.fromString(it, useJokerRule = true) } return hands.sorted().withIndex().sumOf { (index, hand) -> hand.bid * (index + 1).toLong() } } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,998
AdventOfCode
MIT License
aoc21/day_14/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File class Polymer(var pairs: Map<String, Long>, val last: Char) { var chars = mutableMapOf<Char, Long>() constructor (str: String) : this( str.windowed(2).groupingBy { it }.eachCount().mapValues { it.value.toLong() }.toMap(), str.last(), ) fun step(rules: Map<String, String>) { val newPairs = mutableMapOf<String, Long>() for ((pair, freq) in pairs) { newPairs.merge(pair[0] + rules.get(pair)!!, freq, Long::plus) newPairs.merge(rules.get(pair)!! + pair[1], freq, Long::plus) } pairs = newPairs } fun apply(rules: Map<String, String>, steps: Int) { repeat(steps) { step(rules) } chars = pairs .asIterable() .groupingBy { it.key[0] } .fold(0.toLong()) { sum, p -> sum + p.value } .toMap().toMutableMap() chars.merge(last, 1, Long::plus) } fun diff(): Long = chars.values.maxOrNull()!! - chars.values.minOrNull()!! } fun main() { val input = File("input").readLines() val rules = input.drop(2).map { it.split(" -> ").let { it[0] to it[1] } }.toMap() val polymer = Polymer(input[0]) polymer.apply(rules, 10) println("First: ${polymer.diff()}") polymer.apply(rules, 30) println("Second: ${polymer.diff()}") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
1,334
advent-of-code
MIT License
src/main/kotlin/days/Day9.kt
mir47
433,536,325
false
{"Kotlin": 31075}
package days class Day9 : Day(9) { override fun partOne(): Int { var result = 0 inputList.forEachIndexed { i, s -> (s.indices).forEach { j -> var passH = when (j) { 0 -> s[j].digitToInt() < s[j+1].digitToInt() s.length-1 -> s[j].digitToInt() < s[j-1].digitToInt() else -> s[j].digitToInt() < s[j-1].digitToInt() && s[j].digitToInt() < s[j+1].digitToInt() } var passV = when (i) { 0 -> s[j].digitToInt() < inputList[i+1][j].digitToInt() inputList.size-1 -> s[j].digitToInt() < inputList[i-1][j].digitToInt() else -> s[j].digitToInt() < inputList[i-1][j].digitToInt() && s[j].digitToInt() < inputList[i+1][j].digitToInt() } if (passH && passV) result += s[j].digitToInt() + 1 } } return result } override fun partTwo(): Int { val basins = mutableMapOf<Int, Int>() var basinCount = 0 var prev = MutableList(inputList[0].length) { 0 } var current = MutableList(inputList[0].length) { 0 } inputList.forEachIndexed { rowIndex, rowItem -> current = MutableList(inputList[0].length) { 0 } rowItem.forEachIndexed { pointIndex, pointItem -> val pointPrev = if (pointIndex == 0) 9 else rowItem[pointIndex - 1].digitToInt() val point = pointItem.digitToInt() var basin = 0 if (point < 9) { if (pointPrev < 9) { basin = current[pointIndex-1] basins.merge(basin, 1) { a, b -> a + b } if (prev[pointIndex] > 0 && prev[pointIndex] != basin) { val oldBasin = prev[pointIndex] prev.forEachIndexed { index, i -> if (i == oldBasin) { prev[index] = basin } } basins.merge(basin, basins.getOrDefault(oldBasin, 0)) { a, b -> a + b } basins.remove(oldBasin) } } else if (rowIndex > 0) { if (prev[pointIndex] > 0) { basin = prev[pointIndex] basins.merge(prev[pointIndex], 1) { a, b -> a + b } } else { basinCount++ basin = basinCount basins[basin] = 1 } } else { basinCount++ basin = basinCount basins[basin] = 1 } } current[pointIndex] = basin } prev = current } val sorted = basins.toList().sortedByDescending { (key, value) -> value } return sorted[0].second * sorted[1].second * sorted[2].second } }
0
Kotlin
0
0
686fa5388d712bfdf3c2cc9dd4bab063bac632ce
3,164
aoc-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day22.kt
hughjdavey
317,575,435
false
null
package days import splitOnBlank class Day22 : Day(22) { // 34566 override fun partOne(): Any { return getGame(false).playUntilOver().score } // 31854 override fun partTwo(): Any { return getGame(true).playUntilOver().score } private fun getGame(recursive: Boolean): Combat { val (p1, p2) = inputList.splitOnBlank().map { ArrayDeque(it.drop(1).map { it.toInt() }) } return Combat(p1, p2, recursive) } // todo recursive iteration takes around 3 seconds - could be improvded data class Combat(val player1: ArrayDeque<Int>, val player2: ArrayDeque<Int>, val recursive: Boolean = false) { private val snapshots = mutableListOf<CombatSnapshot>() fun playUntilOver(): CombatState { var rounds = 0 while (player1.isNotEmpty() && player2.isNotEmpty()) { rounds++ // changed to || to && based on following reddit discussion (also && was not finishing) // https://www.reddit.com/r/adventofcode/comments/kicn13/2020_day_22_interpretation_of_previously_seen/ if (recursive && snapshots.any { it.player1 == player1.toList() || it.player2 == player2.toList() }) { player2.clear() break } if (recursive) { snapshots.add(CombatSnapshot(rounds, player1.toList(), player2.toList())) } round() } val winner = if (player1.isEmpty()) 2 to player2 else 1 to player1 return CombatState(rounds, winner.first, winner.second, score(winner.second)) } private fun round() { val (p1, p2) = player1.removeFirst() to player2.removeFirst() val p1Win = if (recursive && player1.count() >= p1 && player2.count() >= p2) { Combat(ArrayDeque(player1.toList().take(p1)), ArrayDeque(player2.toList().take(p2)), true).playUntilOver().winner == 1 } else p1 > p2 if (p1Win) player1.addAll(listOf(p1, p2)) else player2.addAll(listOf(p2, p1)) } private fun score(player: ArrayDeque<Int>): Int { return player.reversed().foldIndexed(0) { index, score, card -> score + (card * (index + 1)) } } } data class CombatState(val rounds: Int, val winner: Int, val deck: ArrayDeque<Int>, val score: Int) data class CombatSnapshot(val round: Int, val player1: List<Int>, val player2: List<Int>) }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,533
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day18.kt
andilau
433,504,283
false
{"Kotlin": 137815}
package days @AdventOfCodePuzzle( name = "Snailfish", url = "https://adventofcode.com/2021/day/18", date = Date(day = 18, year = 2021) ) class Day18(val input: List<String>) : Puzzle { private val snailfishNumbers = input.map(SnailfishNumber::from) override fun partOne() = snailfishNumbers .reduce { a, b -> a + b } .magnitude() override fun partTwo() = snailfishNumbers.flatMap { i -> snailfishNumbers.map { j -> i to j } } .filterNot { (i, j) -> i == j } .map { (i, j) -> i + j } .maxOf { it.magnitude() } sealed class SnailfishNumber { class Regular(val value: Int) : SnailfishNumber() { override fun toString() = "$value" } class Pair(val left: SnailfishNumber, val right: SnailfishNumber) : SnailfishNumber() { override fun toString() = "[$left,$right]" } operator fun plus(other: SnailfishNumber): SnailfishNumber = generateSequence<SnailfishNumber>(Pair(this, other)) { s -> s.reduce()?.let { s.replace(it) } }.last() fun findRegularEligibleForSplit(): Regular? = when (this) { is Pair -> { left.findRegularEligibleForSplit()?.run { return this } right.findRegularEligibleForSplit()?.run { return this } } is Regular -> if (value >= 10) this else null } fun findPairEligibleForExplode(depth: Int = 4): Pair? = when (this) { is Pair -> { if (depth == 0) this else { left.findPairEligibleForExplode(depth - 1)?.run { return this } right.findPairEligibleForExplode(depth - 1)?.run { return this } } } is Regular -> null } private fun listOfRegularsAnd(pair: Pair): List<SnailfishNumber> = when (this) { is Regular -> listOf(this) is Pair -> if (this == pair) listOf(this) else left.listOfRegularsAnd(pair) + right.listOfRegularsAnd(pair) } fun reduce(): Map<SnailfishNumber, SnailfishNumber>? { findPairEligibleForExplode()?.run { val substitutions = mutableMapOf<SnailfishNumber, SnailfishNumber>(this to Regular(0)) val listOfRegularsAndPair = this@SnailfishNumber.listOfRegularsAnd(this) val index = listOfRegularsAndPair.indexOf(this) val regularLeft = listOfRegularsAndPair.getOrNull(index - 1) as Regular? regularLeft?.let { substitutions[it] = Regular(it.value + (left as Regular).value) } val regularRight = listOfRegularsAndPair.getOrNull(index + 1) as Regular? regularRight?.let { substitutions[it] = Regular(it.value + (right as Regular).value) } return substitutions } findRegularEligibleForSplit()?.run { return mapOf( this to Pair( Regular(value / 2), Regular((value + 1) / 2) ) ) } return null } fun replace(substitute: Map<SnailfishNumber, SnailfishNumber>): SnailfishNumber { substitute[this]?.let { return it } return when (this) { is Regular -> this is Pair -> Pair(left.replace(substitute), right.replace(substitute)) } } fun magnitude(): Int = when (this) { is Regular -> value is Pair -> 3 * left.magnitude() + 2 * right.magnitude() } companion object { fun from(line: String): SnailfishNumber { var index = 0 fun parse(): SnailfishNumber { if (line[index] == '[') { index++ // '[' val x = parse() index++ // ',' val y = parse() index++ // ']' return Pair(x, y) } val begin = index while (line[index].isDigit()) index++ return Regular(line.substring(begin, index).toInt()) } return parse() } } } internal fun reduce() = snailfishNumbers.reduce { a, b -> a + b } companion object { internal fun fromAndToStringOf(sailfish: String) = SnailfishNumber.from(sailfish).toString() internal fun magnitudeOf(sailfish: String) = SnailfishNumber.from(sailfish).magnitude() internal fun explodingTermOf(sailfish: String) = SnailfishNumber.from(sailfish).findPairEligibleForExplode() internal fun splittingTermOf(sailfish: String) = SnailfishNumber.from(sailfish).findRegularEligibleForSplit() internal fun reducedFormOf(sailfish: String) = with(SnailfishNumber.from(sailfish)) { reduce()?.let { replace(it) }.toString() } } }
0
Kotlin
0
0
b3f06a73e7d9d207ee3051879b83e92b049a0304
5,116
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistinctSubsequences.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 /** * 115. Distinct Subsequences * @see <a href="https://leetcode.com/problems/distinct-subsequences/">Source</a> */ fun interface DistinctSubsequences { fun numDistinct(s: String, t: String): Int } class DistinctSubsequencesDP : DistinctSubsequences { override fun numDistinct(s: String, t: String): Int { // array creation val mem = Array(t.length + 1) { IntArray(s.length + 1) } // filling the first row: with 1s for (j in 0..s.length) { mem[0][j] = 1 } // the first column is 0 by default in every other rows but the first, which we need. for (i in t.indices) { for (j in s.indices) { if (t[i] == s[j]) { mem[i + 1][j + 1] = mem[i][j] + mem[i + 1][j] } else { mem[i + 1][j + 1] = mem[i + 1][j] } } } return mem[t.length][s.length] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,596
kotlab
Apache License 2.0
src/main/kotlin/shortestpath/전보.kt
CokeLee777
614,704,937
false
null
package shortestpath import java.util.* import kotlin.math.* private const val INF = 1e9.toInt() fun main(){ val sc = Scanner(System.`in`) val n = sc.nextInt() val m = sc.nextInt() val start = sc.nextInt() //최단거리 테이블 초기화 val distances = IntArray(n + 1) { INF } //그래프 초기화 val graph = mutableListOf<MutableList<City>>() for(i in 0..n){ graph.add(mutableListOf()) } //그래프 입력받기 for(i in 0 until m){ val x = sc.nextInt() val y = sc.nextInt() val z = sc.nextInt() graph[x].add(City(y, z)) } fun dijkstra(start: Int){ val pq = PriorityQueue<City>() //시작 노드 삽입 및 거리 0으로 초기화 pq.offer(City(start, 0)) distances[start] = 0 //큐가 빌 때까지 반복 while(!pq.isEmpty()){ val city = pq.poll() val now = city.index val distance = city.distance //이미 처리된 도시라면 무시 if(distances[now] < distance) continue //아니라면 연결되어있는 도시들 탐색 for(i in 0 until graph[now].size){ val cost = distances[now] + graph[now][i].distance //더 거리가 짧다면 업데이트 if(cost < distances[graph[now][i].index]){ distances[graph[now][i].index] = cost pq.offer(City(graph[now][i].index, cost)) } } } } dijkstra(start) val cityCount = distances.count { it != INF && it != 0 } val time = distances.maxBy { it != INF && it != 0 } println("$cityCount $time") } data class City(val index: Int, val distance: Int): Comparable<City> { override fun compareTo(other: City): Int = this.distance - other.distance }
0
Kotlin
0
0
919d6231c87fe4ee7fda6c700099e212e8da833f
1,882
algorithm
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[34]在排序数组中查找元素的第一个和最后一个位置.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 // // 如果数组中不存在目标值 target,返回 [-1, -1]。 // // 进阶: // // // 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗? // // // // // 示例 1: // // //输入:nums = [5,7,7,8,8,10], target = 8 //输出:[3,4] // // 示例 2: // // //输入:nums = [5,7,7,8,8,10], target = 6 //输出:[-1,-1] // // 示例 3: // // //输入:nums = [], target = 0 //输出:[-1,-1] // // // // 提示: // // // 0 <= nums.length <= 105 // -109 <= nums[i] <= 109 // nums 是一个非递减数组 // -109 <= target <= 109 // // Related Topics 数组 二分查找 // 👍 1052 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun searchRange(nums: IntArray, target: Int): IntArray { //二分查找 必要条件为数组必须是有序的 var left = findEqualNums(nums,target) if (left == nums.size || nums[left] != target){ return intArrayOf(-1,-1) } return intArrayOf(left,findEqualNums(nums,target+1) -1) } private fun findEqualNums(nums: IntArray, target: Int) : Int{ var left = 0 var right= nums.size while (left < right) { var mid = left + (right - left) /2 if (nums[mid] < target){ left = mid+1 }else{ //在左边 right = mid } } return left } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,696
MyLeetCode
Apache License 2.0
src/Year2022Day11.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
private class Monkey(text: String) { val itemWorryLevels: MutableList<Long> val operation: (Long) -> Long val testDivisor: Int val trueTarget: Int val falseTarget: Int var inspectTimes: Long = 0 init { val lines = text.split("\n") itemWorryLevels = lines[1].substringAfter(": ") .split(", ").map { it.toLong() }.let { ArrayDeque(it) } val operator = lines[2].substringAfter("old ").substringBefore(" ")[0] val operand = lines[2].substringAfterLast(" ") operation = when (operator) { '*' -> { old -> old * (operand.toLongOrNull() ?: old)} '+' -> { old -> old + (operand.toLongOrNull() ?: old)} else -> throw IllegalArgumentException() } testDivisor = lines[3].substringAfter("by ").toInt() trueTarget = lines[4].substringAfter("monkey ").toInt() falseTarget = lines[5].substringAfter("monkey ").toInt() } inline fun inspect(allMonkeys: List<Monkey>, worryLevelFunction: (Long) -> Long) { while (itemWorryLevels.isNotEmpty()) { inspectTimes++ val worryLevel = itemWorryLevels.removeFirst() .let(operation).let(worryLevelFunction) if (worryLevel % testDivisor == 0L) { allMonkeys[trueTarget].itemWorryLevels.add(worryLevel) } else { allMonkeys[falseTarget].itemWorryLevels.add(worryLevel) } } } } fun main() { fun part1(text: String): Long { val monkeys = text.splitToSequence("\n\n").map { Monkey(it) }.toList() repeat(20) { for (monkey in monkeys) { monkey.inspect(monkeys) { worryLevel -> worryLevel / 3 } } } return monkeys.asSequence().map { it.inspectTimes }.sortedDescending().take(2).product() } fun part2(text: String): Long { val monkeys = text.splitToSequence("\n\n").map { Monkey(it) }.toList() val mod = monkeys.asSequence().map { it.testDivisor }.lcm() repeat(10000) { for (monkey in monkeys) { monkey.inspect(monkeys) { worryLevel -> worryLevel % mod } } } return monkeys.asSequence().map { it.inspectTimes }.sortedDescending().take(2).product() } val testText = readText(true) assertEquals(10605L, part1(testText)) assertEquals(2713310158L, part2(testText)) val text = readText() println(part1(text)) println(part2(text)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
2,518
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day17.kt
pavittr
317,532,861
false
null
import java.io.File import java.nio.charset.Charset fun main() { fun part1(inputFile: String) { val input = File(inputFile).readLines(Charset.defaultCharset()) var elements = input.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '#') { Pair(Triple(x, y, 0), true) } else { Pair(Triple(x, y, 0), false) } } }.filter { it.second } var nextElements = elements.toMutableList() println(elements) println(nextElements) for (i in 1..6) { val previousElements = nextElements.toMutableList() nextElements.clear() println("Processing $i, $nextElements, $previousElements") val maxX = (previousElements.maxByOrNull { it.first.first }?.first?.first ?: 0) + 1 val minX = (previousElements.minByOrNull { it.first.first }?.first?.first ?: 0) - 1 val maxY = (previousElements.maxByOrNull { it.first.second }?.first?.second ?: 0) + 1 val minY = (previousElements.minByOrNull { it.first.second }?.first?.second ?: 0) - 1 val maxZ = (previousElements.maxByOrNull { it.first.third }?.first?.third ?: 0) + 1 val minZ = (previousElements.minByOrNull { it.first.third }?.first?.third ?: 0) - 1 println("$minX to $maxX, $minY to $maxY, $minZ to $maxZ") for (x in minX..maxX) { for (y in minY..maxY) { for (z in minZ..maxZ) { // look at the cell and get its list of neighbours val activeNeighbours = previousElements.filter { it.first.first in x - 1..x + 1 && it.first.second in y - 1..y + 1 && it.first.third in z - 1..z + 1 && (it.first.first != x || it.first.second != y || it.first.third != z) } val thisCell = previousElements.filter { it.first.first == x && it.first.second == y && it.first.third == z } .firstOrNull() ?: Pair(Triple(x, y, z), false) if (thisCell.first.first == 0 && thisCell.first.second == 1 && thisCell.first.third == -1) { println("Neighbours for $thisCell are $activeNeighbours") } if (thisCell.second && activeNeighbours.count() in 2..3) { nextElements.add(Pair(thisCell.first, true)) } else if (!thisCell.second && activeNeighbours.count() == 3) { nextElements.add(Pair(thisCell.first, true)) } } } } println("Ending $i, ${nextElements.sortedBy { it.first.third }}, $previousElements") } println(nextElements.count()) } part1("test/day17") part1("puzzles/day17") fun part2(inputFile: String) { val input = File(inputFile).readLines(Charset.defaultCharset()) var elements = input.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '#') { Cube(0, x, y, 0, true) } else { Cube(0, x, y, 0, false) } } }.filter { it.active } var nextElements = elements.toMutableList() for (i in 1..6) { val previousElements = nextElements.toMutableList() nextElements.clear() val maxW = (previousElements.maxByOrNull { it.w }?.w ?: 0) + 1 val minW = (previousElements.minByOrNull { it.w }?.w ?: 0) - 1 val maxX = (previousElements.maxByOrNull { it.x }?.x ?: 0) + 1 val minX = (previousElements.minByOrNull { it.x }?.x ?: 0) - 1 val maxY = (previousElements.maxByOrNull { it.y }?.y ?: 0) + 1 val minY = (previousElements.minByOrNull { it.y }?.y ?: 0) - 1 val maxZ = (previousElements.maxByOrNull { it.z }?.z ?: 0) + 1 val minZ = (previousElements.minByOrNull { it.z }?.z ?: 0) - 1 for (w in minW..maxW) { for (x in minX..maxX) { for (y in minY..maxY) { for (z in minZ..maxZ) { // look at the cell and get its list of neighbours val activeNeighbours = previousElements.filter { it.w in w - 1..w + 1 && it.x in x - 1..x + 1 && it.y in y - 1..y + 1 && it.z in z - 1..z + 1 && (it.w != w || it.x != x || it.y != y || it.z != z) } val thisCell = previousElements.firstOrNull { it.w == w && it.x == x && it.y == y && it.z == z } ?: Cube(w, x, y, z, false) if (thisCell.active && activeNeighbours.count() in 2..3) { nextElements.add(Cube(thisCell.w, thisCell.x, thisCell.y, thisCell.z, true)) } else if (!thisCell.active && activeNeighbours.count() == 3) { nextElements.add(Cube(thisCell.w, thisCell.x, thisCell.y, thisCell.z, true)) } } } } } } println(nextElements.count()) } part2("test/day17") part2("puzzles/day17") } class Cube(val w: Int, val x: Int, val y: Int, val z: Int, val active: Boolean) {}
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
5,926
aoc2020
Apache License 2.0
src/Day20.kt
tigerxy
575,114,927
false
{"Kotlin": 21255}
fun main() { fun part1(input: List<String>): Int { val result = input .parse() .scramble() return (1000..3000 step 1000) .map { it + result.indexOf(0) } .sumOf { result.getMod(it) } } fun part2(input: List<String>): Int = 0 val day = "20" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") val testOutput1 = part1(testInput) println("part1_test=$testOutput1") assert(testOutput1 == 3) val testOutput2 = part2(testInput) println("part2_test=$testOutput2") assert(testOutput1 == 0) val input = readInput("Day$day") println("part1=${part1(input)}") println("part2=${part2(input)}") } private fun List<Int>.scramble(): List<Int> = withIndex() .fold(withIndex()) { list, e -> val oldIdx = list.indexOfFirst { it.index == e.index } var newIdx = (oldIdx + e.value) % lastIndex newIdx = if (newIdx <= 0) lastIndex + newIdx else newIdx val newList = list.toMutableList() newList.removeAt(oldIdx) newList.add(newIdx, e) newList } .map { it.value } private fun List<String>.parse() = mapToInt() private fun List<Int>.getMod(n: Int) = get((n % size)) private fun sum(vararg int: Int) = int.sum()
0
Kotlin
0
1
d516a3b8516a37fbb261a551cffe44b939f81146
1,384
aoc-2022-in-kotlin
Apache License 2.0
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day07.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.days.Day class Day07 : Day(title = "The Sum of Its Parts") { private companion object { private val PARSE_INDICES = listOf(5, 36) private const val WORKER_AMOUNT = 5 } override fun first(input: Sequence<String>): Any = input.parse().determineSteps() override fun second(input: Sequence<String>): Any = input.parse().calculateTimeTaken() private tailrec fun Instructions.determineSteps( accumulator: MutableList<Char> = mutableListOf() ): String = if (accumulator.size == allInstructions.size) accumulator.joinToString("") else determineSteps(accumulator.apply { this += allInstructions.first { a -> a.isProcessable(accumulator, requirements) } }) private tailrec fun Instructions.calculateTimeTaken( accumulator: MutableList<Char> = mutableListOf(), workingOnUntil: MutableMap<Int, MutableList<Char>> = mutableMapOf(), currentSecond: Int = 0 ): Int { workingOnUntil.remove(currentSecond)?.let { accumulator += it.sorted() } val currentlyProcessed = workingOnUntil.values.flatten() allInstructions .asSequence() .filter { it !in currentlyProcessed && it.isProcessable(accumulator, requirements) } .sorted() .take(WORKER_AMOUNT - currentlyProcessed.size) .forEach { workingOnUntil.getOrPut(currentSecond + (it - 'A' + 61)) { mutableListOf() } += it } return if (accumulator.size == allInstructions.size) currentSecond else calculateTimeTaken(accumulator, workingOnUntil, currentSecond + 1) } private fun Sequence<String>.parse() = this .map { it.toCharArray().slice(PARSE_INDICES) } .let { instruction -> Instructions( instruction.flatten().toSortedSet(), instruction.groupBy({ (_, step) -> step }) { (req, _) -> req } ) } private fun Char.isProcessable( accumulator: List<Char>, requirements: Map<Char, List<Char>> ) = this !in accumulator && requirements[this]?.all { it in accumulator } ?: true private data class Instructions( val allInstructions: Set<Char>, val requirements: Map<Char, List<Char>> ) }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,381
AdventOfCode
MIT License
src/main/kotlin/day13/Day13.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day13 import groupByBlanks import mapGroups import runDay fun main() { fun part1(input: List<String>) = input.groupByBlanks() .mapGroups { it.toPacket() } .mapIndexed { index, packets -> (index + 1) to packets.first().compareTo(packets.last()) }.filter { (_, comparison) -> comparison <= 0 } .sumOf { (index) -> index } fun part2(input: List<String>) = input.groupByBlanks() .mapGroups { it.toPacket() } .flatten() .let { it + listOf( "[[2]]".toPacket(), "[[6]]".toPacket(), ) } .sorted() .mapIndexed { index, it -> index to it.toString() } .filter { (_, it) -> it in listOf( "[[2]]", "[[6]]", ) }.map { (index) -> index + 1} .fold(1) { acc, next -> acc * next } (object {}).runDay( part1 = ::part1, part1Check = 13, part2 = ::part2, part2Check = 140, ) } fun String.toPacket(): PacketData { val stack = ArrayDeque<MutableList<PacketData>>() var current = mutableListOf<PacketData>() var num = "" for (char in this) { when (char) { '[' -> { stack.addFirst(current) current = mutableListOf() } ']' -> { if (num.isNotBlank()) { current.add(IntData(num.toInt())) num = "" } val next = ListData(current) current = stack.removeFirst() current.add(next) } ',' -> { if (num.isNotBlank()) { current.add(IntData(num.toInt())) num = "" } } else -> num += char } } return current.first() } sealed interface PacketData : Comparable<PacketData> { override operator fun compareTo(other: PacketData): Int } @JvmInline value class ListData(val data: List<PacketData>) : PacketData { constructor(vararg values: PacketData) : this(values.toList()) override operator fun compareTo(other: PacketData): Int = when (other) { is IntData -> this.compareTo(ListData(other)) is ListData -> this.data.zip(other.data) .fold(0) { _, (left, right) -> val comparison = left.compareTo(right) if (comparison != 0) return comparison 0 }.let { comparison -> when (comparison) { 0 -> this.data.size.compareTo(other.data.size) else -> comparison } } } override fun toString(): String = data.joinToString( prefix = "[", postfix = "]", separator = ",", ) } @JvmInline value class IntData(val data: Int) : PacketData { override operator fun compareTo(other: PacketData): Int = when (other) { is IntData -> this.data.compareTo(other.data) is ListData -> ListData(this).compareTo(other) } override fun toString(): String = data.toString() }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
3,192
advent-of-code-2022
Apache License 2.0
src/day01/Day01.kt
Frank112
572,910,492
false
null
package day01 import readInput fun main() { fun computeCarriedFoodByElf(input: List<String>): List<Int> { val carriedFoodByElfs = mutableListOf<Int>() var carriedFoodByElf = 0 for (s in input) { if(s.isBlank()) { carriedFoodByElfs.add(carriedFoodByElf) carriedFoodByElf = 0 } else { carriedFoodByElf += s.toInt() } } carriedFoodByElfs.add(carriedFoodByElf) return carriedFoodByElfs } fun part1(carriedFoodByElfs: List<Int>): Int { return carriedFoodByElfs.max() } fun part2(carriedFoodByElfs: List<Int>): Int { return carriedFoodByElfs.sortedDescending().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = computeCarriedFoodByElf(readInput("day01/Day01_test")) val testResult1 = part1(testInput) val testResult2 = part2(testInput) check(testResult1 == 24000) { "Got ${testResult1} but expected 24000" } check(testResult2 == 45000) { "Got ${testResult2} but expected 45000" } val input = computeCarriedFoodByElf(readInput("day01/Day01")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1e927c95191a154efc0fe91a7b89d8ff526125eb
1,254
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinReorder.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.abs /** * 1466. Reorder Routes to Make All Paths Lead to the City Zero * @see <a href="https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero"> * Source</a> */ fun interface MinReorder { operator fun invoke(n: Int, connections: Array<IntArray>): Int } class MinReorderDFS : MinReorder { override operator fun invoke(n: Int, connections: Array<IntArray>): Int { val al: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) al.add(ArrayList()) for (c in connections) { al[c[0]].add(c[1]) al[c[1]].add(-c[0]) } return dfs(al, BooleanArray(n), 0) } private fun dfs(al: List<List<Int>>, visited: BooleanArray, from: Int): Int { var change = 0 visited[from] = true for (to in al[from]) { if (!visited[abs(to)]) change += dfs(al, visited, abs(to)) + if (to > 0) 1 else 0 } return change } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,634
kotlab
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2022/day22/Day22.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day22 import com.jacobhyphenated.advent2022.Day typealias Board = Map<Pair<Int,Int>, Tile> /** * Day 22: Monkey Map * * You are given an irregularly shaped map in a 2d grid * The map contains '.' for empty space, and '#' for walls. * empty space means the map should wrap around. * * You also have instructions that involve moving forward and rotating the direction you are facing. */ class Day22: Day<Pair<Board, List<Instruction>>> { override fun getInput(): Pair<Board, List<Instruction>> { return parseInput(readInputFile("day22")) } /** * Follow the instructions. When the map wraps around, * stay in the same row or column you are moving through, but find * the first non-empty space of the opposite side. * * To determine the solution, you need the row and column (1 based) * and the facing (0: right, 1: down, 2: left, 3: up). * return the sum of 1000 times the row, 4 times the column, and the facing */ override fun part1(input: Pair<Board, List<Instruction>>): Int { return followInstructions(input, false) } /** * The irregularly shaped map is actually a cube. You need to fold the different sides to make a cube. * Wrap arounds continue onto the adjacent cube face. * Note: this may change the facing direction in 2d space. */ override fun part2(input: Pair<Board, List<Instruction>>): Int { return followInstructions(input, true) } /** * The instruction engine for parts 1 and 2 is the same except for how we calculate wrap around spaces. */ private fun followInstructions(input: Pair<Board, List<Instruction>>, isCube: Boolean): Int { var inspect = Pair(0,0) val (b, instructions) = input val board = b.withDefault { Tile.EMPTY } while (board[inspect] != Tile.OPEN) { inspect = Pair(0, inspect.second + 1) } var currentLocation = inspect var facing = Facing.RIGHT val maxR = board.keys.maxOf { (r,_) -> r } val maxC = board.keys.maxOf { (_,c) -> c } instructions.forEach { instruction -> if (instruction.turn != null) { facing = facing.turn(instruction.turn) } else { var move = instruction.move!! while (move > 0) { val (r,c) = currentLocation val next = when(facing) { Facing.UP -> Pair(r-1, c) Facing.RIGHT -> Pair(r, c+1) Facing.DOWN -> Pair(r+1, c) Facing.LEFT -> Pair(r, c-1) } if (board[next] == Tile.OPEN) { currentLocation = next } else if (board[next] == Tile.WALL) { // stop when we hit a wall break } else { // empty space - we need to wrap around val (oppositeEdge, direction) = if (!isCube) { findLinearWrapAround(currentLocation, facing, maxR, maxC, board) } else { findCubeWrapAround(currentLocation, facing, maxR, maxC) } if (board[oppositeEdge] == Tile.WALL) { // If the wrap around space is a wall, don't wrap around, stop moving. break } else { currentLocation = oppositeEdge facing = direction } } move-- } } } return (currentLocation.first + 1) * 1000 + (currentLocation.second + 1) * 4 + facing.value } /** * To calculate linear wrap around spaces, go in the opposite direction until we find an empty tile. * That last valid space is our wrap around tile. */ private fun findLinearWrapAround(current: Pair<Int,Int>, facing: Facing, maxR: Int, maxC: Int, board: Board): Pair<Pair<Int,Int>, Facing> { val (r,c) = current val wrapAroundSearch = when (facing) { Facing.RIGHT -> (c downTo 0).map { Pair(r,it) } Facing.DOWN -> (r downTo 0).map { Pair(it, c) } Facing.LEFT -> (c .. maxC).map { Pair(r, it) } Facing.UP -> (r .. maxR).map { Pair(it, c) } } val oppositeEdge = wrapAroundSearch.takeWhile { board.getValue(it) != Tile.EMPTY }.last() return Pair(oppositeEdge, facing) } /** Solve the cube wrap around specifically for this puzzle input by splitting into 6 quadrant sides of the cube: Folding the Cube Shaped like: 21 3 54 6 1 bottom <-> 3 right 1 top <-> 6 bottom 1 right <-> 4 right 2 top <-> 6 left 2 left <-> 5 left 3 left <-> 5 top 4 bottom <-> 6 right Note: I cut out a piece of paper and folded it to figure out how these fit together */ private fun findCubeWrapAround(current: Pair<Int,Int>, facing: Facing, maxR: Int, maxC: Int): Pair<Pair<Int,Int>, Facing> { val sideLength = 50 // hardcoded to puzzle input val (r,c) = current val quadrant = if (r < sideLength) { if (c < sideLength * 2) { 2 } else { 1 } } else if (r < sideLength * 2) { 3 } else if (r < sideLength * 3) { if (c < sideLength ) { 5 } else { 4 } } else { 6 } return when (quadrant) { 1 -> when (facing) { Facing.UP -> Pair(Pair(maxR, c % sideLength), Facing.UP) Facing.RIGHT -> Pair(Pair(maxR - sideLength - r, c - sideLength), Facing.LEFT) Facing.DOWN -> Pair(Pair(c - sideLength, maxC - sideLength), Facing.LEFT) else -> throw IllegalStateException("Quadrant 1") } 2 -> when (facing) { Facing.UP -> Pair(Pair(c + sideLength * 2,0), Facing.RIGHT) Facing.LEFT -> Pair(Pair(maxR - sideLength - r,0), Facing.RIGHT) else -> throw IllegalStateException("Quadrant 2") } 3 -> when (facing) { Facing.RIGHT -> Pair(Pair(sideLength - 1, r + sideLength), Facing.UP) Facing.LEFT -> Pair(Pair(sideLength * 2, r - sideLength), Facing.DOWN) else -> throw IllegalStateException("Quadrant 3") } 4 -> when (facing) { Facing.RIGHT -> Pair(Pair(maxR - sideLength - r, maxC), Facing.LEFT) Facing. DOWN -> Pair(Pair(c + sideLength * 2, sideLength - 1), Facing.LEFT) else -> throw IllegalStateException("Quadrant 4") } 5 -> when (facing) { Facing.UP -> Pair(Pair(c + sideLength, sideLength), Facing.RIGHT) Facing.LEFT -> Pair(Pair(maxR - sideLength - r, sideLength), Facing.RIGHT) else -> throw IllegalStateException("Quadrant 5") } 6 -> when (facing) { Facing.LEFT -> Pair(Pair(0, r - sideLength * 2), Facing.DOWN) Facing.RIGHT -> Pair(Pair(maxR - sideLength, r - sideLength * 2), Facing.UP) Facing.DOWN -> Pair(Pair(0, c + sideLength * 2), Facing.DOWN) else -> throw IllegalStateException("Quadrant 6") } else -> throw IllegalStateException("Invalid Quadrant $quadrant") } } fun parseInput(input: String): Pair<Board, List<Instruction>> { val (boardInput, instructionInput) = input.split("\n\n") val board = mutableMapOf<Pair<Int,Int>, Tile>() boardInput.lines().forEachIndexed { row, line -> line.toList().forEachIndexed { col, c -> val tile = when(c) { ' ' -> Tile.EMPTY '.' -> Tile.OPEN '#' -> Tile.WALL else -> throw NotImplementedError("Invalid board character $c") } board[Pair(row,col)] = tile } } val instructions = mutableListOf<Instruction>() var buffer = "" for (c in instructionInput) { if (c == 'R' || c == 'L') { if (buffer.isNotEmpty()) { instructions.add(Instruction(move = buffer.toInt())) buffer = "" } val turn = when (c) { 'R' -> Turn.RIGHT 'L' -> Turn.LEFT else -> throw NotImplementedError("Invalid instruction character $c") } instructions.add(Instruction(turn = turn)) } else { buffer += c } } if (buffer.isNotEmpty()) { instructions.add(Instruction(move = buffer.toInt())) } return Pair(board, instructions) } } enum class Facing(val value: Int) { RIGHT(0), DOWN(1), LEFT(2), UP(3); fun turn(turnDirection: Turn): Facing { val right = Turn.RIGHT == turnDirection return when (this) { RIGHT -> if (right) { DOWN } else { UP } DOWN -> if (right) { LEFT } else { RIGHT } LEFT -> if (right) { UP } else { DOWN } UP -> if (right) { RIGHT } else { LEFT } } } } enum class Turn { RIGHT, LEFT } enum class Tile { EMPTY, OPEN, WALL } class Instruction(val move: Int? = null, val turn: Turn? = null)
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
9,753
advent2022
The Unlicense
src/Day04.kt
sabercon
648,989,596
false
null
fun main() { fun hasRequiredKeys(passport: Map<String, String>): Boolean { return passport.keys.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")) } fun hasValidValues(passport: Map<String, String>): Boolean { return passport.all { (k, v) -> when (k) { "byr" -> v.toInt() in 1920..2002 "iyr" -> v.toInt() in 2010..2020 "eyr" -> v.toInt() in 2020..2030 "hgt" -> when { v.endsWith("cm") -> v.dropLast(2).toInt() in 150..193 v.endsWith("in") -> v.dropLast(2).toInt() in 59..76 else -> false } "hcl" -> v.matches(Regex("#[0-9a-f]{6}")) "ecl" -> v in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") "pid" -> v.matches(Regex("[0-9]{9}")) else -> true } } } val input = readText("Day04") .split("\n\n") .map { it.split(' ', '\n').associate { kv -> val (k, v) = kv.split(':') k to v } } input.count { hasRequiredKeys(it) }.println() input.count { hasRequiredKeys(it) && hasValidValues(it) }.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
1,285
advent-of-code-2020
MIT License
src/Day25.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
import kotlin.math.ceil import kotlin.math.pow import kotlin.math.floor import kotlin.math.log fun main() { fun snafuToDecimal(num: String): Long { var power = 1L var answer = 0L for (digit in num.trim().reversed()) { answer += when (digit) { '=' -> power * -2 '-' -> -power '0' -> 0 '1' -> power '2' -> power * 2 else -> throw NumberFormatException("\"$num\" is not SNAFU") } power *= 5 } return answer } fun decimalToSnafu(num: Long): String { val map = arrayOf('=', '-', '0', '1', '2') var residue = num var output = ArrayDeque<Char>() while (residue > 0) { residue += 2 output.addFirst(map[(residue % 5).toInt()]) residue /= 5 } return String(output.toCharArray()) } fun Long.toSnafu(): String { return decimalToSnafu(this) } fun part1(input: List<String>): String { return input.sumOf { snafuToDecimal(it) }.toSnafu() } fun part2(input: List<String>): String { return "total_score" } // test if implementation meets criteria from the description, like: val testInput = listOf( "1=-0-2\n", "12111\n", "2=0=\n", "21\n", "2=01\n", "111\n", "20012\n", "112\n", "1=-1=\n", "1-12\n", "12\n", "1=\n", "122\n", ) check(part1(testInput) == "2=-1=0") val input = readInput("day25") println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
1,686
2022-aoc-kotlin
Apache License 2.0
2023/src/main/kotlin/Day17.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import java.util.PriorityQueue object Day17 { fun part1(input: String) = solve(input, 0, 3) fun part2(input: String) = solve(input, 4, 10) private enum class Direction { NORTH, EAST, SOUTH, WEST } private data class Pos(val x: Int, val y: Int) private data class Crucible(val direction: Direction, val pos: Pos, val straightCount: Int) private data class State(val crucible: Crucible, val heat: Int) private fun solve(input: String, minStraightCount: Int, maxStraightCount: Int): Int { val city = input.splitNewlines().map { it.toCharArray().toIntList().toTypedArray() }.toTypedArray() val minimumHeat = mutableMapOf<Crucible, Int>() // We prioritize reaching the end so we can cut off branching ASAP val queue = PriorityQueue<State> { s1, s2 -> s1.heat - s2.heat } queue.addAll( listOf( State(Crucible(Direction.EAST, Pos(0, 0), 0), 0), State(Crucible(Direction.SOUTH, Pos(0, 0), 0), 0) ) ) fun addMoveToQueueIfInBounds(curr: State, direction: Direction) { val newPos = curr.crucible.pos.move(direction) if (newPos.x in city[0].indices && newPos.y in city.indices) { val newStraightCount = if (curr.crucible.direction == direction) curr.crucible.straightCount + 1 else 0 queue.add( State( curr.crucible.copy(direction = direction, pos = newPos, straightCount = newStraightCount), curr.heat + city[newPos.y][newPos.x] ) ) } } val endPos = Pos(city[0].size - 1, city.size - 1) while (queue.isNotEmpty()) { val curr = queue.poll() // Check if we've found the answer if (curr.crucible.pos == endPos && curr.crucible.straightCount >= minStraightCount - 1) { return curr.heat } // Have we been here before, but better? val best = minimumHeat[curr.crucible] if (best != null && best <= curr.heat) { continue } // We record every possible straight count that could've gotten here, since the lowest one is strictly better // (EXCEPT we skip it if we need a minimum amount of moves to do anything interesting) minimumHeat[curr.crucible] = curr.heat if (curr.crucible.straightCount >= minStraightCount) { (curr.crucible.straightCount + 1..maxStraightCount).forEach { minimumHeat[curr.crucible.copy(straightCount = it)] = curr.heat } } // Try turning left and right if (curr.crucible.straightCount >= minStraightCount - 1) { if (curr.crucible.direction == Direction.NORTH || curr.crucible.direction == Direction.SOUTH) { addMoveToQueueIfInBounds(curr, Direction.EAST) addMoveToQueueIfInBounds(curr, Direction.WEST) } else { addMoveToQueueIfInBounds(curr, Direction.NORTH) addMoveToQueueIfInBounds(curr, Direction.SOUTH) } } // Try going straight if (curr.crucible.straightCount < maxStraightCount - 1) { addMoveToQueueIfInBounds(curr, curr.crucible.direction) } } throw IllegalStateException("Didn't find path from start to end!") } private fun Pos.move(direction: Direction): Pos { return when (direction) { Direction.NORTH -> copy(y = y - 1) Direction.EAST -> copy(x = x + 1) Direction.SOUTH -> copy(y = y + 1) Direction.WEST -> copy(x = x - 1) } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
3,413
advent-of-code
MIT License
src/day02/Day02.kt
S-Flavius
573,063,719
false
{"Kotlin": 6843}
package day02 import readInput fun main() { fun part1(input: List<String>): Int { var curScore = 0 for (line in input) { val values = line.split(" ") when { values[1] == "X" -> { curScore += 1 when { values[0] == "A" -> curScore += 3 values[0] == "C" -> curScore += 6 } } values[1] == "Y" -> { curScore += 2 when { values[0] == "A" -> curScore += 6 values[0] == "B" -> curScore += 3 } } values[1] == "Z" -> { curScore += 3 when { values[0] == "B" -> curScore += 6 values[0] == "C" -> curScore += 3 } } } } return curScore } fun part2(input: List<String>): Int { var curScore = 0 for (line in input) { val values = line.split(" ") when { values[1] == "X" -> { when { values[0] == "A" -> curScore += 3 values[0] == "B" -> curScore += 1 values[0] == "C" -> curScore += 2 } } values[1] == "Y" -> { when { values[0] == "A" -> curScore += 4 values[0] == "B" -> curScore += 5 values[0] == "C" -> curScore += 6 } } values[1] == "Z" -> { when { values[0] == "A" -> curScore += 8 values[0] == "B" -> curScore += 9 values[0] == "C" -> curScore += 7 } } } } return curScore } // test if implementation meets criteria from the description, like: val testInput = readInput("day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02/Day02") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
47ce29125ff6071edbb07ae725ac0b9d672c5356
2,398
AoC-Kotlin-2022
Apache License 2.0
day05/Kotlin/day05.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* import kotlin.math.abs fun print_day_5() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 5" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Hydrothermal Venture -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_5() Day5().puzzle1() Day5().puzzle2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day5 { data class Point(val x:Int, val y: Int) private val lines = File("../Input/day5.txt").readLines() private val points = lines.map { line -> line.split(" -> ").map { point -> val pairs = point.split(",") Point(pairs[0].toInt(), pairs[1].toInt()) } } fun puzzle1() { val map2d = Array(1000) { Array(1000) { 0 } } points.forEach() { if (it[0].x == it[1].x) { val min = Math.min(it[0].y, it[1].y) val max = Math.max(it[0].y, it[1].y) for(i in min..max) { map2d[i][it[0].x]++ } } else if (it[0].y == it[1].y) { val min = Math.min(it[0].x, it[1].x) val max = Math.max(it[0].x, it[1].x) for(i in min..max) { map2d[it[0].y][i]++ } } } val overlaps = map2d.sumOf { it.count { point -> point >= 2 } } println("Puzzle 1: " + overlaps) } fun puzzle2() { val map2d = Array(1000) { Array(1000) { 0 } } points.forEach() { if (it[0].x == it[1].x) { val min = Math.min(it[0].y, it[1].y) val max = Math.max(it[0].y, it[1].y) for(i in min..max) { map2d[i][it[0].x]++ } } else if (it[0].y == it[1].y) { val min = Math.min(it[0].x, it[1].x) val max = Math.max(it[0].x, it[1].x) for(i in min..max) { map2d[it[0].y][i]++ } } else if ( isDiagonal(it[0], it[1]) ) { val len = abs(it[0].x - it[1].x) val xStep = if (it[1].x - it[0].x > 0) 1 else -1 val yStep = if (it[1].y - it[0].y > 0) 1 else -1 for(i in 0..len) { val y = it[0].y + (i*yStep) val x = it[0].x + (i*xStep) map2d[y][x]++ } } } val overlaps = map2d.sumOf { it.count { point -> point >= 2 } } println("Puzzle 2: " + overlaps) } private fun isDiagonal(p1: Point, p2: Point): Boolean = abs(p1.x - p2.x) == abs(p1.y - p2.y) }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
3,049
AOC2021
Apache License 2.0
src/main/kotlin/aoc2017/day02_corruption_checksum/CorruptionChecksum.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2017.day02_corruption_checksum fun main() { util.solve(53978, ::partOne) util.solve(314, ::partTwo) } private val RE_RUN_OF_SPACES = Regex("\\s+") private fun checksum(spreadsheet: String, rowChecksum: (List<Int>) -> Int) = spreadsheet .lines() .sumOf { rowChecksum( it.split(RE_RUN_OF_SPACES) .map(Integer::parseInt) ) } fun partOne(input: String) = checksum(input) { val (min, max) = it.fold( Pair(Int.MAX_VALUE, Int.MIN_VALUE) ) { (min, max), n -> Pair(min.coerceAtMost(n), max.coerceAtLeast(n)) } max - min } fun partTwo(input: String) = checksum(input) { numbers -> numbers.forEachIndexed { i, a -> numbers.subList(0, i).forEach { b -> if (a > b) { if (a % b == 0) return@checksum a / b } else { if (b % a == 0) return@checksum b / a } } } throw IllegalStateException("no divisible numbers?!") }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
1,121
aoc-2021
MIT License
src/day02/Day02.kt
mherda64
512,106,270
false
{"Kotlin": 10058}
package day02 import readInput fun main() { data class Operation(val direction: String, val amount: Int) fun part1(input: List<String>): Int { var position = 0; var depth = 0; input.map { it.split(" ") } .map { Operation(it[0], it[1].toInt()) } .forEach { (direction, amount) -> when (direction) { "forward" -> position += amount "down" -> depth += amount "up" -> depth -= amount } } return position * depth } fun part2(input: List<String>): Int { var position = 0 var depth = 0 var aim = 0 input.map { it.split(" ") } .map { Operation(it[0], it[1].toInt()) } .forEach { (direction, amount) -> when (direction) { "forward" -> { position += amount depth += amount * aim } "down" -> aim += amount "up" -> aim -= amount } } return position * depth } val testInput = readInput("Day02_test") check(part1(testInput) == 150) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d04e179f30ad6468b489d2f094d6973b3556de1d
1,337
AoC2021_kotlin
Apache License 2.0
src/Day13.kt
felldo
572,233,925
false
{"Kotlin": 76496}
fun main() { fun addToList(a: String, elements: MutableList<String>) { var str = a while (str != "") { if (str[0] != '[') { elements.add(str.substringBefore(",")) str = if (!str.contains(',')) "" else str.substringAfter(",") } else { var i = 1 var brackets = 1 while (brackets > 0 && i < str.length) { brackets += when (str[i]) { '[' -> 1 ']' -> -1 else -> 0 } i++ } elements.add(str.substring(0, i)) str = str.substring(i) } } } fun listCompare(a: String, b: String): Boolean? { var at = a var bt = b if (a.toIntOrNull() != null && b.toIntOrNull() != null) { if (a.toInt() < b.toInt()) return true if (a.toInt() > b.toInt()) return false return null } if (a.toIntOrNull() == null && b.toIntOrNull() != null) { bt = "[$b]" } if (a.toIntOrNull() != null && b.toIntOrNull() == null) { at = "[$a]" } if (a == "" && b != "") return false if (a != "" && b == "") return true if (a == "") return null val aElements = mutableListOf<String>() val bElements = mutableListOf<String>() at = at.substring(1, at.length - 1) bt = bt.substring(1, bt.length - 1) addToList(at, aElements) addToList(bt, bElements) aElements.remove("") bElements.remove("") while (aElements.isNotEmpty() && bElements.isNotEmpty()) { val comp = listCompare(aElements.removeFirst(), bElements.removeFirst()) if (comp != null) return comp } if (aElements.isEmpty() && bElements.isNotEmpty()) { return true } if (aElements.isNotEmpty()) { return false } return null } fun part1(input: List<List<String>>) = input.mapIndexed { index, list -> if (listCompare(list[0], list[1]) == true) index + 1 else 0 }.sum() fun part2(input: List<List<String>>): Int { val cleanInput = mutableListOf<String>() for (i in input) { for (j in i) { cleanInput.add(j) } } cleanInput.add("[[2]]") cleanInput.add("[[6]]") cleanInput.sortWith { a, b -> when (listCompare(a, b)) { true -> -1 false -> 1 else -> 0 } } return (cleanInput.indexOf("[[2]]") + 1) * (cleanInput.indexOf("[[6]]") + 1) } val input = readInputSpaceDelimited("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
2,986
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
fun main() { val lowercase = 'a'..'z' val uppercase = 'A'..'Z' fun part1(input: List<String>): Int { var score = 0 for (line in input) { val left = line.substring(0 until line.length / 2).toCharArray().toSet() val right = line.substring(line.length / 2 until line.length).toCharArray().toSet() for (c in left) { if (c in right) { score += if (c in lowercase) lowercase.indexOf(c) + 1 else 0 score += if (c in uppercase) uppercase.indexOf(c) + 27 else 0 } } } return score } fun part2(input: List<String>): Int { var score = 0 for (i in input.indices step 3) { val top = input[i].toCharArray().toSet() val mid = input[i + 1].toCharArray().toSet() val bot = input[i + 2].toCharArray().toSet() for (c in top) { if (c in mid && c in bot) { score += if (c in lowercase) lowercase.indexOf(c) + 1 else 0 score += if (c in uppercase) uppercase.indexOf(c) + 27 else 0 } } } return score } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
1,312
Advent-Of-Code-2022
Apache License 2.0
LeetCode/Kotlin/MaxIncreaseKeepingSkyline.kt
vale-c
177,558,551
false
null
/** * 807. Max Increase to Keep City Skyline * https://leetcode.com/problems/max-increase-to-keep-city-skyline/ */ class MaxIncreaseKeepingSkyline { fun maxIncreaseKeepingSkyline(grid: Array<IntArray>): Int { val maxPerLineAndColumn: Pair<List<Int>, List<Int>> = getMaxPerLineAndColumn(grid) val lineMax = maxPerLineAndColumn.first val columnMax = maxPerLineAndColumn.second var increasedHeightSum = 0 grid.forEachIndexed { lineIndex, line -> line.forEachIndexed { columnIndex, currentHeight -> val increasedHeight = Math.min(lineMax[lineIndex], columnMax[columnIndex]) increasedHeightSum += increasedHeight - currentHeight } } return increasedHeightSum } private fun getMaxPerLineAndColumn(grid: Array<IntArray>): Pair<List<Int>, List<Int>> { val lineMax = MutableList(grid.size) {-1} val columnMax = MutableList(grid.size) {-1} grid.forEachIndexed{ lineIndex, line -> line.forEachIndexed{ columnIndex, height -> lineMax[lineIndex] = Math.max(lineMax[lineIndex], height) columnMax[columnIndex] = Math.max(columnMax[columnIndex], height) } } return Pair(lineMax, columnMax) } }
0
Java
5
9
977e232fa334a3f065b0122f94bd44f18a152078
1,314
CodingInterviewProblems
MIT License
src/main/kotlin/com/londogard/fuzzymatch/FuzzyMatcher.kt
londogard
225,202,364
false
null
package com.londogard.fuzzymatch import kotlin.math.min class FuzzyMatcher(private val scoreConfig: ScoreConfig = ScoreConfig()) { data class Result(val indices: List<Int>, val score: Int, val text: String? = null) private data class DataHolder(val textLeft: String, val matches: List<Int>, val recursiveResults: List<Result>) private val emptyResult = Result(emptyList(), 0) /** * Returns true if each character in pattern is found sequentially within text. ~3 times faster than contains * @param pattern String - the pattern to be found * @param text String - the text where we want to find the pattern */ fun fuzzyMatchSimple(pattern: String, text: String): Boolean { //text.contains() var patternIdx = 0 var textIdx = 0 val patternLen = pattern.length val textLen = text.length while (patternIdx != patternLen && textIdx != textLen) { if (pattern[patternIdx].toLowerCase() == text[textIdx].toLowerCase()) ++patternIdx ++textIdx } return patternLen != 0 && textLen != 0 && patternIdx == patternLen } /** * A fuzzy match, finds all possible matches and retrieves the optimal solution using ScoringConfig. * Currently only returns if full match. Else empty result returned. * * @param text: the text input * @param pattern: the pattern we want to match to the text * @param res: recursion param (ignore it) * @param textLen: recursion param (ignore it) * @param fullText: recursion param (ignore it) */ private fun fuzzyMatchFunc( text: String, pattern: String, res: Result = emptyResult, textLen: Int = text.length, fullText: String = text ): Result { return when { pattern.length > text.length || text.isEmpty() -> emptyResult pattern.isEmpty() -> res else -> { val recursiveParams = pattern.foldIndexed( DataHolder( text, res.indices, emptyList() ) ) { index, (textLeft, matches, recursiveRes), patternChar -> when { textLeft.isEmpty() -> return emptyResult patternChar.equals(textLeft[0], true) -> { val recursiveResult = fuzzyMatchFunc( textLeft.drop(1), pattern.substring(index), res.copy(indices = matches), textLen, fullText ) DataHolder( textLeft.drop(1), matches + (textLen - textLeft.length), recursiveRes + recursiveResult ) } else -> { val updatedText = textLeft.dropWhile { !it.equals(patternChar, true) } if (updatedText.isEmpty()) return emptyResult val recursiveResult = fuzzyMatchFunc( updatedText.drop(1), pattern.substring(index), res.copy(indices = matches), textLen, fullText ) DataHolder( updatedText.drop(1), matches + (textLen - updatedText.length), recursiveRes + recursiveResult ) } } } val results = recursiveParams.recursiveResults + Result(recursiveParams.matches, 10) if (recursiveParams.matches.size != pattern.length) emptyResult else results.filter { it.score > 0 }.map { Result( it.indices, scoringFunction(it.indices, fullText) ) }.maxBy { it.score }?.copy(text = fullText)!! } } } /** * Fuzzy match pattern on a collection of texts. Returns the topN results (scoring by ScoreConfig). * @param texts: The collection of texts. * @param pattern: The pattern to match on the texts * @param topN: Number of results to return */ fun fuzzyMatch(texts: List<String>, pattern: String, topN: Int = 20): List<Result> = if (pattern.length == 1) texts.asSequence() .filter { it.contains(pattern) } .take(topN) .map { match -> Result(listOf(match.indexOf(pattern)), scoreConfig.firstLetterMatch, match) } .toList() else texts .map { fuzzyMatchFunc(it, pattern) } .filter { it.score > 0 } .sortedByDescending { it.score } .take(topN) private fun scoringFunction(indices: List<Int>, text: String): Int { return listOf( min(3, indices[0]) * scoreConfig.unmatchedLeadingLetter, indices.windowed(2).map { indexWindow -> val firstLetter = if (indexWindow.first() == 0) scoreConfig.firstLetterMatch else 0 val consecutive = if (indexWindow.first() == indexWindow.last() - 1) scoreConfig.consecutiveMatch else 0 val neighbour = text[indexWindow.first()] val camelCase = if (neighbour.isLowerCase() && text[indexWindow.last()].isUpperCase()) scoreConfig.camelCaseMatch else 0 val separator = if (neighbour == ' ' || neighbour == '_') scoreConfig.separatorMatch else 0 val unmatched = (indices.lastOrNull() ?: text.length) * scoreConfig.unmatchedLetter firstLetter + consecutive + camelCase + separator + unmatched }.sum() ).sum() } }
1
Kotlin
0
2
f6df4d4ef699e3af5d857bba100fecce2c7fd879
6,159
fuzzy-match-kt
Apache License 2.0
algorithms/src/main/kotlin/com/kotlinground/algorithms/sorting/mergesort/mergesort.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.algorithms.sorting.mergesort private fun combineSortedArrays(arrayOne: IntArray, arrayTwo: IntArray): IntArray { var arrayOneIndex = 0 var arrayTwoIndex = 0 var mergedArrayIndex = 0 val mergedArray = IntArray(arrayOne.size + arrayTwo.size) // both arrays have some items left in them. while (arrayOneIndex < arrayOne.size && arrayTwoIndex < arrayTwo.size) { // choose the smaller of the two items and add it to the // merged array. if (arrayOne[arrayOneIndex] <= arrayTwo[arrayTwoIndex]) { mergedArray[mergedArrayIndex] = arrayOne[arrayOneIndex] arrayOneIndex += 1 } else { mergedArray[mergedArrayIndex] = arrayTwo[arrayTwoIndex] arrayTwoIndex += 1 } mergedArrayIndex += 1 } // grab any lingering items in the first array after we've // exhausted the second array while (arrayOneIndex < arrayOne.size) { mergedArray[mergedArrayIndex] = arrayOne[arrayOneIndex] mergedArrayIndex += 1 arrayOneIndex += 1 } // grab any lingering items in the second array after we've // exhausted the first array while (arrayTwoIndex < arrayTwo.size) { mergedArray[mergedArrayIndex] = arrayTwo[arrayTwoIndex] mergedArrayIndex += 1 arrayTwoIndex += 1 } return mergedArray } fun mergeSort(theArray: IntArray): IntArray { // base case: single element array if (theArray.size <= 1) { return theArray } // split the input in half val middleIndex = theArray.size / 2 val left: IntArray = theArray.copyOfRange(0, middleIndex) val right: IntArray = theArray.copyOfRange(middleIndex, theArray.size) // sort each half val leftSorted = mergeSort(left) val rightSorted = mergeSort(right) // merge the sorted halves return combineSortedArrays(leftSorted, rightSorted) }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,936
KotlinGround
MIT License
src/main/kotlin/de/soerenhenning/mimwidth/ExactMimCalculator.kt
SoerenHenning
107,282,322
false
{"Kotlin": 47246}
package de.soerenhenning.mimwidth import com.google.common.graph.Graph import de.soerenhenning.mimwidth.graphs.createCut class ExactMimCalculator<T>(private val graph: Graph<T>, private val treeDecomposition: TreeDecomposition<T>) { fun compute(): TreeDecomposition<T> { val tree = treeDecomposition.tree val cutMimValues = HashMap<Set<T>, Int>(treeDecomposition.cutMimValues.size) for(edge in tree.edges()) { val child = edge.asSequence().minBy { it.size } ?: emptySet() val cut = graph.createCut(child) val exactMim = computeMim(cut) cutMimValues[child] = exactMim } return TreeDecomposition(tree, cutMimValues) } private fun computeMim(graph: Graph<T>): Int { return when { isMimEqualsZero(graph) -> 0 !isMimGreaterOne(graph) -> 1 !isMimGreaterTwo(graph) -> 2 else -> Int.MAX_VALUE } } private fun isMimEqualsZero(graph: Graph<T>): Boolean { // MIM == 0 <=> No edge exists return graph.edges().isEmpty() } private fun isMimGreaterOne(graph: Graph<T>): Boolean { // Search for an induced matching of 2 => MIM is greater or equal than 2 => greater than 1 for (firstEdgeStart in graph.nodes()) { for (firstEdgeEnd in graph.adjacentNodes(firstEdgeStart)) { val firstEdgeAdjacentNodes = graph.adjacentNodes(firstEdgeStart) + graph.adjacentNodes(firstEdgeEnd) for (secondEdgeStart in graph.nodes() - firstEdgeAdjacentNodes) { for (secondEdgeEnd in graph.adjacentNodes(secondEdgeStart) - firstEdgeAdjacentNodes) { return true } } } } return false } private fun isMimGreaterTwo(graph: Graph<T>): Boolean { // Search for an induced matching of 3 => MIM is greater or equal than 3 => greater than 2 for (firstEdgeStart in graph.nodes()) { for (firstEdgeEnd in graph.adjacentNodes(firstEdgeStart)) { val firstEdgeAdjacentNodes = graph.adjacentNodes(firstEdgeStart) + graph.adjacentNodes(firstEdgeEnd) for (secondEdgeStart in graph.nodes() - firstEdgeAdjacentNodes) { for (secondEdgeEnd in graph.adjacentNodes(secondEdgeStart) - firstEdgeAdjacentNodes) { val secondEdgeAdjacentNodes = graph.adjacentNodes(secondEdgeStart) + graph.adjacentNodes(secondEdgeEnd) val firstAndSecondEdgeAdjacentNodes = firstEdgeAdjacentNodes + secondEdgeAdjacentNodes for (thirdEdgeStart in graph.nodes()- firstAndSecondEdgeAdjacentNodes) { for (thirdEdgeEnd in graph.adjacentNodes(thirdEdgeStart) - firstAndSecondEdgeAdjacentNodes) { return true } } } } } } return false } }
0
Kotlin
0
0
5b49df3716acd6762341453d50bc573b890c87cc
3,056
MIM-Width
Apache License 2.0
advent-of-code-2020/src/test/java/aoc/Day3TobogganTrajectory.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.KotlinAssertions.assertThat import org.junit.Test class Day3TobogganTrajectory { private fun rideToboggan(map: Map<Point, Char>, pathFunction: (Point) -> Point): Map<Point, Char> { val maxX = map.keys.map { it.x }.max() ?: 0 val maxY = map.keys.map { it.y }.max() ?: 0 fun getWithLoop(point: Point): Char? { return map[point] ?: map[point.copy(x = point.x.rem(maxX + 1))] } val path = generateSequence(Point(0, 0), pathFunction) .takeWhile { it.y <= maxY } .toList() return path.map { point -> point to when (getWithLoop(point)) { '#' -> 'X' else -> 'O' } }.toMap() } @Test fun silverTest() { val map = parseMap(testInput) val collisions = rideToboggan(map) { point -> point.right().right().right().down() } printMap(map + collisions) assertThat(collisions.count { (_, it) -> it == 'X' }).isEqualTo(7) } @Test fun silverTask() { val map = parseMap(input) val collisions = rideToboggan(map) { point -> point.right().right().right().down() } assertThat(collisions.count { (_, it) -> it == 'X' }).isEqualTo(274) } @Test fun goldTest() { val map = parseMap(testInput) val product = multiplyTreeHits(map) assertThat(product).isEqualTo(336) assertThat(rideToboggan(map) { point -> point.right().down() }.values.count { it == 'X' }).isEqualTo(2) assertThat(rideToboggan(map) { point -> point.right().right().right().down() }.values.count { it == 'X' }).isEqualTo(7) assertThat(rideToboggan(map) { point -> point.right(inc = 5).down() }.values.count { it == 'X' }).isEqualTo(3) assertThat(rideToboggan(map) { point -> point.right(inc = 7).down() }.values.count { it == 'X' }).isEqualTo(4) assertThat(rideToboggan(map) { point -> point.right().down(inc = 2) }.values.count { it == 'X' }).isEqualTo(2) } @Test fun goldTask() { val product = multiplyTreeHits(parseMap(input)) assertThat(product).isEqualTo(6050183040) } /** * Right 1, down 1. * Right 3, down 1. (This is the slope you already checked.) * Right 5, down 1. * Right 7, down 1. * Right 1, down 2. */ private fun multiplyTreeHits(map: Map<Point, Char>): Long { return listOf( rideToboggan(map) { point -> point.right().down() }, rideToboggan(map) { point -> point.right(inc = 3).down() }, rideToboggan(map) { point -> point.right(inc = 5).down() }, rideToboggan(map) { point -> point.right(inc = 7).down() }, rideToboggan(map) { point -> point.right().down(inc = 2) } ) .map { it.count { (_, it) -> it == 'X' }.toLong() } .reduce { l, r -> l * r } } val testInput = """ ..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.# """.trimIndent() val input = """ ......#..##..#...#...#.###..... #..#............#..........#... ..........#....#..........#.... ....#..#.#..........#..#.....#. #.......#...#......#........### #####........#.#....##..##..#.. ......#.#..#..#..##.#..#.##.... .#..#.#..............##....##.. ..##......#....#........#...### ...#....#.#....#.#..#......#..# ..................#.....#.....# #.#...#...#....#............#.# .#...#.....#...##........#..... ...#....#........#..#....#..### #...##.....##.#.#...........#.# .###........#.#.#.........#.... ...#.............###.....#.#..# .####.#..#....#.....#.........# .#.#........#.#.....#.....#.... .#.......#................##.## ...#.#..#...###.....#....#..##. ...#....##..#............##...# #...#............######...#.##. .........#........#.#...#..##.. .....###..#.#.....##.#.#......# ..#.#...#.#..#.#.##..#.....#.#. ..#......#.#....#...#.......... ..#...#.....#.#...##.....#..... .##...........####........##... ....#............#.#........... .....####.........#.##....###.. #..#..#.#..............#.#..... ...#.#........#.........#...... ......#.#.#...#.....#....#..... ........#.#...#####..#..#...... .....#.#....#....#...........## .#...#.........#.......##...... .#.##..##......#............... ...#.....#.......#.#.#......... .........#..#...#...#.#.##....# .#......##....#..#.........#... ....#.....#........#.........## ......#...........##........... .....#..............###.#....#. ........#..#...#..#..#..#..#.#. .#.....#.##.#..#..#.#.....#.... ...#....#...#.#.....##.#...#..# #..#......#..#.###...........#. .##...##.#........#.#......#.#. ...#.#..#.#.......#..###...##.. #.......#.#....#..........#.... .#.....#..#.#.#..#..#........#. .#...#......#.#...#.##.....#.## ...######..#.#....#.........##. #.#.......................#.... ..#..##...#...#.#..##.......#.. .##..#.......##......##.#..#... #.#....##.......#..#........... ..#...#............#..#........ ........#.#.........#...#..#..# .#...###...............##...#.. ...........#.....#....#....###. #..#....##..#................## ...#.#..#..##......#....##....# ...#.##...#....#..#....#....... #...##..##.#.........#...#....# .##........###.#..........#.... ..#..#..#...#.##..#.#......#... .......##..#....###.##.....#..# #....#...#.#.....#..###....##.. .#.......#.........#....#.#..#. .........#.......#.#.......#... ..........#...##..#...#....#.## ..#........#.......#........... #....#.....##......#....#.#...# ......#.....#....#.....#..#.... .#....##...#...##.............. ..#....#......#...#....#...#... #....###...##..#.#....##......# ..#.......#.........#..#......# ...#...#.##.......#....##..#... ..#.#...#.##..#..#..#...#.#...# .#.........###....#....#.....#. .#.##.#..##..#...........#....# ....##..#..##.#.......#....#..# ....#..#.........##..#......#.# ..........#.#.#....##.#......## .##...#....###...#..........#.. #..#.....#..#.#.#.#..#......#.# ......#....#......##.#......#.# ...#.....#.......#....#.......# .#.#................#.......... ......#..#..#...............##. ##......#...#.####....#.#.#.... ...#..##............#....#..... ..#..#.#...#..................# .##.#.#..##.###.....#..#....... ..#...#.#...#......#..#........ .###..........##...###..##..#.. #.#...#........#.......##...... ..##...#........#....##...##... .......#.##.....#.#.##..#..##.. ........#............#....##... ...#.#.#..#.........#.#.......# ..#..##.##...#.##...#....#...#. .....##.#...##............##... .#...#.###....#.......#...#...# .......#######.#....#.....#.#.. ......#.......#............##.. .....#...........#......#.....# ........#....#.##.#............ .#........#.......##.#.#....#.. #.....#..####.#................ .....#.......................## .#.....#..##.#..##........#.#.# #...##....#..##................ ......##.###..........#.....#.. .#........#...#..............## ..#..........###.........#..... ....#.....##....#..#..#.#.#.... ....#.......#.##...#.####.#.... #........#............#.##..... ..#......##.....#..#...#....... ..#......###...#.##......#..#.. #..#..#............#..#.###.... ...##.........#..##...#..#.#... ..#.###..#.##.#........#..#.... ......#..###.#........#........ .#....#.#..#.....#..#..#....... #.....##.##...#...###.#.#..#.#. .#....#..#.........#..#....###. ......##.####...#....#........# ##..#........#..#..##...#...... #.........#.........#...#..#.#. ..........#...................# ###....#....#....#......###...# #....##........#..###.#..#..... .#......#.....#.#.........#..#. ...#.......##.....#.........### ..............#........#.....## ....#.#..#.....###.#....##..... .........#..##.#....#.#........ ...#....#.......#.#.#..#.#....# ...........#...#..........#.#.. #.................##........### ####..#.#..#...#.....###....... ..#.#......##.#.......#........ .......##........#..#.....#..#. ...#..#......#..#.#.......###.. #....#...##..#.#.#.#.........#. ....#....#....#.#..#..........# ...###........#.#.###......##.. ................#.....#.#...##. ..#..#.###...........#...###.#. .........................#..#.# #...#..#..##.###.....##.##.#... ...#..................#.#....#. ......#..##.#.......#.......#.. .##....#.#................#.... .#...#..#.#.#....##....#....... .##......#.....#..........#.... ..#...........#..##.........#.. ....#.#...........#..........## ....#.#.#...........#.#........ ......#.....#..#....##....##... ............##...##......#.#.## #.#.....#..#....#..#...#.#...#. .#...###..#..#.......#.......#. .....#..#.##.....#....#...#.... ##.....#..##.......##..#.#.#..# ....#.#......##....#.....#..### .#...#.#......#.##...#..##..... .#...#...#......##..#..#...#.#. .#.........#....##...###...##.. ###.....#......####.....#.#.... .....#..##.##................#. .#.................#...#..##.#. ....#....#..#.......#.....#.... .##....#..#..#.....###.#..#..#. #.#.......#.....##...#.....#... #.#........#.#.###...#....#.... .#.....#.....##.#...#..#....... ..###.#............#...##.###.. .....#.....#..#..##............ .#.#..#.#..##..#....#...##..... .#...........#..#.......#...#.# #.#.#.#.....##....#............ ...#.................#.#......# .....##.............#...#.#.... .##......#.#....#..........#.#. .#.##.......##...#...#.....#.#. #...#.#........#......##....#.# #....##....#....#...#..#..#.#.# ......#..........#...#.....#..# #..#....#....#..##.#..#.#...#.. ......#..#.#....#.....#.#..#..# ...#.#...###........#.#......## ..#............................ ...#.#..##...##...#...#......## ...#.####......#.........#....# .#...#.#...##....#......#.#.... .#.....##..##.#................ .#...............#............. ......#.....#...#..##..##...... ...#..##.......#.......#..#.#.# ......##.....#..#.....#...#.#.# ........##........#.#........## .#....#.....###..#.......#...#. #...#....#.........#.......#... ...##..#........#####.#........ ###..#....#.#..#...#.####...... ..#..........#.#.............#. #......#.#....#.#.#....#.##.... .#.#.#.............#....#...#.. ......#.....#.#...#..###.#..#.. .....#..#............#...#...## ..#......###..#........#.#..... #..##......#.#.#.#...........#. #..#...##.##.....#....#..#..... ...##.#..........#.#....#...#.. .#.#.#.#..#.#...#......#....... ....#......###.#............... .........#...#....#...#.#....#. ##.#.........#...##............ ........#..........#.#...#..... ..#........#....#.......#...... #..#...............#..#...##.#. #........#.....##.#..#....#...# ..##....#....#.#...........##.. ....#.#.........#..#.....#..#.. .......##....#.#.#....###.#.... ......#....#.#...#..#.........# .....##..#....#.#......#.#.#... #.##..##.#.......#..#...##.#.## ........#.#..#...##.#.#..#..... #..#......#......#...#.#..#.... .....#......#.#....##....##.... ....#.##...##..#..........##.#. .#....#.......#.........#...... .#.......#.#...#............... ....#.##.......#.##..#.##..#... #..#.......#.....#..#.......... ..#.##.......#....#.#..##..#... .#.....#...##.#.#..#...#....... .......#.........#......#.#.... #.##.....##.......#....#....... ##.#.#.........##..#.....#....# ....#.#.#.#....#..#..##.......# #...#...........#.#............ ...#...#.#..#..##.............. ......#.......#.........#..#.#. #.....##.#....#...#..#......... #...#..###.##..###...##.....#.. #....#.#.#...#.#..........#.... ................#.#....#.....## #.##..............####.....#.## ................#.....#........ #...#..#......#.....#......#... .........##...........#...#...# #.#....#...##.....#.....#..#..# .....#...##..##.............#.. ....###.#.......#.........#...# ..#.......#......#..#...#.#.... #.#....#......#.##....#.##.#... .#.#...#.......#.#...#.##..#... ..........#......#.....#....... ........#...#.....#...##...#.#. .....##....#.##..#........#.##. ..........##.....#..#........#. .#....#..#.......#.##.......... .#..#..#...#...#........#.##... .#...#.##.......#...#........#. .....#....#.............#..#... ...#....##...#...#.....##...... #.#####.........##...#.....#... ......#.......#....#.....#..#.. ..#..............#.#..#..#..... ....#.................#...#.... ###.#..##.#....#...#.#......#.# ..##......#.#........#.#...##.. .....#...#...#..#.#..#..##..#.. .##...#......#...#...##.#...#.. .......###.#...........##.##... .#.##..#.#.###.......#..##...#. ..#....#.......#..##......#.... .#....#.#..#..#.#.#....#...#... ..........##....#....#.#....... .....#.......#.#..###.#.###.... .#.#....#.##..#.#..#.....#.#.#. ....#.....#.#.#............#... .###....#...##......##..###..#. ...#.#..#.....#...#....##..#... .#.#....#..........#...##.....# #.....##...#........#.#..##..#. .......#....#.#..........#...#. .........#..#.#.###.........##. ..................#.#....#....# ....#....#.#..#.......###.##.## ....#...#.................#.... ...#..#####.......#.#..##.##... ##.#....#...............#..#... ....#..........#...........#.#. ..##.#.##.#..#.#....#.......... .....#....#....##.#....#....#.# .......#..##.....###...#....#.# .#.......#..#.#.#...........#.. .#...........##.#.##....#.#.... ....#.#....#.#.#......##....... .........##......#.#.....###... ........#.#...#.##.....#.##.##. ##.#..##.#.........#....#...... .#.#.#....#..........#.#....#.. ....###.........#.#.#.......... #..#....##.....#............... #.##....#.#...#.....#......#.#. ............#.##........#...... .....#.#.....##..##............ .##..........#.......#......#.. ...##..##......#.....#..#....## .##.##...#.................##.. #....#.#........#..#....#..##.# ....##..##......#....###.#.#..# .....#....#..#..#...##...#...#. """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
16,561
advent-of-code
MIT License
src/cn/leetcode/codes/simple50/Simple50.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple50 import cn.leetcode.codes.out fun main() { // val x = 2.0000 // val n = 10 val x = 2.0000 val n = -2 val re = myPow(x, n) out("re = $re") } /* 50. Pow(x, n) 实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。 示例 1: 输入:x = 2.00000, n = 10 输出:1024.00000 示例 2: 输入:x = 2.10000, n = 3 输出:9.26100 示例 3: 输入:x = 2.00000, n = -2 输出:0.25000 解释:2-2 = 1/22 = 1/4 = 0.25 提示: -100.0 < x < 100.0 -231 <= n <= 231-1 -104 <= xn <= 104 */ //快速幂 、 递归 fun myPow(x: Double, n: Int): Double { val N = n.toLong() return if (n >= 0) powFull(x, N) else 1.0 / powFull(x, -N) } private fun powFull(x: Double, n: Long): Double { //递归结束条件 if (n <= 0) { return 1.0 } //快速幂 结果 val y = powFull(x, n / 2) return if (n % 2 == 0L) { y * y } else y * y * x }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
972
LeetCodeSimple
Apache License 2.0
src/aoc2023/Day6.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2023 import utils.checkEquals import utils.readInputAsText fun main(): Unit = with(Day6) { part1(testInput).checkEquals(288) part1(input) .checkEquals(219849) // .sendAnswer(part = 1, day = "6", year = 2023) part2(testInput).checkEquals(71503) part2(input) .checkEquals(29432455) // .sendAnswer(part = 2, day = "6", year = 2023) } object Day6 { private fun String.extractAllNums() = "\\d+".toRegex().findAll(this).map { it.value.toLong() }.toList() fun part1(input: String): Long { val allNums = input.extractAllNums() val (times, diss) = allNums.chunked(allNums.size / 2) val raceMillisToDistancePairs = times.zip(diss) return raceMillisToDistancePairs.fold(1) { prod, (time, dis) -> prod * countRecordBeat(time, dis) } } fun part2(input: String): Long { val allNums = input.extractAllNums() val (time, dis) = allNums.chunked(allNums.size / 2).map { it.joinToString(separator = "").toLong() } return countRecordBeat(time, dis) } private fun countRecordBeat(time: Long, dis: Long): Long { var recordBeatCount = 0L var buttonHold = 0L while (buttonHold <= time) { val leftTime = time - buttonHold val raceDistance = leftTime * buttonHold if (raceDistance > dis) recordBeatCount++ buttonHold++ } return recordBeatCount } val input get() = readInputAsText("Day6", "aoc2023") val testInput get() = readInputAsText("Day6_test", "aoc2023") }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,675
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/g2101_2200/s2146_k_highest_ranked_items_within_a_price_range/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2146_k_highest_ranked_items_within_a_price_range // #Medium #Array #Sorting #Breadth_First_Search #Matrix #Heap_Priority_Queue // #2023_06_25_Time_1373_ms_(100.00%)_Space_78_MB_(100.00%) import java.util.ArrayDeque import java.util.Collections import java.util.Deque class Solution { fun highestRankedKItems(grid: Array<IntArray>, pricing: IntArray, start: IntArray, k: Int): List<List<Int>> { val m = grid.size val n = grid[0].size val row = start[0] val col = start[1] val low = pricing[0] val high = pricing[1] val items: MutableList<IntArray> = ArrayList() if (grid[row][col] in low..high) items.add(intArrayOf(0, grid[row][col], row, col)) grid[row][col] = 0 val q: Deque<IntArray> = ArrayDeque() q.offer(intArrayOf(row, col, 0)) val dirs = intArrayOf(-1, 0, 1, 0, -1) while (q.isNotEmpty()) { val p = q.poll() val i = p[0] val j = p[1] val d = p[2] for (l in 0..3) { val x = i + dirs[l] val y = j + dirs[l + 1] if (x in 0 until m && y >= 0 && y < n && grid[x][y] > 0) { if (grid[x][y] in low..high) { items.add(intArrayOf(d + 1, grid[x][y], x, y)) } grid[x][y] = 0 q.offer(intArrayOf(x, y, d + 1)) } } } Collections.sort(items) { a: IntArray, b: IntArray -> if (a[0] != b[0]) return@sort a[0] - b[0] if (a[1] != b[1]) return@sort a[1] - b[1] if (a[2] != b[2]) return@sort a[2] - b[2] a[3] - b[3] } val ans: MutableList<List<Int>> = ArrayList() var i = 0 while (i < items.size && i < k) { val p = items[i] ans.add(listOf(p[2], p[3])) ++i } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,983
LeetCode-in-Kotlin
MIT License
src/Day03.kt
Inn0
573,532,249
false
{"Kotlin": 16938}
class Backpack constructor( val compartment1: String, val compartment2: String, val str: String = compartment1 + compartment2 ) { fun getDupeVal(): Char { for (c1 in compartment1) { for (c2 in compartment2) { if (c1 == c2){ return c1 } } } return 'a' } } fun main() { fun getPrio(char: Char): Int { val prioList = mutableListOf<Char>() var c: Char = 'a' while(c <= 'z'){ prioList.add(c) ++c } c = 'A' while (c <= 'Z'){ prioList.add(c) ++c } return prioList.indexOf(char) + 1 } fun readBackpacks(input: List<String>): MutableList<Backpack> { val backpacks = mutableListOf<Backpack>() input.forEach { val comp1 = it.substring(0, it.length / 2) val comp2 = it.substring(it.length / 2) val backpack = Backpack(comp1, comp2) backpacks.add(backpack) } return backpacks } fun getGroups(backpacks: List<Backpack>): MutableList<MutableList<Backpack>> { val backpackGroups: MutableList<MutableList<Backpack>> = mutableListOf() var backpackGroup: MutableList<Backpack> = mutableListOf() var counter = 0 backpacks.forEach { backpackGroup.add(it) if(counter == 2) { backpackGroups.add(backpackGroup) backpackGroup = mutableListOf() counter = -1 } counter++ } return backpackGroups } fun getTotal(backpacks: List<Backpack>): Int { var total = 0 backpacks.forEach { total += getPrio(it.getDupeVal()) } return total } fun getBadgeVal(backpacks: List<Backpack>): Int { for (c1 in backpacks[0].str) { for (c2 in backpacks[1].str){ for (c3 in backpacks[2].str){ if(c1 == c2 && c2 == c3){ return getPrio(c1) } } } } return 0 } fun part1(input: List<String>): Int { val backpacks = readBackpacks(input) return getTotal(backpacks) } fun part2(input: List<String>): Int { val backpacks = readBackpacks(input) val groups = getGroups(backpacks) var total = 0 groups.forEach { total += getBadgeVal(it) } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
f35b9caba5f0c76e6e32bc30196a2b462a70dbbe
2,882
aoc-2022
Apache License 2.0
advent-of-code-2022/src/Day19.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { val testInput = readInput("Day19_test") val input = readInput("Day19") "Part 1" { part1(testInput) shouldBe 33 measureAnswer { part1(input) } } "Part 2" { part2(testInput) shouldBe (56 * 62) measureAnswer { part2(input) } } } private fun readInput(name: String) = readLines(name).map(FactoryBlueprint.Companion::fromString) private fun part1(input: List<FactoryBlueprint>): Int = input.withIndex().sumOf { (i, bp) -> maxGeodes(bp, time = 24) * (i + 1) } private fun part2(input: List<FactoryBlueprint>): Int = input.take(3).map { bp -> maxGeodes(bp, time = 32) }.reduce(Int::times) private fun maxGeodes(blueprint: FactoryBlueprint, time: Int): Int { val maxBotsInTime = Array(time + 2) { 0 } val queue = ArrayDeque<State>() val seenStates = mutableSetOf<State>() fun addNextState(state: State) { if (state in seenStates) return queue.addLast(state) seenStates += state } addNextState(State(time)) var maxGeodes = 0 while (queue.isNotEmpty()) { val state = queue.removeFirst() if (state.timeLeft == 0) { maxGeodes = maxOf(maxGeodes, state.geodes) continue } if (state.geodeBots < maxBotsInTime[state.timeLeft + 1]) continue maxBotsInTime[state.timeLeft] = maxOf(state.geodeBots, maxBotsInTime[state.timeLeft]) addNextState(state.tick()) if (state.shouldBuildGeodeBot(blueprint)) { addNextState( state.tick( spendOre = blueprint.geodeBotCostOre, spendObsidian = blueprint.geodeBotCostObsidian, newGeodeBots = +1, ) ) } if (state.shouldBuildObsidianBot(blueprint)) { addNextState( state.tick( spendOre = blueprint.obsidianBotCostOre, spendClay = blueprint.obsidianBotCostClay, newObsidianBots = +1, ) ) } if (state.shouldBuildClayBot(blueprint)) { addNextState( state.tick( spendOre = blueprint.clayBotCost, newClayBots = +1, ) ) } if (state.shouldBuildOreBot(blueprint)) { addNextState( state.tick( spendOre = blueprint.oreBotCost, newOreBots = +1, ) ) } } return maxGeodes } private data class State( val timeLeft: Int, val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geodes: Int = 0, val oreBots: Int = 1, val clayBots: Int = 0, val obsidianBots: Int = 0, val geodeBots: Int = 0, ) { fun shouldBuildOreBot(bp: FactoryBlueprint) = oreBots < bp.maxOreCost && bp.canBuildOreBot(ore) fun shouldBuildClayBot(bp: FactoryBlueprint) = clayBots < bp.obsidianBotCostClay && bp.canBuildClayBot(ore) fun shouldBuildObsidianBot(bp: FactoryBlueprint) = obsidianBots < bp.geodeBotCostObsidian && bp.canBuildObsidianBot(ore, clay) fun shouldBuildGeodeBot(bp: FactoryBlueprint) = bp.canBuildGeodeBot(ore, obsidian) fun tick( spendOre: Int = 0, spendClay: Int = 0, spendObsidian: Int = 0, newOreBots: Int = 0, newClayBots: Int = 0, newObsidianBots: Int = 0, newGeodeBots: Int = 0, ): State = State( timeLeft = timeLeft - 1, ore = ore + oreBots - spendOre, clay = clay + clayBots - spendClay, obsidian = obsidian + obsidianBots - spendObsidian, geodes = geodes + geodeBots, oreBots = oreBots + newOreBots, clayBots = clayBots + newClayBots, obsidianBots = obsidianBots + newObsidianBots, geodeBots = geodeBots + newGeodeBots, ) } private class FactoryBlueprint( val oreBotCost: Int, val clayBotCost: Int, val obsidianBotCostOre: Int, val obsidianBotCostClay: Int, val geodeBotCostOre: Int, val geodeBotCostObsidian: Int, ) { val maxOreCost = maxOf(clayBotCost, obsidianBotCostOre, geodeBotCostOre) fun canBuildOreBot(ore: Int) = ore >= oreBotCost fun canBuildClayBot(ore: Int) = ore >= clayBotCost fun canBuildObsidianBot(ore: Int, clay: Int) = ore >= obsidianBotCostOre && clay >= obsidianBotCostClay fun canBuildGeodeBot(ore: Int, obsidian: Int) = ore >= geodeBotCostOre && obsidian >= geodeBotCostObsidian companion object { private val pattern = Regex( "Blueprint \\d+: Each ore robot costs (\\d+) ore. " + "Each clay robot costs (\\d+) ore. " + "Each obsidian robot costs (\\d+) ore and (\\d+) clay. " + "Each geode robot costs (\\d+) ore and (\\d+) obsidian." ) fun fromString(line: String): FactoryBlueprint { val (oreCost, clayCost, obsidianCostOre, obsidianCostClay, geodeCostOre, geodeCostObsidian) = pattern.matchEntire(line)!!.destructured return FactoryBlueprint( oreBotCost = oreCost.toInt(), clayBotCost = clayCost.toInt(), obsidianBotCostOre = obsidianCostOre.toInt(), obsidianBotCostClay = obsidianCostClay.toInt(), geodeBotCostOre = geodeCostOre.toInt(), geodeBotCostObsidian = geodeCostObsidian.toInt(), ) } } }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
5,541
advent-of-code
Apache License 2.0
src/main/kotlin/day03/day03.kt
andrew-suprun
725,670,189
false
{"Kotlin": 18354, "Python": 17857, "Dart": 8224}
package day03 import java.io.File fun main() { run(::part1) run(::part2) } data class Number(val value: Int, val row: Int, val colStart: Int, var colEnd: Int) fun run(part: (numbers: List<Number>, char: Char, row: Int, col: Int) -> Int) { val lines = File("input.data").readLines() val numbers = parseEngine(lines) var result = 0 for ((row, line) in lines.withIndex()) { for ((col, char) in line.withIndex()) { result += part(numbers, char, row, col) } } println(result) } fun part1(numbers: List<Number>, char: Char, row: Int, col: Int): Int { var result = 0 if (char != '.' && !char.isDigit()) { for (number in numbers) { if (adjacent(number, row, col)) { result += number.value } } } return result } fun part2(numbers: List<Number>, char: Char, row: Int, col: Int): Int { var result = 0 if (char == '*') { val adjacentNumbers = mutableListOf<Number>() for (number in numbers) { if (adjacent(number, row, col)) adjacentNumbers += number } if (adjacentNumbers.size == 2) { result += adjacentNumbers[0].value * adjacentNumbers[1].value } } return result } fun parseEngine(lines: List<String>): List<Number> { val numbers = mutableListOf<Number>() for ((row, line) in lines.withIndex()) { var firstDigit = -1 for ((col, char) in line.withIndex()) { if (char.isDigit()) { if (firstDigit == -1) { firstDigit = col } } else { if (firstDigit != -1) { val value = line.substring(firstDigit, col).toInt() numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = col) firstDigit = -1 } } } if (firstDigit != -1) { val value = line.substring(firstDigit, line.length).toInt() numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = line.length) } } return numbers } fun adjacent(number: Number, row: Int, col: Int): Boolean = row in number.row - 1..number.row + 1 && col in number.colStart - 1..number.colEnd // Part1: 527144 // Part2: 81463996
0
Kotlin
0
0
dd5f53e74e59ab0cab71ce7c53975695518cdbde
2,361
AoC-2023
The Unlicense
advent-of-code/src/main/kotlin/solution/Day07.kt
kressnick25
573,285,946
false
null
package solution import java.lang.Exception import java.lang.Integer.parseInt import java.lang.NullPointerException data class File ( val size: Int, val name: String ) class Dir constructor(val name: String, val parent: Dir?, var files: ArrayDeque<File> = ArrayDeque(), val subDirs: ArrayDeque<Dir> = ArrayDeque()) { fun size(): Int { var total = 0 total += files.map(File::size).sum() total += subDirs.map(Dir::size).sum() return total } } fun parseCommands(lines: List<String>): Dir { val root = Dir("/", null) var parent = root var head = root for (line in lines) { val cmdReg = "(\\\$) ([a-z]+) *(.*)".toRegex() if (line.matches(cmdReg)) { val (_, cmd, cmdVal) = cmdReg.matchEntire(line)!!.destructured when(cmd) { "cd" -> head = when (cmdVal) { "/" -> root ".." -> head.parent ?: throw NullPointerException("No parent of current dir") else -> head.subDirs.find { it.name == cmdVal } ?: throw NullPointerException("Dir not found in current") } "ls" -> continue else -> throw Exception("Unknown cmd: $cmd") } } else { val dirReg = "(dir) ([a-z]+)".toRegex() val fileReg = "([0-9]+) ([a-z]+\\.*[a-z]*)".toRegex() when { line.matches(dirReg) -> { val (_, dirname) = dirReg.matchEntire(line)!!.destructured head.subDirs.addLast(Dir(dirname, head)) } line.matches(fileReg) -> { val (size, filename) = fileReg.matchEntire(line)!!.destructured head.files.addLast(File(parseInt(size), filename)) } else -> throw Exception("Unknown line format") } } } return root } class Day07 : Solution { override fun solvePart1(input: String): String { val root: Dir = parseCommands(input.lines()) var total = 0 val queue: ArrayDeque<Dir> = ArrayDeque() queue.addFirst(root) while(queue.isNotEmpty()) { val next = queue.removeFirst() queue.addAll(next.subDirs) val size = next.size() if (size <= 100000) { total += size } } return total.toString() } override fun solvePart2(input: String): String { val diskSize = 70000000 val targetUnused = 30000000 val root: Dir = parseCommands(input.lines()) var usedSpace = root.size() var unusedSpace = diskSize - usedSpace val optionDirs: MutableList<Dir> = mutableListOf() var queue: ArrayDeque<Dir> = ArrayDeque() queue.addFirst(root) while(queue.isNotEmpty()) { val next = queue.removeFirst() queue.addAll(next.subDirs) val dirSize = next.size() if (unusedSpace + dirSize >= targetUnused) { optionDirs.add(next) } } return optionDirs.map(Dir::size).minOrNull()!!.toString() } }
0
Rust
0
0
203284a1941e018c7ad3c5d719a6e366013ffb82
3,270
advent-of-code-2022
MIT License
src/Day07.kt
thiyagu06
572,818,472
false
{"Kotlin": 17748}
import aoc22.printIt import java.io.File fun main() { fun parseInput(file: String): List<String> { return File(file).readLines() } fun part1(): Long { val input = parseInput("input.txt/day07.txt") val dirs = mutableListOf(Dir(null)) var current: Dir = dirs.first() input.drop(1).forEach { line -> when { line == "$ cd .." -> current = current.parent!! line.startsWith("$ cd") -> { Dir(current).also { current.children += it; dirs += it; current = it } } line[0].isDigit() -> current.filesSize += line.substringBefore(" ").toLong() } } return dirs.filter { it.totalSize <= 100_000 }.sumOf { it.totalSize }.printIt() } fun part2(): Long { val input = parseInput("input.txt/day07.txt") val dirs = mutableListOf(Dir(null)) var current: Dir = dirs.first() input.drop(1).forEach { line -> when { line == "$ cd .." -> current = current.parent!! line.startsWith("$ cd") -> { Dir(current).also { current.children += it; dirs += it; current = it } } line[0].isDigit() -> current.filesSize += line.substringBefore(" ").toLong() } } val missing = 30_000_000 - (70_000_000 - dirs.first().totalSize) return dirs.filter { it.totalSize >= missing }.minOf { it.totalSize }.printIt() } // test if implementation meets criteria from the description, like: check(part1() == 1086293.toLong()) check(part2() == 366028.toLong()) } class Dir(val parent: Dir?, var children: List<Dir> = emptyList()) { var filesSize = 0L val totalSize: Long get() = filesSize + children.sumOf { it.totalSize } }
0
Kotlin
0
0
55a7acdd25f1a101be5547e15e6c1512481c4e21
1,852
aoc-2022
Apache License 2.0
src/Day15.kt
Tomcat88
572,566,485
false
{"Kotlin": 52372}
import kotlin.math.abs object Day15 { fun part1(input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>) { val grid = mutableMapOf<Pair<Int, Int>, Char>() val rowToInspect = 2000000 input.forEach { (sensor, beacon) -> sensor.log("s") beacon.log("b") val (sX, sY) = sensor val (bX, bY) = beacon grid[sensor] = 'S' grid[beacon] = 'B' val dx = abs(sX - bX) val dy = abs(sY - bY) val radius = dx + dy val diff = abs(rowToInspect - sY) (sX - (radius - diff)..(sX + (radius - diff))).log() .forEach { grid[it to rowToInspect] = '#' } } grid.filter { it.key.second == rowToInspect }.size.log() } fun part2(input: List<Sensor>) { val reducedMax = 4_000_000 (0..reducedMax).forEach { row -> var col = 0 while (col <= reducedMax) { val sb = input.find { (radius, sensor, beacon) -> val (sX, sY) = sensor val (bX, bY) = beacon val dR = abs(row - sY) val dC = abs(col - sX) return@find dR + dC <= radius } if (sb != null) { val (sX, sY) = sb.center val dR = abs(row - sY) val dC = sX - col col += (sb.radius - dR + dC) + 1 } else { (row to col).log("part2") (col.toLong() * reducedMax.toLong() + row.toLong()).log("part2") return@forEach } } } // input.forEach { (sensor, beacon) -> // sensor.log("s") // beacon.log("b") // val (sX, sY) = sensor // val (bX, bY) = beacon // grid[sensor] = 'S' // grid[beacon] = 'B' // val dx = abs(sX - bX) // val dy = abs(sY - bY) // val radius = dx + dy //// (sY - radius..sY + radius).log().contains(rowToInspect).log("contains") // ((sY - radius).. (sY + radius)).filter { it in 0..reducedMax }.forEach{ row -> // val diff = abs(row - sY) // (sX - (radius - diff)..(sX + (radius - diff))).filter { it >= 0 && it <= reducedMax }.forEach { grid[it to row] = '#' } // } // } // grid.size.log("part2") // grid.filter{ it.key.second == rowToInspect }.size.log() } @JvmStatic fun main(args: Array<String>) { val input = downloadAndReadInput("Day15", "\n").filter { it.isNotBlank() }.map { it.split(":").let { (sensor, beacon) -> sensor.removePrefix("Sensor at ").split(",").let { it[0].removePrefix("x=").toInt() to it[1].removePrefix(" y=").toInt() } to beacon.removePrefix(" closest beacon is at ").split(",").let { it[0].removePrefix("x=").toInt() to it[1].removePrefix(" y=").toInt() } }.let { Sensor.of(it.first, it.second) } }.log() part2(input) } data class Sensor(val radius: Int, val center: Pair<Int, Int>, val beacon: Pair<Int, Int>) { fun inside(pair: Pair<Int, Int>): Boolean { val (x, y) = center val dR = abs(pair.second - y) val dC = abs(pair.first - x) return dR + dC <= radius } companion object { fun of(center: Pair<Int, Int>, beacon: Pair<Int, Int>): Sensor { val (sX, sY) = center val (bX, bY) = beacon val dx = abs(sX - bX) val dy = abs(sY - bY) return Sensor(dx + dy, center, beacon) } } } } operator fun Pair<Int, Int>.plus(pair: Pair<Int, Int>) = (first + pair.first) to (second + pair.second)
0
Kotlin
0
0
6d95882887128c322d46cbf975b283e4a985f74f
4,144
advent-of-code-2022
Apache License 2.0
src/Day09/Solution.kt
cweinberger
572,873,688
false
{"Kotlin": 42814}
package Day09 import readInput import kotlin.math.abs /** * Initial state: ...... ...... ...... ...... H..... */ fun main() { fun Boolean.toInt() = if (this) 1 else 0 fun parseInstructions(input: List<String>) : List<Pair<Char, Int>> { return input.map { line -> line.split(" ").let { Pair(it.first().first(), it.last().toInt()) } } } fun moveHead(from: Pair<Int, Int>, direction: Char) : Pair<Int, Int> { return when (direction) { 'R' -> Pair(from.first + 1, from.second) 'D' -> Pair(from.first, from.second + 1) 'L' -> Pair(from.first - 1, from.second) 'U' -> Pair(from.first, from.second - 1) else -> throw IllegalArgumentException("Illegal direction: $direction") } } fun isTouching(head: Pair<Int, Int>, tail: Pair<Int, Int>) : Boolean { return abs(head.first - tail.first) <= 1 && abs(head.second - tail.second) <= 1 } fun moveTail(tail: Pair<Int, Int>, head: Pair<Int, Int>) : Pair<Int, Int> { if (isTouching(tail, head)) return tail var newX: Int = tail.first var newY: Int = tail.second // UGLY BUT WORKS (: // X if (abs(head.first - tail.first) > 1) { newX = tail.first + if (tail.first > head.first) -1 else 1 if (abs(head.second - tail.second) > 1) { newY = tail.second + if (tail.second > head.second) -1 else 1 } else { newY = head.second } return Pair(newX, newY) } // Y if (abs(head.second - tail.second) > 1) { newY = tail.second + if (tail.second > head.second) -1 else 1 if (abs(head.first - tail.first) > 1) { newX = tail.first + if (tail.first > head.first) -1 else 1 } else { newX = head.first } return Pair(newX, newY) } return Pair(newX, newY) } fun printField( positions: List<Pair<Int, Int>>, xMin: Int? = null, xMax: Int? = null, yMin: Int? = null, yMax: Int? = null, ) { val xMin = xMin ?: positions.minOf { it.first } val xMax = xMax ?: positions.maxOf { it.first } val yMin = yMin ?: positions.minOf { it.second } val yMax = yMax ?: positions.maxOf { it.second } for (y in yMin .. yMax) { for (x in xMin .. xMax) { if (positions.first() == Pair(x,y)) { print("H") } else if (positions.contains(Pair(x,y))) { print(positions.indexOfFirst { it == Pair(x,y) }) } else { print(".") } } print("\n") } println("") } fun part2(input: List<String>, tails: Int): Int { val instructions = parseInstructions(input) val positions = mutableListOf<Pair<Int, Int>>() repeat(tails+1) { positions.add(Pair(0,0)) } // first is head, rest is tail val visitedFields = mutableSetOf(positions.last()) instructions.forEach { instruction -> repeat(instruction.second) { positions[0] = moveHead(positions.first(), instruction.first) for (i in 1 until positions.size) { val newTail = moveTail(positions[i], positions[i-1]) positions[i] = newTail } visitedFields.add(positions.last()) } } // printField(positions) // printField(visitedFields.toList()) return visitedFields.count() } fun part1(input: List<String>): Int { return part2(input, 1) } val testInput = readInput("Day09/TestInput") val testInput2 = readInput("Day09/TestInput2") val input = readInput("Day09/Input") println("\n=== Part 1 - Test Input ===") println(part1(testInput)) println("\n=== Part 1 - Final Input ===") println(part1(input)) println("\n=== Part 2 - Test Input ===") println(part2(testInput, 9)) println("\n=== Part 2 - Test Input 2 ===") println(part2(testInput2, 9)) println("\n=== Part 2 - Final Input ===") println(part2(input, 9)) }
0
Kotlin
0
0
883785d661d4886d8c9e43b7706e6a70935fb4f1
4,335
aoc-2022
Apache License 2.0
src/ThreeSum2.kt
max-f
221,919,191
false
{"Python": 13459, "Kotlin": 8011}
import java.io.File fun main() { val s = ThreeSumSolution() val inputStrRaw = File("/home/keks/input_long").readText(Charsets.UTF_8) val inputStr = inputStrRaw.slice(1 until inputStrRaw.length - 1) val inputIntArr = inputStr.trim().split(",").toList().map { it.toInt() }.toIntArray() // Thread.sleep(2000) // val listOfResults = s.threeSum(inputIntArr) val listOfResults = measureTimeMillis({ time -> println("Duration: $time ms") }) { s.threeSum(inputIntArr) } // val listOfResults: List<List<Int>> = s.threeSum(intArrayOf(-1, 0, 1, 2, -1, -4)) // val listOfResults: List<List<Int>> = s.threeSum(intArrayOf(0, 0, 0, 1, 1, -2, -2, 1, 1)) // val listOfResults: List<List<Int>> = s.threeSum(intArrayOf(-1, -1, 2)) println(listOfResults.size) listOfResults.forEach { triplet -> println(triplet.joinToString(separator = ", ", prefix = "[", postfix = "]")) } // s.twoSum(listOf(1, 2), 0) } inline fun <T> measureTimeMillisHere( loggingFunction: (Long) -> Unit, function: () -> T ): T { val startTime = System.currentTimeMillis() val result: T = function.invoke() loggingFunction.invoke(System.currentTimeMillis() - startTime) return result } class ThreeSumSolution { private var alreadySeen: MutableSet<Set<Int>> = mutableSetOf() fun threeSum(nums: IntArray): List<List<Int>> { val result = mutableListOf<List<Int>>() val allTwoSums = twoSum(nums.toList()) for ( a in nums) { val complementingPairs = allTwoSums[-a] ?: continue for (pairSet in complementingPairs) { val b: Int = pairSet[0] val c: Int = pairSet[1] val tripletSet: Set<Int> = setOf(a, b, c) if (!alreadySeen.contains(tripletSet)) { alreadySeen.add(tripletSet) result.add(listOf(a, b, c)) } } } return result } /** * Return all possible twoSums */ private fun twoSum(nums: List<Int>): Map<Int, List<List<Int>>> { val allTwoSums: MutableMap<Int, MutableList<List<Int>>> = mutableMapOf() for ((ax, a) in nums.withIndex()) { for ((bx, b) in nums.withIndex()) { if (ax == bx) { continue } val twoSum = a + b val tuple = listOf(a, b) val listToAdd = allTwoSums.getOrDefault(twoSum, mutableListOf()) listToAdd.add(tuple) allTwoSums[twoSum] = listToAdd } } return allTwoSums } }
0
Python
0
0
3fc1888484531a1a23b880f9875614e56f846564
2,634
leetcode
MIT License
src/main/kotlin/me/peckb/aoc/_2018/calendar/day11/Day11.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2018.calendar.day11 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import kotlin.Int.Companion.MIN_VALUE class Day11 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readOne { input -> val serialNumber = input.toInt() val fuelCells = Array(300) { Array(300) { 0 } } repeat(300) { y -> repeat(300) { x -> fuelCells[y][x] = calculatePowerLevel(x, y, serialNumber) } } var maxFuelCellArea: Pair<Pair<Int, Int>, Int> = (-1 to -1) to MIN_VALUE (1 until 299).forEach { y -> (1 until 299).forEach { x -> val sum = (y - 1..y + 1).sumOf { yy -> (x - 1..x + 1).sumOf { xx -> fuelCells[yy][xx] } } if (sum > maxFuelCellArea.second) maxFuelCellArea = (x - 1 to y - 1) to sum } } maxFuelCellArea.first } fun partTwo(filename: String) = generatorFactory.forFile(filename).readOne { input -> val serialNumber = input.toInt() val summedAreaFuelCells = Array(300) { Array(300) { 0 } } repeat(300) { y -> repeat(300) { x -> val ul = summedAreaFuelCells.get(y - 1, x - 1) ?: 0 val ur = summedAreaFuelCells.get(y - 1, x) ?: 0 val ll = summedAreaFuelCells.get(y, x - 1) ?: 0 val lr = calculatePowerLevel(x, y, serialNumber) summedAreaFuelCells[y][x] = lr + ll + ur - ul } } var maxFuelCellArea = Triple((-1 to -1), MIN_VALUE, 0) (1..300).forEach { gridSize -> (0 until 300 - gridSize).forEach { y -> (0 until 300 - gridSize).forEach { x -> val ul = summedAreaFuelCells[y][x] val ur = summedAreaFuelCells[y][x + gridSize] val ll = summedAreaFuelCells[y + gridSize][x] val lr = summedAreaFuelCells[y + gridSize][x + gridSize] val sum = lr + ul - ur - ll if (sum > maxFuelCellArea.second) maxFuelCellArea = Triple(x + 1 to y + 1, sum, gridSize) } } } Triple(maxFuelCellArea.first.first, maxFuelCellArea.first.second, maxFuelCellArea.third) } private fun calculatePowerLevel(x: Int, y: Int, serialNumber: Int): Int { val rackID = (x + 10) var powerLevel = rackID * y powerLevel += serialNumber powerLevel *= rackID val hundredsDigit = (powerLevel % 1000) / 100 return hundredsDigit - 5 } private fun <T> Array<Array<T>>.get(y: Int, x: Int): T? { return if (y in (indices) && x in (this[y].indices)) { this[y][x] } else { null } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,639
advent-of-code
MIT License
src/main/kotlin/de/tek/adventofcode/y2022/day04/CampCleanup.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day04 import de.tek.adventofcode.y2022.util.readInputLines class AssignmentPair(code: String) { private val sections = code.split(',').map { parseLimits(it) }.map { IntRange(it[0], it[1]) } private fun parseLimits(it: String) = it.split('-').map { limit -> limit.toInt() }.take(2) fun containsFullOverlap(): Boolean { val biggestSection = sections.maxBy { it.length() } return sections.all { biggestSection.contains(it.first) && biggestSection.contains(it.last) } } fun bothSectionsOverlap() = sections[0] overlaps sections[1] || sections[1] overlaps sections[0] private fun IntRange.length() = last - first private infix fun IntRange.overlaps(other: IntRange) = this.contains(other.first) || this.contains(other.last) } fun main() { val input = readInputLines(AssignmentPair::class) fun part1(input: List<String>) = input.map { AssignmentPair(it) }.count { it.containsFullOverlap() } fun part2(input: List<String>) = input.map { AssignmentPair(it) }.count { it.bothSectionsOverlap() } println("In ${part1(input)} assignment pairs one range fully contains the other.") println("In ${part2(input)} assignment pairs the ranges overlap.") }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
1,245
advent-of-code-2022
Apache License 2.0
src/Day18.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
fun main() { var dx: MutableList<Int> = mutableListOf(0, 1, 0, -1, 0, 0) var dy: MutableList<Int> = mutableListOf(-1, 0, 1, 0, 0, 0) var dz: MutableList<Int> = mutableListOf(0, 0, 0, 0, -1, 1) fun part1(input: List<String>): Int { val tam = 20 var grid = Array(tam) { Array(tam) { BooleanArray(tam) { false } } } var minVal = tam var maxVal = 0 for (line in input) { var (x, y, z) = line.split(",").map { it.toInt() } grid[x][y][z] = true minVal = minOf(minVal, x, y, z) maxVal = maxOf(maxVal, x, y, z) } var ans = 0 for (x in 0 until tam) { for (y in 0 until tam) { for (z in 0 until tam) { if (!grid[x][y][z]) continue for (k in 0 until dx.size) { var nx = x + dx[k] var ny = y + dy[k] var nz = z + dz[k] if (nx < 0 || nx >= tam || ny < 0 || ny >= tam || nz < 0 || nz >= tam) { ans++ } else if (!grid[nx][ny][nz]) { ans++ } } } } } return ans } fun dfs(x: Int, y: Int, z: Int, grid: Array<Array<BooleanArray>>, vis: Array<Array<BooleanArray>>, tam: Int) { var stack = mutableListOf<Triple<Int, Int, Int>>() stack.add(Triple(x, y, z)) while (stack.isNotEmpty()) { var (x, y, z) = stack.removeAt(stack.size - 1) if (vis[x][y][z]) continue vis[x][y][z] = true for (k in 0 until dx.size) { var nx = x + dx[k] var ny = y + dy[k] var nz = z + dz[k] if (nx < 0 || nx >= tam || ny < 0 || ny >= tam || nz < 0 || nz >= tam) continue if (!grid[nx][ny][nz] && !vis[nx][ny][nz]) { stack.add(Triple(nx, ny, nz)) } } } } fun part2(input: List<String>): Int { val tam = 22 var grid = Array(tam) { Array(tam) { BooleanArray(tam) { false } } } var vis = Array(tam) { Array(tam) { BooleanArray(tam) { false } } } for (line in input) { var (x, y, z) = line.split(",").map { it.toInt()+1 } grid[x][y][z] = true } dfs(0, 0, 0, grid, vis, tam) var ans = 0 for (x in 0 until tam) { for (y in 0 until tam) { for (z in 0 until tam) { if (!grid[x][y][z]) continue for (k in 0 until dx.size) { var nx = x + dx[k] var ny = y + dy[k] var nz = z + dz[k] if (nx < 0 || nx >= tam || ny < 0 || ny >= tam || nz < 0 || nz >= tam) { ans++ } else if (vis[nx][ny][nz]) { ans++ } } } } } return ans } val input = readInput("Day18") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
3,314
advent-of-code-2022-kotlin
Apache License 2.0
solutions/src/MaxDiffYouCanGetFromChangingInteger.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/ */ class MaxDiffYouCanGetFromChangingInteger { fun maxDiff(num: Int) : Int { val numMap = buildNumMap(num) var min = Int.MAX_VALUE var max = Int.MIN_VALUE for(x in 0 until 10) { for(y in 0 until 10) { val copyMap = numMap.toMutableMap() if (x != y) { copyMap[x] = listOf() copyMap[y] = numMap.getOrDefault(y, listOf()) + numMap.getOrDefault(x, listOf()) } val newNum = buildNum(copyMap) if (newNum != 0) { min = minOf(min,newNum) max = maxOf(max,newNum) } } } return max-min } private fun buildNum(numMap: Map<Int,List<Int>>) : Int { val numList = numMap .flatMap { entry -> entry.value.map { Pair(it,entry.key) } } .sortedBy { it.first } .map { it.second } if (numList.isEmpty()) { return 0 } else if (numList[0] == 0) { return 0 } var number = 0 for (i in numList.indices) { number*=10 number+=numList[i] } return number; } private fun buildNumMap(number: Int) : Map<Int,List<Int>> { val numList = mutableListOf<Int>() var num = number while (num > 0) { numList.add(0,num % 10) num/=10 } return numList .mapIndexed { index, i -> Pair(i,index) } .groupBy{it.first} .mapValues { entry -> entry.value.map { it.second } } } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,769
leetcode-solutions
MIT License
src/main/kotlin/Problem26.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import java.util.Comparator /** * Reciprocal cycles * * A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to * 10 are given: * * 1/2 = 0.5 * 1/3 = 0.(3) * 1/4 = 0.25 * 1/5 = 0.2 * 1/6 = 0.1(6) * 1/7 = 0.(142857) * 1/8 = 0.125 * 1/9 = 0.(1) * 1/10 = 0.1 * * Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring * cycle. * * Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. * * https://projecteuler.net/problem=26 */ fun main() { println(2.countRepeatingDecimalsInUnitFraction()) println(3.countRepeatingDecimalsInUnitFraction()) println(4.countRepeatingDecimalsInUnitFraction()) println(5.countRepeatingDecimalsInUnitFraction()) println(6.countRepeatingDecimalsInUnitFraction()) println(7.countRepeatingDecimalsInUnitFraction()) println(8.countRepeatingDecimalsInUnitFraction()) println(9.countRepeatingDecimalsInUnitFraction()) println(10.countRepeatingDecimalsInUnitFraction()) println(findLongestRecurringCycle(1_000)) } private fun findLongestRecurringCycle(limit: Int): Int = (2 until limit) .map { it to it.countRepeatingDecimalsInUnitFraction() } .maxWithOrNull(Comparator.comparingInt(Pair<Int, Int>::second))!! .first private fun Int.countRepeatingDecimalsInUnitFraction(): Int { var acc = 10 var rem: Int val rems = mutableMapOf<Int, Int>() var index = 0 do { rem = acc / this acc -= (this * rem) if (acc in rems) { return rems.size - rems[acc]!! } else { rems[acc] = index index++ } acc *= 10 } while (acc > 0) return 0 }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,815
project-euler
MIT License
src/main/kotlin/aoc2015/Day14.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2015 import AoCDay import util.match // https://adventofcode.com/2015/day/14 object Day14 : AoCDay<Int>( title = "Reindeer Olympics", part1Answer = 2696, part2Answer = 1084, ) { private class Reindeer(val speed: Int, val goSeconds: Int, val restSeconds: Int) { fun travelFor(seconds: Int): Int { var distance = 0 var secondsLeft = seconds while (true) { repeat(goSeconds) { if (secondsLeft <= 0) return distance secondsLeft-- distance += speed } secondsLeft -= restSeconds } } } private val REINDEER_REGEX = Regex("""\w+ can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds\.""") private fun parseReindeer(input: String) = input .lines() .map { line -> REINDEER_REGEX.match(line) } .map { (speed, goSeconds, restSeconds) -> Reindeer(speed.toInt(), goSeconds.toInt(), restSeconds.toInt()) } override fun part1(input: String) = parseReindeer(input).maxOf { reindeer -> reindeer.travelFor(seconds = 2503) } override fun part2(input: String): Int { class ReindeerState( val reindeer: Reindeer, var go: Boolean = true, var secondsLeft: Int, var distance: Int = 0, var points: Int = 0, ) val reindeerStates = parseReindeer(input).map { ReindeerState(it, secondsLeft = it.goSeconds) } repeat(2503) { for (state in reindeerStates) with(state) { if (secondsLeft <= 0) { go = !go secondsLeft = if (go) reindeer.goSeconds else reindeer.restSeconds } secondsLeft-- if (go) distance += reindeer.speed } val maxDistance = reindeerStates.maxOf { it.distance } reindeerStates.forEach { if (it.distance == maxDistance) it.points++ } } return reindeerStates.maxOf { it.points } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,110
advent-of-code-kotlin
MIT License
src/main/kotlin/com/jacobhyphenated/advent2023/day10/Day10.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day10 import com.jacobhyphenated.advent2023.Day import java.util.* /** * Day 10: Pipe Maze * * The puzzle input describes a maze of pipes. Each character represents the shape of a pipe * with the '.' character meaning an empty spaces. * * Start at the S symbol, which connects to adjacent connecting pipes * Following the pipes from the S symbol form a loop. There are segments of pipe * throughout the grid that are not part of the pipe loop */ class Day10: Day<List<List<Char>>> { override fun getInput(): List<List<Char>> { return readInputFile("10").lines().map { it.toCharArray().toList() } } /** * Part 1: What section of pipe loop is the furthest distance from the S position? * * Solve with a straightforward implementation of Dijkstra's algorithm to find the path cost * from S to all other positions in the loop */ override fun part1(input: List<List<Char>>): Int { val distances = calculateDistances(input) return distances.values.max() } /** * Part 2: Count how many spaces are enclosed within the loop * * Note: You can move between sections of pipe that do not connect * example: * .......... * .S------7. * .|F----7|. * .||OOOO||. * .||OOOO||. * .|L-7F-J|. * .|II||II|. * .L--JL--J. * .......... * * The O spaces are open to the outside because you can move between the 7F, ||, and JL pipe segments * The above example contains only 4 interior spaces, marked as I * * Note 2: junk pipe segments not part of the pipe loop can count as interior spaces */ override fun part2(input: List<List<Char>>): Int { // use the distance calculation from part 1 to build the full pipe loop val distances = calculateDistances(input) // account for moving between pipes by adding empty spaces around the previous grid spaces val expandedGrid = input.flatMap { row -> listOf( row.flatMap { c -> listOf(c, '.') }, List(row.size * 2) { '.' } )}.toList() val pipeLoop = distances.keys.map { (r,c) -> Pair(r*2, c*2) }.toSet() // Connect the pipe loop spaces through the new empty spaces val expandedPipeLoop = pipeLoop.toMutableSet() pipeLoop.forEach { (r, c) -> directionsFromPosition(r, c, expandedGrid).map { direction -> val next = direction.nextPosition(r,c) val skipNext = direction.nextPosition(next.first, next.second) if (skipNext in pipeLoop && direction.opposite() in directionsFromPosition(skipNext.first, skipNext.second, expandedGrid)) { expandedPipeLoop.add(next) } } } // Now test each grid position (that is not part of the pipe loop) to see if it's interior or not val memoOpen = mutableSetOf<Pair<Int,Int>>() return input.indices.flatMap { row -> input[row].indices.map { col -> Pair(row * 2, col * 2) } } .filter { it !in expandedPipeLoop } .count { (row, col) -> !canAccessOutsideOfGrid(row, col, expandedGrid, expandedPipeLoop, memoOpen) } } // Use Dijkstra's algorithm to calculate the distance from the start to each other pipe node private fun calculateDistances(input: List<List<Char>>): Map<Pair<Int,Int>, Int> { val start = findStart(input) val distances: MutableMap<Pair<Int,Int>, Int> = mutableMapOf(start to 0) val (startRow, startCol) = start // we don't know what the start pipe looks like, so find each adjacent // location where the pipe connects to the start location val connectToStart = Direction.values().mapNotNull { direction -> val next = direction.nextPosition(startRow, startCol) if (next.first !in input.indices || next.second !in input[0].indices) { null } else if (direction.opposite() in directionsFromPosition(next.first, next.second, input)) { next } else { null } } // because the S is a weird pipe position, add the adjacent pipes to the queue rather than the start pipe val queue = PriorityQueue<PathCost> { a, b -> a.cost - b.cost } connectToStart.forEach { queue.add(PathCost(it, 1)) distances[it] = 1 } var current: PathCost do { current = queue.remove() // If we already found a less expensive way to reach this position if (current.cost > (distances[current.location] ?: Int.MAX_VALUE)) { continue } val (r,c) = current.location // From the current position, find connecting pipes findAdjacent(r, c, input).forEach { // cost is the number of steps taken, increases by 1 for each move val cost = distances.getValue(current.location) + 1 // If the cost to this space is less than what was previously known, put this on the queue if (cost < (distances[it] ?: Int.MAX_VALUE)) { distances[it] = cost queue.add(PathCost(it, cost)) } } } while (queue.size > 0) return distances } private fun findStart(grid: List<List<Char>>): Pair<Int,Int> { for (r in grid.indices) { for (c in grid[r].indices) { if (grid[r][c] == 'S') { return Pair(r,c) } } } throw IllegalStateException("Could not find start position") } // Finds pipe segments that connect to the current pipe segment // checks for connection points on the adjacent segment that line up with the current segment private fun findAdjacent(row: Int, col: Int, grid: List<List<Char>>): List<Pair<Int,Int>> { return directionsFromPosition(row, col, grid).mapNotNull { direction -> val (r, c) = direction.nextPosition(row, col) if (direction.opposite() in directionsFromPosition(r, c, grid)) { Pair(r, c) } else { null } } } private fun directionsFromPosition(row: Int, col: Int, grid: List<List<Char>>): List<Direction> { return when(grid[row][col]) { '.' -> emptyList() '|' -> listOf(Direction.NORTH, Direction.SOUTH) '-' -> listOf(Direction.EAST, Direction.WEST) 'L' -> listOf(Direction.NORTH, Direction.EAST) 'J' -> listOf(Direction.NORTH, Direction.WEST) '7' -> listOf(Direction.WEST, Direction.SOUTH) 'F' -> listOf(Direction.EAST, Direction.SOUTH) 'S' -> Direction.values().toList() else -> throw IllegalStateException("Unknown pipe character: ${grid[row][col]}") } } /** * Use a recurse search function with memoization to find if a grid position can reach outside the pipe loop * * @param row row position to test * @param col column position to test * @param grid the full expanded grid containing spaces between non-connected pipe segments * @param pipeLoop to full pipe loop with connections added to enclose the interior spaces * @param memoOpen a set used to keep track of spaces we've previously determined are not interior spaces * @param path the path so far in the recursive search */ private fun canAccessOutsideOfGrid(row: Int, col: Int, grid: List<List<Char>>, pipeLoop: Set<Pair<Int,Int>>, memoOpen: MutableSet<Pair<Int, Int>>, path: MutableSet<Pair<Int,Int>> = mutableSetOf() ): Boolean { path.add(Pair(row, col)) // this space is not interior, therefore any space on our path is not interior if (Pair(row, col) in memoOpen){ memoOpen.addAll(path) return true } // this space is at the edge of our puzzle grid, and therefor is not interior if (row <= 0 || row >= grid.size || col <= 0 || col >= grid[row].size ) { memoOpen.addAll(path) return true } // search in each direction that does not contain a pipe loop space // if any direction leads outside the pipe loop, this space cannot be interior return Direction.values() .map { it.nextPosition(row, col) } .filter { it !in pipeLoop && it !in path } .any { (r,c) -> canAccessOutsideOfGrid(r, c, grid, pipeLoop, memoOpen, path) } } override fun warmup(input: List<List<Char>>) { part2(input) } } enum class Direction { NORTH, EAST, SOUTH, WEST; fun opposite(): Direction { return when(this) { NORTH -> SOUTH EAST -> WEST SOUTH -> NORTH WEST -> EAST } } fun nextPosition(row: Int, col: Int): Pair<Int,Int> { return when (this) { NORTH -> Pair(row - 1, col) SOUTH -> Pair(row + 1, col) EAST -> Pair(row, col + 1) WEST -> Pair(row, col - 1) } } } data class PathCost(val location: Pair<Int,Int>, val cost: Int) fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day10().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
8,786
advent2023
The Unlicense
src/Day11.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
fun main() { fun parseOperation(operationLine: String): (Long) -> Long { val operationString = operationLine.trim().replace("Operation: new = old ", "") val operand = operationString.split(" ")[0] val numberString = operationString.split(" ")[1] if (numberString == "old") { if (operand == "+") { return { worryLevel: Long -> worryLevel + worryLevel } } else { return { worryLevel: Long -> worryLevel * worryLevel } } } else { val number = numberString.toLong() if (operand == "+") { return { worryLevel: Long -> worryLevel + number } } else { return { worryLevel: Long -> worryLevel * number } } } } fun parseMonkeys(input: List<String>): List<Monkey> { return input.chunked(7).map { monkeyLines -> val monkeyNumber = monkeyLines[0].trim().split(" ")[1].replace(":", "").toInt() val startingItems = monkeyLines[1].trim().replace("Starting items: ", "").split(", ").map { it.toLong() } val operation = parseOperation(monkeyLines[2]) val testNumber = monkeyLines[3].trim().replace("Test: divisible by ", "").toLong() val test = { worryLevel: Long -> worryLevel % testNumber == 0L } val ifTrueTarget = monkeyLines[4].trim().replace("If true: throw to monkey ", "").toInt() val ifFalseTarget = monkeyLines[5].trim().replace("If false: throw to monkey ", "").toInt() Monkey( monkeyNumber, startingItems.toMutableList(), operation, test, ifTrueTarget, ifFalseTarget, itemsInspected = 0L, ifTrueDivsionNumber = testNumber ) } } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) repeat(20) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.itemsInspected++ val newWorryLevel = monkey.operation(item) / 3L val test = monkey.test(newWorryLevel) val target = if (test) { monkey.ifTrueTarget } else { monkey.ifFalseTarget } monkeys[target].items.add(newWorryLevel) } monkey.items.clear() } } return monkeys.map { it.itemsInspected }.sortedDescending().take(2).reduce { a, b -> a * b } } // fun reduceWorryLevel(worryLevel: Long): Long { // var newWorryLevel = worryLevel // if(worryLevel % 2 == 0L && (worryLevel / 2) % 2 == 0L) { // do { // newWorryLevel /= 2 // } while (newWorryLevel % 2 == 0L && (newWorryLevel / 2) == 0L) // } // if(worryLevel % 3 == 0L && (worryLevel / 3) % 3 == 0L) { // do { // newWorryLevel /= 3 // } while (newWorryLevel % 3 == 0L && (newWorryLevel / 3) == 0L) // } // if(worryLevel % 5 == 0L && (worryLevel / 5) % 5 == 0L) { // do { // newWorryLevel /= 5 // } while (newWorryLevel % 5 == 0L && (newWorryLevel / 5) == 0L) // } // if(worryLevel % 7 == 0L && (worryLevel / 7) % 7 == 0L) { // do { // newWorryLevel /= 7 // } while (newWorryLevel % 7 == 0L && (newWorryLevel / 7) == 0L) // } // return newWorryLevel // } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) val commonDivisor = monkeys.map { it.ifTrueDivsionNumber }.reduce { acc, l -> acc * l } var round = 0 repeat(10000) { round++ monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.itemsInspected++ var newWorryLevel = monkey.operation(item) val test = monkey.test(newWorryLevel) val target = if (test) { monkey.ifTrueTarget } else { monkey.ifFalseTarget } newWorryLevel = newWorryLevel % commonDivisor monkeys[target].items.add(newWorryLevel) } monkey.items.clear() } } return monkeys.map { it.itemsInspected }.sortedDescending().take(2).reduce { a, b -> a * b } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) println("Check 1 passed") check(part2(testInput) == 2713310158L) println("Check 2 passed") val input = readInput("Day11") println(part1(input)) println(part2(input)) } data class Monkey( val number: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val test: (Long) -> Boolean, val ifTrueTarget: Int, val ifFalseTarget: Int, var itemsInspected: Long = 0L, val ifTrueDivsionNumber: Long )
0
Kotlin
0
1
3c7e46ddfb933281be34e58933b84870c6607acd
5,281
advent-of-code-2022
Apache License 2.0
src/Utils.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
import java.io.File import java.math.BigInteger import java.security.MessageDigest import kotlin.math.abs typealias Matrix = Array<IntArray> typealias BooleanMatrix = Array<BooleanArray> typealias Int3DMatrix = Array<Array<IntArray>> typealias Boolean3DMatrix = Array<Array<BooleanArray>> /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') operator fun IntRange.contains(other: IntRange): Boolean = first <= other.first && other.last <= last val IntRange.size get() = abs(this.last - this.first) + 1 data class XY(val x: Int, val y: Int) data class MutableXY(var x: Int, var y: Int) { fun toXY() = XY(x = x, y = y) } data class IJ(val i: Int, val j: Int) data class MutableIJ(var i: Int, var j: Int) { fun toIJ() = IJ(i = i, j = j) } fun BooleanMatrix.deepCopyOf(): BooleanMatrix = Array(this.size) { i -> this[i].copyOf() } data class Item(val steps: Int, val ij: IJ) : Comparable<Item> { override fun compareTo(other: Item): Int { return this.steps - other.steps } } /** * Create all possible combinations from the list's elements */ fun <T> List<T>.allCombinations(): List<List<T>> { val results = mutableListOf<List<T>>() repeat(this.size + 1) { count -> combine(data = ArrayList(count), results, start = 0, index = 0, count = count) } return results } /** * Create all possible combinations with size "count " from the list's elements * @param count - count of the elements in each combination */ fun <T> List<T>.combinations(count: Int): List<List<T>> { val results = mutableListOf<List<T>>() combine(data = ArrayList(count), results, start = 0, index = 0, count = count) return results } private fun <T> List<T>.combine( data: ArrayList<T>, results: MutableList<List<T>>, start: Int, index: Int, count: Int, ) { // Current combination is ready to be added to the result if (index == count) { results.add(ArrayList(data)) return } // replace index with all possible elements. The condition // "this.lastIndex - i + 1 >= (count - 1) - index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions var i = start while (i <= this.lastIndex && (this.lastIndex - i + 1 >= (count - 1) - index)) { if (data.lastIndex < index) { data.add(this[i]) } else { data[index] = this[i] } combine(data, results, start = i + 1, index = index + 1, count = count) i++ } }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
2,798
AOC2022
Apache License 2.0
src/day5/Day05.kt
omarshaarawi
573,867,009
false
{"Kotlin": 9725}
package day5 import java.io.File data class Operation(val move: Int, val from: Int, val to: Int) fun main() { val charMatch = """\[(\w)\]""".toRegex() val moveMatch = """move (\w+) from (\w) to (\w)""".toRegex() fun parseStack(stacks: String) = stacks.split("\n") .reversed() .asSequence() .drop(1) .map { line -> line.chunked(4).map { charMatch.find(it)?.groups?.get(1)?.value } } .map { it.mapIndexedNotNull { index, item -> if (item != null) { Pair(index + 1, item) } else { null } } }.flatten() .groupBy { it.first } .mapValues { mapItem -> mapItem.value.map { it.second }.toMutableList() } .toMutableMap() fun parseOperations(operations: String) = operations.split("\n").mapNotNull { val (number, startColumn, endColumn) = moveMatch.find(it)!!.destructured Operation(number.toInt(), startColumn.toInt(), endColumn.toInt()) } fun part1(): String { val data = File("src/day5/Day05.txt").readText() val (stacks, operations) = data.split("\n\n") val parsedStack = parseStack(stacks) val parsedOperations = parseOperations(operations) parsedOperations.forEach { operation -> val objToMove = (1..operation.move).map { parsedStack[operation.from]!!.removeLast() } parsedStack[operation.to]!!.addAll(objToMove) } return parsedStack.mapNotNull { it.value.lastOrNull() }.joinToString("") } fun part2(): String { val data = File("src/day5/Day05.txt").readText() val (stacks, operations) = data.split("\n\n") val parsedStack = parseStack(stacks) val parsedOperations = parseOperations(operations) parsedOperations.forEach { operation -> val objToMove = (1..operation.move).map { parsedStack[operation.from]!!.removeLast() }.reversed() parsedStack[operation.to]!!.addAll(objToMove) } return parsedStack.mapNotNull { it.value.lastOrNull() }.joinToString("") } println(part1()) println(part2()) }
0
Kotlin
0
0
4347548045f12793a8693c4d31fe3d3dade5100a
2,277
advent-of-code-kotlin-2022
Apache License 2.0
src/Year2022Day05.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
import java.util.Stack fun main() { fun handle(input: List<String>, handler: (Array<Stack<Char>>, Int, Int, Int) -> Unit): String { val borderLine = input.indexOf("") val stacks = Array<Stack<Char>>(input[borderLine - 1].count { it.isDigit() } + 1) { Stack() } for ((colIndex, value) in input[borderLine - 1].withIndex().filter { it.value.isDigit() }) { val id = value.digitToInt() for (rowIndex in borderLine - 1 downTo 0) { input[rowIndex][colIndex] .takeIf { it.isUpperCase() } ?.run(stacks[id]::push) } } val re = Regex("move (\\d+) from (\\d+) to (\\d+)") for (i in borderLine + 1 until input.size) { val result = re.find(input[i])!! val (num, from, to) = result.groupValues .withIndex().filter { it.index > 0 }.map { it.value.toInt() } handler(stacks, num, from, to) } return stacks.filter { it.isNotEmpty() }.map { it.peek() }.joinToString("") } fun part1(input: List<String>): String { return handle(input) { stacks, num, from, to -> repeat(num) { stacks[to].push(stacks[from].pop()) } } } fun part2(input: List<String>): String { val tempStack = Stack<Char>() return handle(input) { stacks, num, from, to -> repeat(num) { tempStack.push(stacks[from].pop()) } repeat(num) { stacks[to].push(tempStack.pop()) } } } val testLines = readLines(true) check(part1(testLines) == "CMZ") check(part2(testLines) == "MCD") val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
1,812
aoc-2022-in-kotlin
Apache License 2.0
day14/src/main/kotlin/Day14.kt
bzabor
160,240,195
false
null
class Day14(private val input: List<String>) { val recipeMin = 607331 val recipies = mutableListOf(3, 7) var elf1Index = 0 var elf2Index = 1 var tryCount = 1 fun part1(): Int { while (recipies.size <= recipeMin + 10) { tryCount++ recipies.addAll(nextRecipes()) elf1Index = updateElfIndex(elf1Index) elf2Index = updateElfIndex(elf2Index) } val result = recipies.slice(recipeMin..recipeMin + 9) println("") println(result) println("") print("After $recipeMin recipies: ") result.forEach { print(it) } println("") return 0 } // To create new recipes, the two Elves combine their current recipes. This creates new recipes from the // digits of the sum of the current recipes' scores. With the current recipes' scores of 3 and 7, their // sum is 10, and so two new recipes would be created: the first with score 1 and the second with score 0. // If the current recipes' scores were 2 and 3, the sum, 5, would only create one recipe // (with a score of 5) with its single digit. private fun nextRecipes(): List<Int> { return (recipies[elf1Index] + recipies[elf2Index]).toString().toList().map { Integer.parseInt(it.toString()) } } // To do this, the Elf steps forward through the scoreboard a number of recipes equal to 1 plus the score // of their current recipe. So, after the first round, the first Elf moves forward 1 + 3 = 4 times, while // the second Elf moves forward 1 + 7 = 8 times. If they run out of recipes, they loop back around to the // beginning. private fun updateElfIndex(elfIndex: Int): Int { val recipeVal = recipies[elfIndex] var newIndex = elfIndex + recipeVal + 1 if (newIndex > recipies.lastIndex) { newIndex = newIndex % recipies.size } return newIndex } private fun printRecipies() { println("") recipies.withIndex().forEach { (idx, int) -> print( when (idx) { elf1Index -> "(${int})" elf2Index -> "[${int}]" else -> " $int " }) } } val testString = "607331" var baseRemove = 607000 fun part2(): Int { while (getFirstIndexOf(testString) < 0 && tryCount < 30000000) { tryCount++ if (tryCount % 1000 == 0) println("tryCount: $tryCount recipe length: ${recipies.size} + baseRemove: $baseRemove") val nextRecipies = nextRecipes() baseRemove += nextRecipies.size recipies.addAll(nextRecipies) elf1Index = updateElfIndex(elf1Index) elf2Index = updateElfIndex(elf2Index) } println("First index of $testString is ${getFirstIndexOf(testString) + baseRemove}") return 0 } private fun getFirstIndexOf(s: String): Int { val recipeString = recipies.drop(baseRemove).joinToString(separator = "") return recipeString.indexOf(testString) } }
0
Kotlin
0
0
14382957d43a250886e264a01dd199c5b3e60edb
3,166
AdventOfCode2018
Apache License 2.0
src/main/kotlin/com/github/dangerground/aoc2020/Day20.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput import com.github.dangerground.aoc2020.util.World fun main() { val process = Day20(DayInput.batchesOfStringList(20)) println("result part 1: ${process.part1()}") println("result part 2: ${process.part2()}") } class Day20(val input: List<List<String>>) { val tiles = input.map { tileNum(it[0]) to World(it.drop(1).toMutableList()) }.toMap() val tileNeighbours = tiles.map { it.key to 0 }.toMap().toMutableMap() val options = tiles.mapValues { listOf( it.value, it.value.rotateLeft(), it.value.rotateLeft().rotateLeft(), it.value.rotateLeft().rotateLeft().rotateLeft(), it.value.flip(), it.value.rotateLeft().flip(), it.value.rotateLeft().rotateLeft().flip(), it.value.rotateLeft().rotateLeft().flip().rotateLeft().flip() ) } val relations = tiles.mapValues { Information() } //01234567890123456789 // # //# ## ## ### // # # # # # # val seamonster = listOf( Pair(0, 19), Pair(1, 0), Pair(1, 5), Pair(1, 6), Pair(1, 11), Pair(1, 12), Pair(1, 17), Pair(1, 18), Pair(1, 19), Pair(2, 1), Pair(2, 4), Pair(2, 7), Pair(2, 10), Pair(2, 13), Pair(2, 16) ) private fun tileNum(txt: String) = txt.replace("[^0-9]".toRegex(), "").toLong() fun part1(): Long { val tileNeighbours = tiles.map { it.key to 0 }.toMap().toMutableMap() for ((t1, w1Opts) in options) { for ((t2, w2Opts) in options) { if (t1 == t2) { continue } next@ for (w1 in w1Opts) { for (w2 in w2Opts) { val matchingEdge = matchingEdge(w1, w2) if (matchingEdge != null) { //println(">--------------Found (${t1} / ${t2} / $matchingEdge)------------------>") tileNeighbours[t1] = tileNeighbours[t1]!! + 1 break@next } } } } } return tileNeighbours.filter { it.value == 2 }.map { it.key }.reduce { i1, i2 -> i1 * i2 } } fun matchingEdge(w1: World, w2: World): Side? { // match right var matching = true for (r in 0 until w1.getRowCount()) { if (w1.getCell(r, 0) != w2.getCell(r, w2.getColumnCount() - 1)) { matching = false break } } if (matching) { return Side.LEFT } // match left matching = true for (r in 0 until w1.getRowCount()) { if (w2.getCell(r, 0) != w1.getCell(r, w1.getColumnCount() - 1)) { matching = false break } } if (matching) { return Side.RIGHT } // match top matching = true for (c in 0 until w1.getRowCount()) { if (w2.getCell(0, c) != w1.getCell(w2.getRowCount() - 1, c)) { matching = false break } } if (matching) { return Side.TOP } // match bottom matching = true for (c in 0 until w1.getRowCount()) { if (w1.getCell(0, c) != w2.getCell(w2.getRowCount() - 1, c)) { matching = false break } } if (matching) { return Side.BOTTOM } return null } fun part2(): Int { calculateRelationships() println(relations) val coord = getPositions() //println(coord) val matrix = mutableMapOf<Int, MutableMap<Int, Long>>() coord.map { it.value.second }.forEach { matrix[it] = mutableMapOf() } val filled = matrix.map { (row, _)-> row to coord.filter { it.value.second == row }.map { Pair(it.value.first, it.key) }.toMap().toMutableMap()} // println(coord) // debug print table filled.forEach { println() it.second.forEach { print(" ${it.value} ") } } return -1 } private fun getPositions(): MutableMap<Long, Pair<Int, Int>> { val remainingKeys = tiles.keys.toMutableList() val coord = mutableMapOf<Long, Pair<Int, Int>>() coord[remainingKeys[0]] = Pair(0, 0) remainingKeys.removeAt(0) println(remainingKeys) /* val pos = mutableMapOf<Int, MutableMap<Int, Long>>() pos[0] = mutableMapOf(0 to remainingKeys[0]) */ while (!remainingKeys.isEmpty()) { val tileNum = remainingKeys.random() //println("$tileNum -> $coord") val relation = relations[tileNum]!! coord.toList().forEach { (tile, c) -> if (tile == relation.right) { //println(" Right ") coord[tileNum] = Pair(c.first - 1, c.second) remainingKeys.remove(tileNum) } else if (tile == relation.left) { // println(" Left ") coord[tileNum] = Pair(c.first + 1, c.second) remainingKeys.remove(tileNum) } else if (tile == relation.top) { //println(" Top ") coord[tileNum] = Pair(c.first, c.second + 1) remainingKeys.remove(tileNum) } else if (tile == relation.bottom) { //println(" Bottom ") coord[tileNum] = Pair(c.first, c.second - 1) remainingKeys.remove(tileNum) } else { return@forEach } } } return coord } private fun calculateRelationships() { for ((t1, w1Opts) in options) { for ((t2, w2Opts) in options) { if (t1 == t2) { continue } next@ for (w1 in w1Opts) { for (w2 in w2Opts) { val matchingEdge = matchingEdge(w1, w2) if (matchingEdge != null) { when (matchingEdge) { Side.TOP -> { relations[t1]!!.top = t2 //relations[t2]!!.bottom = t1 } Side.BOTTOM -> { relations[t1]!!.bottom = t2 //relations[t2]!!.top = t1 } Side.LEFT -> { relations[t1]!!.left = t2 //relations[t2]!!.right = t1 } Side.RIGHT -> { relations[t1]!!.right = t2 //relations[t2]!!.left = t1 } else -> { } } println(">--------------Found (${t1} / ${t2} / $matchingEdge)------------------>") tileNeighbours[t1] = tileNeighbours[t1]!! + 1 break@next } } } } } println("neighbours") println(tileNeighbours) } } class Information { var left: Long? = null var right: Long? = null var top: Long? = null var bottom: Long? = null override fun toString(): String { return "Information(left=$left, right=$right, top=$top, bottom=$bottom)" } } enum class Side { TOP, LEFT, BOTTOM, RIGHT }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
8,133
adventofcode-2020
MIT License
LeetCode/0789. Escape The Ghosts/Solution.kt
InnoFang
86,413,001
false
{"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410}
/** * 40 / 40 test cases passed. * Status: Accepted * Runtime: 256 ms */ class Solution { fun escapeGhosts(ghosts: Array<IntArray>, target: IntArray): Boolean { val distance = fun(x: Int, y: Int) = Math.abs(x - target[0]) + Math.abs(y - target[1]) val d = distance(0, 0) ghosts.forEach { if (distance(it[0], it[1]) <= d) return false } return true } } /** * 40 / 40 test cases passed. * Status: Accepted * Runtime: 328 ms */ class Solution2 { fun escapeGhosts(ghosts: Array<IntArray>, target: IntArray): Boolean { // val distance = fun(g: IntArray) = target.zip(g, { x1, x2 -> Math.abs(x1 + x2) }).sum() val distance = fun(g: IntArray) = (0..1).sumBy { Math.abs(g[it] - target[it]) } val d = target.sumBy(Math::abs) ghosts.forEach { if (distance(it) <= d) return false } return true } } fun main(args: Array<String>) { Solution().escapeGhosts(arrayOf( intArrayOf(1, 0), intArrayOf(0, 3) ), intArrayOf(0, 1)).let(::println) }
0
C++
8
20
2419a7d720bea1fd6ff3b75c38342a0ace18b205
1,055
algo-set
Apache License 2.0
Problems/Algorithms/1162. As Far from Land as Possible/FarLand.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun maxDistance(grid: Array<IntArray>): Int { val n = grid.size val m = grid[0].size val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) val visited = Array(n) { BooleanArray(m) { false } } val queue = ArrayDeque<Pair<Int, Int>>() for (r in 0..n-1) { for (c in 0..m-1) { if (grid[r][c] == 1) { queue.add(Pair(r, c)) } } } var ans = -1 while (!queue.isEmpty()){ for (i in 1..queue.size) { val curr = queue.removeFirst() val x = curr.first val y = curr.second for (neighbor in neighbors) { val r = x + neighbor[0] val c = y + neighbor[1] if (isValid(n, m, r, c) && !visited[r][c] && grid[r][c] == 0) { visited[r][c] = true queue.add(Pair(r, c)) } } } ans++ } if (ans <= 0) return -1 return ans } private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean { return r >= 0 && r < n && c >= 0 && c < m } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,386
leet-code
MIT License
src/com/ncorti/aoc2023/Day15.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 fun main() { fun String.computeHash(): Int { var current = 0 toCharArray().forEach { current += it.toInt() current *= 17 current %= 256 } return current } fun parseInput() = getInputAsText("15") { split(",").filter(String::isNotBlank).map { it.trim() } } fun computeFocalLength(boxes: MutableMap<Int, MutableList<Pair<String, Int>>>): Long { var total = 0L boxes.forEach { (index, list) -> list.forEachIndexed { listIndex, (label, value) -> total += (index + 1) * (listIndex + 1) * value } } return total } fun part1(): Int = parseInput().sumOf { it.computeHash() } fun part2(): Long { val input = parseInput() val boxes = mutableMapOf<Int, MutableList<Pair<String, Int>>>() repeat(256) { boxes[it] = mutableListOf() } input.forEach { val label = it.substringBefore("-").substringBefore("=") val box = boxes[label.computeHash()]!! when { "=" in it -> { val value = it.substringAfter("=").toInt() val existingLensIdx = box.indexOfFirst { it.first == label } if (existingLensIdx != -1) { box[existingLensIdx] = label to value } else { box.add(label to value) } } "-" in it -> { box.firstOrNull { it.first == label }?.let { box.remove(it) } } } } return computeFocalLength(boxes) } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
1,834
adventofcode-2023
MIT License
src/Day02a.kt
palex65
572,937,600
false
{"Kotlin": 68582}
fun calc(o: Int, r: Int): Int = r + 1 + when(r - o) { -2,1 -> 6 // Win 2,-1 -> 0 // Lose else /*0*/ -> 3 // Draw } fun part1a(lines: List<String>): Int = lines.sumOf { calc(it[0] - 'A', it[2] - 'X') } fun part2a(lines: List<String>): Int = lines.sumOf { val o = it[0] - 'A' calc(o, when (it[2]) { 'X' -> (o + 2) % 3 'Z' -> (o + 1) % 3 else /*'Y'*/ -> 0 } ) } fun main() { val testInput = readInput("Day02_test") check(part1a(testInput) == 15) check(part2a(testInput) == 12) val input = readInput("Day02") println(part1a(input)) // 14375 println(part2a(input)) // 10274 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
673
aoc2022
Apache License 2.0
solutions/aockt/y2022/Y2022D14.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2022 import aockt.y2022.Y2022D14.FallingSandSimulation.* import io.github.jadarma.aockt.core.Solution object Y2022D14 : Solution { /** Represents a discrete point in 2D space. */ private data class Point(val x: Int, val y: Int) /** Simulates a potentially infinite grid of [Cell]s. If [maxDepth] is specified, an infinite wall is spawned. */ private class FallingSandSimulation(private val maxDepth: Int? = null) { /** The possible cell types in the simulation. */ enum class Cell { Empty, Wall, Sand } private val cells: MutableMap<Int, MutableMap<Int, Cell>> = mutableMapOf() /** Get the [Cell] value in the simulation at this [point]. */ operator fun get(point: Point): Cell = cells .getOrElse(point.x) { emptyMap() } .getOrDefault(point.y, if (maxDepth != null && point.y == maxDepth) Cell.Wall else Cell.Empty) /** Update the contents at this [point] in the simulation with the new [cell] value. */ operator fun set(point: Point, cell: Cell) = cells.getOrPut(point.x) { mutableMapOf() }.apply { if (cell == Cell.Empty) { remove(point.y) if (isEmpty()) cells.remove(point.x) } else put(point.y, cell) } /** Draw an orthogonal, straight line wall from [a] to [b], overriding any existing cells. */ fun drawWall(a: Point, b: Point) { when { a.x == b.x -> (minOf(a.y, b.y)..maxOf(a.y, b.y)).forEach { y -> this[Point(a.x, y)] = Cell.Wall } a.y == b.y -> (minOf(a.x, b.x)..maxOf(a.x, b.x)).forEach { x -> this[Point(x, a.y)] = Cell.Wall } else -> throw IllegalArgumentException("Wall lines may only have 90 degree turns.") } } /** Draw a complex [line] defined by these points. */ fun drawWall(line: List<Point>) = line.windowed(2).forEach { (a, b) -> drawWall(a, b) } /** * Spawn a [Cell.Sand] cell at the given [point] and let it fall. * The cell on which it spawns is overwritten if not empty. * Returns the final resting position of the cell, or null if it goes out of bounds. */ fun dropAndSet(point: Point): Point? { this[point] = Cell.Empty var p = point while (maxDepth != null || cells.getOrDefault(p.x, emptyMap()).any { (k, _) -> k > p.y }) { val below = p.copy(y = p.y + 1) val left = p.copy(x = p.x - 1, y = p.y + 1) val right = p.copy(x = p.x + 1, y = p.y + 1) when (Cell.Empty) { this[below] -> p = below this[left] -> p = left this[right] -> p = right else -> { this[p] = Cell.Sand return p } } } return null } } /** Parse the input and return the list of lines. */ private fun parseInput(input: String): Sequence<List<Point>> = input .lineSequence() .map { line -> line.split(" -> ").flatMap { it.split(',') } } .map { it.map(String::toInt).chunked(2) { (a, b) -> Point(a, b) } } override fun partOne(input: String): Any { val dropPoint = Point(500, 0) val sim = FallingSandSimulation().apply { parseInput(input).forEach(::drawWall) } (0..Int.MAX_VALUE).forEach { iteration -> if (sim.dropAndSet(dropPoint) == null) return iteration } return -1 } override fun partTwo(input: String): Any { val dropPoint = Point(500, 0) val lines = parseInput(input) val sim = FallingSandSimulation(maxDepth = lines.flatten().maxOf { it.y } + 2) .apply { lines.forEach(::drawWall) } (1..Int.MAX_VALUE).forEach { iteration -> sim.dropAndSet(dropPoint) ?: error("Didn't hit the bottom of an infinite floor.") if (sim[dropPoint] == Cell.Sand) return iteration } return -1 } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,156
advent-of-code-kotlin-solutions
The Unlicense
src/Day04.kt
oleksandrbalan
572,863,834
false
{"Kotlin": 27338}
fun main() { val input = readInput("Day04") .filterNot { it.isEmpty() } .map { val (elf1, elf2) = it.split(",") elf1.range to elf2.range } val part1 = input.count { (range1, range2) -> range1.contains(range2) || range2.contains(range1) } println("Part1: $part1") val part2 = input.count { (range1, range2) -> range1.first in range2 || range2.first in range1 } println("Part2: $part2") } private val String.range: IntRange get() = split("-") .map { it.toInt() } .let { it[0]..it[1] } private fun IntRange.contains(other: IntRange): Boolean = first <= other.first && last >= other.last
0
Kotlin
0
2
1493b9752ea4e3db8164edc2dc899f73146eeb50
709
advent-of-code-2022
Apache License 2.0
src/day08/Day08.kt
schrami8
572,631,109
false
{"Kotlin": 18696}
package day08 import readInput fun visibleFromLeft(line: ArrayList<Int>, index: Int): Boolean { for (i in 0 until index) { if (line[i] >= line[index]) return false } return true } fun visibleFromRight(line: ArrayList<Int>, index: Int): Boolean { for (i in index + 1 until line.size) { if (line[i] >= line[index]) return false } return true } fun visibleFromTop(column: ArrayList<ArrayList<Int>>, columnIndex: Int, index: Int): Boolean { for (i in 0 until index) { if (column[i][columnIndex] >= column[index][columnIndex]) return false } return true } fun visibleFromBottom(column: ArrayList<ArrayList<Int>>, columnIndex: Int, index: Int): Boolean { for (i in index + 1 until column.size) { if (column[i][columnIndex] >= column[index][columnIndex]) return false } return true } fun visibleFromLeftCnt(line: ArrayList<Int>, index: Int): Int { var treesCnt = 0 for (i in index - 1 downTo 0) { treesCnt += 1 if (line[i] >= line[index]) break } return treesCnt } fun visibleFromRightCnt(line: ArrayList<Int>, index: Int): Int { var treesCnt = 0 for (i in index + 1 until line.size) { treesCnt += 1 if (line[i] >= line[index]) break } return treesCnt } fun visibleFromTopCnt(column: ArrayList<ArrayList<Int>>, columnIndex: Int, index: Int): Int { var treesCnt = 0 for (i in index - 1 downTo 0) { treesCnt += 1 if (column[i][columnIndex] >= column[index][columnIndex]) break } return treesCnt } fun visibleFromBottomCnt(column: ArrayList<ArrayList<Int>>, columnIndex: Int, index: Int): Int { var treesCnt = 0 for (i in index + 1 until column.size) { treesCnt += 1 if (column[i][columnIndex] >= column[index][columnIndex]) break } return treesCnt } fun getTrees2D(input: List<String>): ArrayList<ArrayList<Int>> { val trees: ArrayList<ArrayList<Int>> = ArrayList(input.size) for (line in input.indices) { trees.add(ArrayList(input[line].length)) for (i in input[line]) { trees[line].add(i.digitToInt()) } } return trees } fun main() { fun part1(input: List<String>): Int { val trees: ArrayList<ArrayList<Int>> = getTrees2D(input) var visibleTrees = (2 * input.size + 2 * input[0].length) - 4 // border for (i in trees.indices) { if (i == 0 || i == trees[i].size - 1) continue for (j in trees[i].indices) { if (j == 0 || j == trees[i].size - 1) continue if (visibleFromLeft(trees[i], j) || visibleFromRight(trees[i], j) || visibleFromTop(trees, j, i) || visibleFromBottom(trees, j, i)) ++visibleTrees } } return visibleTrees } fun part2(input: List<String>): Int { val trees: ArrayList<ArrayList<Int>> = getTrees2D(input) var mostVisibleTrees = 0 for (i in trees.indices) { for (j in trees[i].indices) { var tmpVisible = visibleFromLeftCnt(trees[i], j) tmpVisible *= visibleFromRightCnt(trees[i], j) tmpVisible *= visibleFromTopCnt(trees, j, i) tmpVisible *= visibleFromBottomCnt(trees, j, i) if (mostVisibleTrees < tmpVisible) mostVisibleTrees = tmpVisible } } return mostVisibleTrees } // test if implementation meets criteria from the description, like: val testInput = readInput("day08/Day08_test") check(part1(testInput) == 21) val input = readInput("day08/Day08") println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
215f89d7cd894ce58244f27e8f756af28420fc94
3,896
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2023/day18/day18Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day18 import lib.* import lib.twoDimensional.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<List<Instruction>> { return setup { day(18) year(2023) //input("example.txt") parser { it.readLines() .map { val parts = it.split(" ") Instruction( charToDirection[parts[0][0]]!!, parts[1].toInt(), parts[2].replace("(", "").replace(")", "") ) } } partOne { var currentPos = Point(0, 0) val lines = mutableListOf<Line>() it.forEach { val newPos = currentPos + (it.direction.movementDelta() * it.dist.toLong()) lines.add(Line(currentPos, newPos)) currentPos = newPos } val inside = mutableListOf<LongRange>() val horizontalLines = lines.filter { it.from.x != it.to.x } val verticalLines = lines.filter { it.from.y != it.to.y } horizontalLines.filter { it.from.cardinalDirectionTo(it.to) == CardinalDirection.East }.forEach { val start = it.from.y val otherLines = horizontalLines.filter { it.from.y > start } (it.from.x .. it.to.x).forEach { x -> val limit = otherLines.filter { (minOf(it.from.x, it.to.x)..maxOf(it.from.x, it.to.x)).contains(x) } .minOfOrNull { it.from.y } if (limit != null) { val candidate = start + 1 until limit if(verticalLines.none { it.from.x == x && candidate.intersects(minOf(it.from.y, it.to.y)..maxOf(it.from.y, it.to.y)) }) { inside.add(start + 1 until limit) } } } } (inside.sumOf { it.size() } + lines.sumOf { it.size() } - lines.count() ).toString() } partTwo { val realInstructions = it.map { Instruction(hexDigitToDirection[it.color.last()]!!, it.color.drop(1).dropLast(1).toInt(16), it.color) } var currentPos = Point(0, 0) val lines = mutableListOf<Line>() realInstructions.forEach { val newPos = currentPos + (it.direction.movementDelta() * it.dist.toLong()) lines.add(Line(currentPos, newPos)) currentPos = newPos } val inside = mutableListOf<LongRange>() val horizontalLines = lines.filter { it.from.x != it.to.x } val verticalLines = lines.filter { it.from.y != it.to.y } horizontalLines.filter { it.from.cardinalDirectionTo(it.to) == CardinalDirection.East }.forEach { val start = it.from.y val otherLines = horizontalLines.filter { it.from.y > start } (it.from.x .. it.to.x).forEach { x -> val limit = otherLines.filter { (minOf(it.from.x, it.to.x)..maxOf(it.from.x, it.to.x)).contains(x) } .minOfOrNull { it.from.y } if (limit != null) { val candidate = start + 1 until limit if(verticalLines.none { it.from.x == x && candidate.intersects(minOf(it.from.y, it.to.y)..maxOf(it.from.y, it.to.y)) }) { inside.add(start + 1 until limit) } } } } (inside.sumOf { it.size() } + lines.sumOf { it.size() } - lines.count() ).toString() } } } val charToDirection = mapOf('U' to CardinalDirection.North, 'D' to CardinalDirection.South, 'L' to CardinalDirection.West, 'R' to CardinalDirection.East) val hexDigitToDirection = mapOf('0' to CardinalDirection.East, '1' to CardinalDirection.South, '2' to CardinalDirection.West, '3' to CardinalDirection.North) data class Instruction(val direction: CardinalDirection, val dist: Int, val color: String)
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
4,236
AoC-2023-DDJ
MIT License
src/Day04.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
fun main() { val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return input.map(::parseLine) .count { (first, second) -> first in second || second in first } } private fun part2(input: List<String>): Int { return input.map(::parseLine) .count { (first, second) -> first overlaps second || second overlaps first } } private fun parseLine(line: String): Pair<IntRange, IntRange> { val (first, second) = line.split(",").map { val (start, end) = it.split("-") start.toInt()..end.toInt() } return first to second } private operator fun IntRange.contains(other: IntRange): Boolean { return start in other && endInclusive in other } private infix fun IntRange.overlaps(other: IntRange): Boolean { return start in other || endInclusive in other }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
999
aoc-22
Apache License 2.0
src/main/java/com/barneyb/aoc/aoc2016/day17/TwoStepsForward.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2016.day17 import com.barneyb.aoc.util.Solver import java.security.MessageDigest import java.util.* import kotlin.experimental.and const val WIDTH = 4 const val HEIGHT = 4 fun main() { Solver.execute( { it.trim() }, ::shortestPath, { longestPath(it).length }) } internal data class State( val x: Int, val y: Int, val passcode: String, val path: String = "" ) { companion object { fun start(passcode: String) = State(1, 1, passcode) } fun up() = copy(y = y - 1, path = path + "U") fun down() = copy(y = y + 1, path = path + "D") fun left() = copy(x = x - 1, path = path + "L") fun right() = copy(x = x + 1, path = path + "R") } fun shortestPath(passcode: String): String { val queue: Deque<State> = LinkedList() queue.add(State.start(passcode)) while (queue.isNotEmpty()) { val curr = queue.remove()!! if (curr.x == WIDTH && curr.y == HEIGHT) { return curr.path } queue.addAll(adjacent(curr)) } throw IllegalArgumentException("Passcode '$passcode' doesn't offer a path to the vault") } fun longestPath(passcode: String): String { val queue: Deque<State> = LinkedList() queue.add(State.start(passcode)) var longest = "" while (queue.isNotEmpty()) { val curr = queue.remove()!! if (curr.x == WIDTH && curr.y == HEIGHT) { if (curr.path.length > longest.length) { longest = curr.path } } else { queue.addAll(adjacent(curr)) } } if (longest.isEmpty()) { throw IllegalArgumentException("Passcode '$passcode' doesn't offer a path to the vault") } return longest } internal fun adjacent( curr: State, ): Collection<State> { val result = mutableListOf<State>() val doors = doors(curr.passcode, curr.path) //@formatter:off if (doors[0] && curr.y > 1 ) result.add(curr.up()) if (doors[1] && curr.y < HEIGHT) result.add(curr.down()) if (doors[2] && curr.x > 1 ) result.add(curr.left()) if (doors[3] && curr.x < WIDTH ) result.add(curr.right()) //@formatter:on return result } internal fun doors(passcode: String, path: String = ""): BooleanArray { val digest = MessageDigest.getInstance("MD5") digest.update(passcode.toByteArray()) digest.update(path.toByteArray()) val bytes = digest.digest() return booleanArrayOf( //@formatter:off bytes[0].rotateRight(4) and 0xf >= 0xb, bytes[0] and 0xf >= 0xb, bytes[1].rotateRight(4) and 0xf >= 0xb, bytes[1] and 0xf >= 0xb, //@formatter:on ) }
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
2,787
aoc-2022
MIT License
src/day08/Day08.kt
tobihein
569,448,315
false
{"Kotlin": 58721}
package day08 import readInput class Day08 { fun part1(): Int { val readInput = readInput("day08/input") return part1(readInput) } fun part2(): Int { val readInput = readInput("day08/input") return part2(readInput) } fun part1(input: List<String>): Int { val visibleTrees = mutableSetOf<Pair<Int, Int>>() val trees = toArray(input) for (row in 0 until input.size) { for (column in 0 until input.size) { if (isVisible(row, column, trees)) { visibleTrees.add(Pair(row, column)) } } } return visibleTrees.size } fun part2(input: List<String>): Int { val scenicScores = mutableSetOf<Int>() val trees = toArray(input) for (row in 0 until input.size) { for (column in 0 until input.size) { scenicScores.add(getScenicScore(row, column, trees)) } } return scenicScores.max() } private fun getScenicScore(row: Int, column: Int, trees: Array<IntArray>): Int { return scoreRight(row, column, trees) * scoreLeft(row, column, trees) * scoreAbove( row, column, trees ) * scoreBelow(row, column, trees) } private fun scoreRight(row: Int, column: Int, trees: Array<IntArray>): Int { var canSeeHeight = trees[row][column] - 1 var canSeeTrees = 0 var blocked = false for (i in column + 1 until trees.size) { val currentTree = trees[row][i] if (currentTree > canSeeHeight) { canSeeTrees++ canSeeHeight = currentTree + 1 blocked = true } else if (!blocked) { canSeeTrees++ } } return canSeeTrees } private fun scoreLeft(row: Int, column: Int, trees: Array<IntArray>): Int { var canSeeHeight = trees[row][column] - 1 var canSeeTrees = 0 var blocked = false for (i in column - 1 downTo 0) { val currentTree = trees[row][i] if (currentTree > canSeeHeight) { canSeeTrees++ canSeeHeight = currentTree + 1 blocked = true } else if (!blocked) { canSeeTrees++ } } return canSeeTrees } private fun scoreBelow(row: Int, column: Int, trees: Array<IntArray>): Int { var canSeeHeight = trees[row][column] - 1 var canSeeTrees = 0 var blocked = false for (i in row + 1 until trees.size) { val currentTree = trees[i][column] if (currentTree > canSeeHeight) { canSeeTrees++ canSeeHeight = currentTree + 1 blocked = true } else if (!blocked) { canSeeTrees++ } } return canSeeTrees } private fun scoreAbove(row: Int, column: Int, trees: Array<IntArray>): Int { var canSeeHeight = trees[row][column] - 1 var canSeeTrees = 0 var blocked = false for (i in row - 1 downTo 0) { val currentTree = trees[i][column] if (currentTree > canSeeHeight) { canSeeTrees++ canSeeHeight = currentTree + 1 blocked = true } else if (!blocked) { canSeeTrees++ } } return canSeeTrees } private fun isVisible(row: Int, column: Int, trees: Array<IntArray>): Boolean { return isVisibleFromLeft(row, column, trees) || isVisibleFromTop(row, column, trees) || isVisibleFromRight( row, column, trees ) || isVisibleFromBottom(row, column, trees) } private fun isVisibleFromLeft(row: Int, column: Int, trees: Array<IntArray>): Boolean { val currentTree = trees[row][column] for (i in 0 until column) { if (trees[row][i] >= currentTree) { return false } } return true } private fun isVisibleFromRight(row: Int, column: Int, trees: Array<IntArray>): Boolean { val currentTree = trees[row][column] for (i in trees[row].size - 1 downTo column + 1) { if (trees[row][i] >= currentTree) { return false } } return true } private fun isVisibleFromTop(row: Int, column: Int, trees: Array<IntArray>): Boolean { val currentTree = trees[row][column] for (i in 0 until row) { if (trees[i][column] >= currentTree) { return false } } return true } private fun isVisibleFromBottom(row: Int, column: Int, trees: Array<IntArray>): Boolean { val currentTree = trees[row][column] for (i in trees[row].size - 1 downTo row + 1) { if (trees[i][column] >= currentTree) { return false } } return true } private fun toArray(input: List<String>): Array<IntArray> { val rows = mutableListOf<IntArray>() for (trees in input) { rows.add(trees.toCharArray().map { it.digitToInt() }.toIntArray()) } return rows.toTypedArray() } }
0
Kotlin
0
0
af8d851702e633eb8ff4020011f762156bfc136b
5,369
adventofcode-2022
Apache License 2.0
2022/src/Day25.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src val snafu = mapOf("=" to -2, "-" to -1, "1" to 1, "2" to 2, "0" to 0) val snafuBack = mapOf(-2 to "=", -1 to "-", 1 to "1", 2 to "2", 0 to "0") fun main() { fun encoder(number: String): Long { // powers of five in reverse order val powersOf5 = generateSequence { 5 } .map { it.toLong() } .scan(1L) { acc, i -> acc * i } .take(number.length) .toList() .reversed() return number .map { snafu[it.toString()]!! } .mapIndexed { index, i -> i * powersOf5[index] } .sum() } fun decoder(number: Long): String { return if (number == 0L) "" else { if (number % 5 == 0L || number % 5 == 1L || number % 5 == 2L) { decoder(number / 5) + snafuBack[(number % 5).toInt()]!! } else { decoder(number / 5 + 1) + snafuBack[(number % 5 - 5).toInt()]!! } } } val input = readInput("input25") .map { it.trim() } .sumOf { encoder(it) } .also { println(it) } println(decoder(input)) }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
1,174
AoC
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MeetingRooms.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min fun interface MeetingRoomsStrategy { fun canAttendMeetings(intervals: Array<IntArray>): Boolean } class MeetingRoomsBruteForce : MeetingRoomsStrategy { override fun canAttendMeetings(intervals: Array<IntArray>): Boolean { val n = intervals.size for (i in 0 until n) { for (j in i + 1 until n) { if (overlap(intervals[i], intervals[j])) { return false } } } return true } private fun overlap(i1: IntArray, i2: IntArray): Boolean { return min(i1[1], i2[1]) > max(i1[0], i2[0]) } } class MeetingRoomsSorting : MeetingRoomsStrategy { override fun canAttendMeetings(intervals: Array<IntArray>): Boolean { intervals.sortWith { a, b -> a[0].compareTo(b[0]) } for (i in 0 until intervals.size - 1) { if (intervals[i][1] > intervals[i + 1][0]) { return false } } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,698
kotlab
Apache License 2.0
src/main/kotlin/apoy2k/aoc2023/problem1/Problem1.kt
ApoY2k
725,965,251
false
{"Kotlin": 2769}
package apoy2k.aoc2023.problem1 import apoy2k.aoc2023.readInput fun main() { println("Part 1: ${part1()}") println("Part 2: ${part2()}") } private fun part1() = solve(map.values.toSet()) private fun part2() = solve(map.keys + map.values) private fun solve(numbers: Set<String>) = readInput("problem1.txt") .sumOf { val first = it.findAnyOf(numbers)?.second?.toNumber() ?: error("no first digit for '$it'") val last = it.findLastAnyOf(numbers)?.second?.toNumber() ?: error("no last digit for '$it'") "$first$last".toInt() } private fun String.toNumber() = toIntOrNull() ?: map[this]?.toInt() ?: error("cannot convert '$this' to number") private val map = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9" )
0
Kotlin
0
0
4d428feac36813acb8541b69d6fb821669714882
880
aoc2023
The Unlicense
src/main/kotlin/adventofcode/year2022/Day05SupplyStacks.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2022 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.transpose class Day05SupplyStacks(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val stacks by lazy { val stackRows = input .split("\n\n") .first() .lines() .dropLast(1) .map { row -> row.filterIndexed { index, _ -> index % 4 == 1 }.toList() } .map { row -> row.map { if (it == ' ') null else it } } val stackCount = stackRows.last().size stackRows .map { row -> row + (1..stackCount - row.size).map { null } } .transpose() .map { stack -> stack.filterNotNull() } } private val procedure by lazy { input .split("\n\n") .last() .lines() .map { PROCEDURE_REGEX.find(it)!!.destructured } .map { (quantity, from, to) -> Triple(quantity.toInt(), from.toInt() - 1, to.toInt() - 1) } } private fun rearrangeStacks(moveMultipleCrates: Boolean = false) = procedure.fold(stacks) { stacks, (quantity, fromIndex, toIndex) -> val cratesToMove = stacks[fromIndex].takeLast(quantity) stacks.mapIndexed { index, stack -> when (index) { fromIndex -> stack.dropLast(quantity) toIndex -> stack + if (moveMultipleCrates) cratesToMove else cratesToMove.reversed() else -> stack } } } .map { stack -> stack.last() } .joinToString("") override fun partOne() = rearrangeStacks() override fun partTwo() = rearrangeStacks(moveMultipleCrates = true) companion object { private val PROCEDURE_REGEX = """move (\d+) from (\d+) to (\d+)""".toRegex() } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,880
AdventOfCode
MIT License
src/main/kotlin/org/tinygears/tinydiff/algorithm/MyersDiffAlgorithm.kt
TinyGearsOrg
561,403,042
false
{"Kotlin": 76143}
/* * Copyright (c) 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 org.tinygears.tinydiff.algorithm import org.tinygears.tinydiff.transform.Transformer import org.tinygears.tinydiff.transform.transform import java.util.* /** * This class allows to compare two objects sequences. * * The two sequences can hold any object type, as only the `equals` * method is used to compare the elements of the sequences. It is * guaranteed that the comparisons will always be done as `o1.equals(o2)` * where `o1` belongs to the first sequence and `o2` belongs to the * second sequence. This can be important if subclassing is used for some * elements in the first sequence and the `equals` method is specialized. * * Comparison can be seen from two points of view: either as giving the smallest * modification allowing to transform the first sequence into the second one, or * as giving the longest sequence which is a subsequence of both initial * sequences. The `equals` method is used to compare objects, so any * object can be put into sequences. Modifications include deleting, inserting * or keeping one object, starting from the beginning of the first sequence. * * This class implements the comparison algorithm, which is the very efficient * algorithm from <NAME> * * [An O(ND) Difference Algorithm and Its Variations](http://www.cis.upenn.edu/~bcpierce/courses/dd/papers/diff.ps). * * This algorithm produces the shortest possible [edit script][EditScript] containing * all the [commands][EditCommand] needed to transform the first sequence into the * second one. * * @see EditScript * @see EditCommand * @see CommandVisitor */ internal class MyersDiffAlgorithm<T> : DiffAlgorithm<T> { /** * Get the [EditScript] object. * @return the edit script resulting from the comparison of the two sequences */ override fun getEditScript(origSequence: List<T>, modifiedSequence: List<T>, vararg transformers: Transformer<T>): EditScript<T> { val context = if (transformers.isEmpty()) { Context(origSequence, modifiedSequence) } else { val origSequenceTransformed = origSequence .map { transform(it, *transformers) } val modifiedSequenceTransformed = modifiedSequence.map { transform(it, *transformers) } Context(origSequenceTransformed, modifiedSequenceTransformed, origSequence, modifiedSequence) } return context.buildScript() } private inner class Context constructor(val sequenceA: List<T>, val sequenceB: List<T>, val originalSequenceA: List<T> = sequenceA, val originalSequenceB: List<T> = sequenceB) { private val editScript: EditScript<T> = EditScript.empty() private val vDown: IntArray private val vUp: IntArray init { require(sequenceA.size == originalSequenceA.size) require(sequenceB.size == originalSequenceB.size) val size = sequenceA.size + sequenceB.size + 2 vDown = IntArray(size) vUp = IntArray(size) } /** * Build an edit script. */ fun buildScript(): EditScript<T> { buildScript(0, sequenceA.size, 0, sequenceB.size) return editScript } /** * Build a snake. * * @param start the value of the start of the snake * @param diag the value of the diagonal of the snake * @param end1 the value of the end of the first sequence to be compared * @param end2 the value of the end of the second sequence to be compared * @return the snake built */ private fun buildSnake(start: Int, diag: Int, end1: Int, end2: Int): Snake { var end = start while (end - diag < end2 && end < end1 && sequenceA[end] == sequenceB[end - diag]) { ++end } return Snake(start, end, diag) } /** * Get the middle snake corresponding to two subsequences of the main sequences. * * The snake is found using the MYERS Algorithm (this algorithm has * also been implemented in the GNU diff program). This algorithm is * explained in Eugene Myers article: * * [An O(ND) Difference Algorithm and Its Variations](http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps). * * @param start1 the beginning of the first sequence to be compared * @param end1 the end of the first sequence to be compared * @param start2 the beginning of the second sequence to be compared * @param end2 the end of the second sequence to be compared * @return the middle snake */ private fun getMiddleSnake(start1: Int, end1: Int, start2: Int, end2: Int): Snake? { // Myers Algorithm // Initialisations val m = end1 - start1 val n = end2 - start2 if (m == 0 || n == 0) { return null } val delta = m - n val sum = n + m val offset = (if (sum % 2 == 0) sum else sum + 1) / 2 vDown[1 + offset] = start1 vUp[1 + offset] = end1 + 1 for (d in 0..offset) { // Down var k = -d while (k <= d) { // First step val i = k + offset if (k == -d || k != d && vDown[i - 1] < vDown[i + 1]) { vDown[i] = vDown[i + 1] } else { vDown[i] = vDown[i - 1] + 1 } var x = vDown[i] var y = x - start1 + start2 - k while (x < end1 && y < end2 && sequenceA[x] == sequenceB[y]) { vDown[i] = ++x ++y } // Second step if (delta % 2 != 0 && delta - d + 1 <= k && k <= delta + d - 1) { if (vUp[i - delta] <= vDown[i]) { return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2) } } k += 2 } // Up k = delta - d while (k <= delta + d) { // First step val i = k + offset - delta if (k == delta - d || k != delta + d && vUp[i + 1] <= vUp[i - 1] ) { vUp[i] = vUp[i + 1] - 1 } else { vUp[i] = vUp[i - 1] } var x = vUp[i] - 1 var y = x - start1 + start2 - k while (x >= start1 && y >= start2 && sequenceA[x] == sequenceB[y]) { vUp[i] = x-- y-- } // Second step if (delta % 2 == 0 && -d <= k + delta && k + delta <= d) { if (vUp[i] <= vDown[i + delta]) { return buildSnake(vUp[i], k + start1 - start2, end1, end2) } } k += 2 } } return null } /** * Build an edit script. * * @param start1 the beginning of the first sequence to be compared * @param end1 the end of the first sequence to be compared * @param start2 the beginning of the second sequence to be compared * @param end2 the end of the second sequence to be compared */ @Suppress("NAME_SHADOWING") private fun buildScript(start1: Int, end1: Int, start2: Int, end2: Int) { var start1 = start1 var end1 = end1 var start2 = start2 var end2 = end2 // short-cut: for elements at the start/end of the two sequences that are equal // we can already add keep commands and omit them during the main algorithm // to speed up things. while (start1 < end1 && start2 < end2 && sequenceA[start1] == sequenceB[start2]) { editScript.appendKeep(originalSequenceA[start1], originalSequenceB[start2]) ++start1 ++start2 } val commands = LinkedList<Pair<T, T>>() while (end1 > start1 && end2 > start2 && sequenceA[end1 - 1] == sequenceB[end2 - 1]) { // collect the equal elements at the end in reverse order. commands.addFirst(Pair(originalSequenceA[end1 - 1], originalSequenceB[end2 - 1])) --end1 --end2 } // one of the sequences is a sub-sequence of the other one. if (start1 == end1) { while (start2 < end2) { editScript.appendInsert(originalSequenceB[start2++]) } } else if (start2 == end2) { while (start1 < end1) { editScript.appendDelete(originalSequenceA[start1++]) } } else { // for the remaining part, calculate the middle snake val middle = getMiddleSnake(start1, end1, start2, end2) if (middle == null || middle.start == end1 && middle.diag == end1 - end2 || middle.end == start1 && middle.diag == start1 - start2) { var i = start1 var j = start2 while (i < end1 || j < end2) { if (i < end1 && j < end2 && sequenceA[i] == sequenceB[j]) { editScript.appendKeep(originalSequenceA[i], originalSequenceB[j]) ++i ++j } else { if (end1 - i > end2 - j) { editScript.appendDelete(originalSequenceA[i]) ++i } else { editScript.appendInsert(originalSequenceB[j]) ++j } } } } else { buildScript(start1, middle.start, start2, middle.start - middle.diag) for (i in middle.start until middle.end) { editScript.appendKeep(originalSequenceA[i], originalSequenceB[i - middle.diag]) } buildScript(middle.end, end1, middle.end - middle.diag, end2) } } // do not forget to add the collected keep commands at the end. for ((origObj, newObj) in commands) { editScript.appendKeep(origObj, newObj) } } } /** * This class is a simple placeholder to hold the end part of a path. */ private class Snake constructor(val start: Int, val end: Int, val diag: Int) }
0
Kotlin
0
0
6556f2868fcb879cc22cd5ae1557862377e1ef27
12,050
tinydiff
Apache License 2.0