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/Day05.kt
jmorozov
573,077,620
false
{"Kotlin": 31919}
import java.util.ArrayDeque import java.util.Deque fun main() { val inputData = readInput("Day05") part1(inputData) part2(inputData) } private fun part1(inputData: List<String>) { val stacks = mutableListOf<Deque<Char>>() for (line in inputData) { when { line.startsWith(" 1 ") || line.isBlank() -> continue line.startsWith("move") -> moveCrate(line, stacks) else -> parseStacksLine(line, stacks) } } println("PART 1. Crate ends up on top of each stack: ${getTop(stacks)}") } private fun parseStacksLine(line: String, stacks: MutableList<Deque<Char>>) { val regex = """(\s{3})\s?|(\[[A-Z]\])\s?""".toRegex() var matchResult = regex.find(line) var idx = 0 while (matchResult != null) { val value = matchResult.value var stack: Deque<Char>? = stacks.getOrNull(idx) if (stack == null) { stack = ArrayDeque<Char>() stacks.add(stack) } if (value.isNotBlank()) { // TODO: add proper validation, of course val crate = value.trim()[1] stack.addFirst(crate) } idx++ matchResult = matchResult.next() } } private fun moveCrate(line: String, stacks: MutableList<Deque<Char>>) { val regex = """move (?<timesStr>\d+) from (?<fromStackStr>\d+) to (?<toStackStr>\d+)""".toRegex() val matchResult = regex.find(line) ?: return val (timesStr, fromStackStr, toStackStr) = matchResult.destructured var times = timesStr.toInt() val fromStack = stacks.getOrNull(fromStackStr.toInt() - 1) ?: return val toStack = stacks.getOrNull(toStackStr.toInt() - 1) ?: return while (times != 0 && fromStack.isNotEmpty()) { val crate = fromStack.pollLast() toStack.addLast(crate) times-- } } private fun getTop(stacks: MutableList<Deque<Char>>): String = stacks .filter { it.isNotEmpty() } .map { it.last } .joinToString(separator = "") private fun part2(inputData: List<String>) { val stacks = mutableListOf<Deque<Char>>() for (line in inputData) { when { line.startsWith(" 1 ") || line.isBlank() -> continue line.startsWith("move") -> moveCreateByCrateMover9001(line, stacks) else -> parseStacksLine(line, stacks) } } println("PART 2. Crate ends up on top of each stack: ${getTop(stacks)}") } private fun moveCreateByCrateMover9001(line: String, stacks: MutableList<Deque<Char>>) { val regex = """move (?<createsStr>\d+) from (?<fromStackStr>\d+) to (?<toStackStr>\d+)""".toRegex() val matchResult = regex.find(line) ?: return val (createsStr, fromStackStr, toStackStr) = matchResult.destructured var creates = createsStr.toInt() val fromStack = stacks.getOrNull(fromStackStr.toInt() - 1) ?: return val toStack = stacks.getOrNull(toStackStr.toInt() - 1) ?: return val buffer = ArrayDeque<Char>(creates) while (creates != 0 && fromStack.isNotEmpty()) { val crate = fromStack.pollLast() buffer.addFirst(crate) creates-- } toStack.addAll(buffer) }
0
Kotlin
0
0
480a98838949dbc7b5b7e84acf24f30db644f7b7
3,179
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidParenthesisString.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 678. Valid Parenthesis String * @see <a href="https://leetcode.com/problems/valid-parenthesis-string/">Source</a> */ fun interface ValidParenthesisString { operator fun invoke(s: String): Boolean } /** * Approach #1: Brute Force Time Limit Exceeded */ class ValidParenthesisStringBruteForce : ValidParenthesisString { private var ans = false override fun invoke(s: String): Boolean { solve(StringBuilder(s), 0) return ans } private fun solve(sb: StringBuilder, i: Int) { if (i == sb.length) { ans = ans or valid(sb) } else if (sb[i] == '*') { for (c in "() ".toCharArray()) { sb.setCharAt(i, c) solve(sb, i + 1) if (ans) return } sb.setCharAt(i, '*') } else { solve(sb, i + 1) } } fun valid(sb: StringBuilder): Boolean { var bal = 0 for (element in sb) { if (element == '(') bal++ if (element == ')') bal-- if (bal < 0) break } return bal == 0 } } /** * Approach #2: Dynamic Programming */ class ValidParenthesisStringDP : ValidParenthesisString { override fun invoke(s: String): Boolean { val n: Int = s.length if (n == 0) return true val dp = Array(n) { BooleanArray(n) } for (i in 0 until n) { if (s[i] == '*') dp[i][i] = true val local = s[i] == '(' || s[i] == '*' if (i < n - 1 && local && (s[i + 1] == ')' || s[i + 1] == '*')) { dp[i][i + 1] = true } } dp(s, n, dp) return dp[0][n - 1] } private fun dp(s: String, n: Int, dp: Array<BooleanArray>) { for (size in 2 until n) { var i = 0 while (i + size < n) { if (s[i] == '*' && dp[i + 1][i + size]) { dp[i][i + size] = true } else if (s[i] == '(' || s[i] == '*') { for (k in i + 1..i + size) { val local = (s[k] == ')' || s[k] == '*') && (k == i + 1 || dp[i + 1][k - 1]) if (local && (k == i + size || dp[k + 1][i + size])) { dp[i][i + size] = true } } } i++ } } } } /** * Approach #3: Greedy */ class ValidParenthesisStringGreedy : ValidParenthesisString { override fun invoke(s: String): Boolean { var lo = 0 var hi = 0 for (c in s.toCharArray()) { lo += if (c == '(') 1 else -1 hi += if (c != ')') 1 else -1 if (hi < 0) break lo = max(lo, 0) } return lo == 0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,473
kotlab
Apache License 2.0
src/day06/Day06.kt
jpveilleux
573,221,738
false
{"Kotlin": 42252}
package day06 import readInput const val currentDay = 6 const val baseDir = "./day0${currentDay}/" const val testInputFileName = "${baseDir}Day0${currentDay}_test" const val part1controlFileName = "${baseDir}Day0${currentDay}_part1_control" const val part2controlFileName = "${baseDir}Day0${currentDay}_part2_control" const val inputFileName = "${baseDir}Day0${currentDay}" val part1controlInput = readInput(part1controlFileName) val part2controlInput = readInput(part2controlFileName) val input = readInput(inputFileName) fun main() { fun part1(input: List<String>): Int { val chars = input[0].toCharArray() var buffer = arrayListOf<Char>() for (i in chars.indices) { println(buffer.distinct().count() == 4) if(buffer.distinct().count() < 4) { if(buffer.size == 4) { buffer.removeAt(0) } buffer.add(chars[i]) } else { println(chars[i]) return i } } return 0 } fun part2(input: List<String>): Int { val chars = input[0].toCharArray() var buffer = arrayListOf<Char>() for (i in chars.indices) { println(buffer.distinct().count() == 14) if(buffer.distinct().count() < 14) { if(buffer.size == 14) { buffer.removeAt(0) } buffer.add(chars[i]) } else { println(chars[i]) return i } } return 0 } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5ece22f84f2373272b26d77f92c92cf9c9e5f4df
1,652
jpadventofcode2022
Apache License 2.0
src/day04/Solve04.kt
NKorchagin
572,397,799
false
{"Kotlin": 9272}
package day04 import utils.* import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue @ExperimentalTime fun main() { fun readRangePairs(fileName: String) = readInput(fileName) .map { line -> line.split(",") .map { it.splitToPair("-") } .map { it.first.toInt() .. it.second.toInt() } } .map { it.first() to it.last() } fun solveA(fileName: String): Long = readRangePairs(fileName) .count { (left, right) -> left.inside(right) || right.inside(left) } .toLong() fun solveB(fileName: String): Long = readRangePairs(fileName) .count { (left, right) -> left.overlaps(right) || right.overlaps(left) } .toLong() check(solveA("day04/Example") == 2L) check(solveB("day04/Example") == 4L) val input = "day04/Input.ignore" val (part1, time1) = measureTimedValue { solveA(input) } println("Part1: $part1 takes: ${time1.inWholeMilliseconds}ms") val (part2, time2) = measureTimedValue { solveB(input) } println("Part2: $part2 takes: ${time2.inWholeMilliseconds}ms") }
0
Kotlin
0
0
ed401ab4de38b83cecbc4e3ac823e4d22a332885
1,180
AOC-2022-Kotlin
Apache License 2.0
src/Day02.kt
Vincentvibe3
573,202,573
false
{"Kotlin": 8454}
fun main() { fun part1(input: List<String>): Int { val DRAW = 3 val WIN = 6 val LOSS = 0 val ROCK = 1 val PAPER = 2 val SCISSORS = 3 var totalPoints = 0 for (line in input) { var roundPoints = 0 val split = line.split(" "); val opponent = split[0] val player = split[1] if ( (opponent == "A" && player == "Y") || (opponent == "B" && player == "Z") || (opponent == "C" && player == "X") ) { roundPoints += WIN } else if ( (opponent == "A" && player == "X") || (opponent == "B" && player == "Y") || (opponent == "C" && player == "Z") ) { roundPoints += DRAW } if (player == "X") { roundPoints += ROCK } else if (player == "Y") { roundPoints += PAPER } else if (player == "Z") { roundPoints += SCISSORS } totalPoints+=roundPoints } return totalPoints } fun part2(input: List<String>): Int { val DRAW = 3 val WIN = 6 val LOSS = 0 val ROCK = 1 val PAPER = 2 val SCISSORS = 3 var totalPoints = 0 for (line in input) { var roundPoints = 0 val split = line.split(" "); val opponent = split[0] val player = split[1] if (player == "X") { roundPoints += LOSS if (opponent=="A"){ roundPoints+=SCISSORS } else if (opponent =="B"){ roundPoints+=ROCK }else if (opponent =="C"){ roundPoints+=PAPER } } else if (player == "Y") { roundPoints += DRAW if (opponent=="A"){ roundPoints+=ROCK } else if (opponent =="B"){ roundPoints+=PAPER }else if (opponent =="C"){ roundPoints+=SCISSORS } } else if (player == "Z") { roundPoints += WIN if (opponent=="A"){ roundPoints+=PAPER } else if (opponent =="B"){ roundPoints+=SCISSORS }else if (opponent =="C"){ roundPoints+=ROCK } } totalPoints+=roundPoints } return totalPoints } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
246c8c43a416023343b3ef518ae3e21dd826ee81
2,934
advent-of-code-2022
Apache License 2.0
src/Day01.kt
dominiquejb
572,656,769
false
{"Kotlin": 10603}
fun main() { fun part1(input: List<String>): Int { val elves = mutableListOf<Int>() var calorieCount: Int = 0 input.forEach { if (it.isNullOrBlank()) { elves.add(calorieCount) calorieCount = 0 } else { calorieCount += it.toInt() } } elves.add(calorieCount) // add last return elves.max() } fun part2(input: List<String>): Int { val elves = mutableListOf<Int>() var calorieCount: Int = 0 input.forEach { if (it.isNullOrBlank()) { elves.add(calorieCount) calorieCount = 0 } else { calorieCount += it.toInt() } } elves.add(calorieCount) // add last println("Sublist") println(elves.sortedDescending().subList(0, 3)) println("Sublist") return elves.sortedDescending().take(3).sum() } val inputLines = readInputLines("input.01") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
f4f75f9fc0b5c6c81759357e9dcccb8759486f3a
1,101
advent-of-code-2022
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2016/calendar/day11/Day11.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2016.calendar.day11 import me.peckb.aoc.pathing.GenericIntDijkstra import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import javax.inject.Inject import kotlin.collections.MutableMap.MutableEntry class Day11 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> val initialLayout = loadLayout(input) val paths = RTGDijkstra().solve(initialLayout) val uniqueMachines = initialLayout.floors.flatMap { it.microchips }.size val numFloors = initialLayout.floors.size val solution = findCheapestPathToGoal(paths, numFloors, uniqueMachines) solution.value } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> val initialLayout = loadLayout(input) val paths = RTGDijkstra().solve(initialLayout) val uniqueMachines = initialLayout.floors.flatMap { it.microchips }.size val numFloors = initialLayout.floors.size val solution = findCheapestPathToGoal(paths, numFloors, uniqueMachines) // adding any number of matching RTGs to the bottom floor doesn't change how long it takes // to solve the initial problem, and the increased cost is just // initialSolution + ((numFloors - 1) * numFloors) * (newPairs) val newPairs = 2 solution.value + (((numFloors - 1) * numFloors) * newPairs) } private fun findCheapestPathToGoal(paths: MutableMap<FloorPlan, Int>, numFloors: Int, uniqueMachines: Int): MutableEntry<FloorPlan, Int> { return paths.entries.first { (fp, _) -> val topLevelIndex = numFloors - 1 fp.elevatorIndex == topLevelIndex && fp.floors[topLevelIndex].generators.size == uniqueMachines && fp.floors[topLevelIndex].microchips.size == uniqueMachines } } private fun loadLayout(input: Sequence<String>): FloorPlan { val floors = input.map { line -> val generators = sortedSetOf<String>() val microchips = sortedSetOf<String>() val equipmentOnFloor = line.substringAfter("floor contains ") .split("a ") .filterNot { it.isEmpty() } .filterNot { it.contains("nothing") } val (generatorData, microchipData) = equipmentOnFloor.partition { it.contains("generator") } generatorData.forEach { generators.add(it.substring(0, 3)) } microchipData.forEach { microchips.add(it.substring(0, 3)) } Floor(generators, microchips) } return FloorPlan(floors.toList(), 0) } class RTGDijkstra : GenericIntDijkstra<FloorPlan>() }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,584
advent-of-code
MIT License
src/main/kotlin/leetcode/kotlin/dp/213. House Robber II.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.dp /** * f(n) = Max( // max amount to robbed till n * f(n-2) + A[n], // max amount robbed till n-2 and current house * f(n-1) // max amount robbed till n-1 * ) */ private fun rob(nums: IntArray): Int { if (nums.size == 1) return nums[0] var dp = IntArray(nums.size) fun find(n: Int, lastLooted: Boolean): Int { if (n < 0) return 0 if (n == 0) return if (lastLooted) 0 else nums[0] if (dp[n] == 0) dp[n] = (find(n - 2, lastLooted) + nums[n]).coerceAtLeast(find(n - 1, lastLooted)) return dp[n] } var a = find(nums.size - 1, true) // check with excluding first dp.forEachIndexed { index, _ -> dp[index] = 0 } return a.coerceAtLeast(find(nums.size - 2, false)) // check with excluding last } fun main() { println(rob2(intArrayOf(2, 2, 3))) println(rob2(intArrayOf(1, 2, 3, 1))) } private fun rob2(nums: IntArray): Int { if (nums.size == 1) return nums[0] fun maxx(a: Int, b: Int): Int { var sl = 0 var l = 0 for (i in a..b) { var m = Math.max(sl + nums[i], l) sl = l l = m } return l } return maxx(0, nums.size - 2).coerceAtLeast(maxx(1, nums.size - 1)) }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
1,309
kotlinmaster
Apache License 2.0
src/Day06.kt
karloti
573,006,513
false
{"Kotlin": 25606}
import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue // <NAME> (my) fun String.indexOf(n: Int): Int = asSequence() .withIndex() .runningFold(mutableMapOf<Char, Int>() to -1) { (m, r), (i, c) -> m to (m.put(c, i)?.coerceAtLeast(r) ?: r) } .withIndex() .indexOfFirst { (index, value) -> index - value.second - 1 == n } // <NAME> fun solution(input: String, length: Int): Int { var distinctCount = 0 val charCounts = IntArray(256) return 1 + input.indices.first { if (it >= length) { when (--charCounts[input[it - length].code]) { 0 -> distinctCount-- 1 -> distinctCount++ } } when (++charCounts[input[it].code]) { 1 -> distinctCount++ 2 -> distinctCount-- } distinctCount == length } } // <NAME> fun String.startMessageIndexLinear(size: Int): Int { val dublicateIndexMap = mutableMapOf<Char, Int>() var dublicateIndex = 0 var index = 0 return indexOfFirst { char -> val lastSeen = dublicateIndexMap.put(char, index) ?: 0 dublicateIndex = dublicateIndex.coerceAtLeast((lastSeen)) index++ - dublicateIndex >= size + 1 } } @OptIn(ExperimentalTime::class) fun main() { val input = ('a'..'y').joinToString("").repeat(1_000_000) + "z" print("<NAME> = ") measureTimedValue { solution(input, 26) }.let(::println) print("<NAME> = ") measureTimedValue { input.startMessageIndexLinear(26) }.let(::println) print("<NAME> = ") measureTimedValue { input.indexOf(26) }.let(::println) print("windowed-native = ") measureTimedValue { input.windowed(26).indexOfFirst { it.toSet().size == 26 } + 26 }.let(::println) check(readInputAsText("Day06").indexOf(4) == 1909) check(readInputAsText("Day06").indexOf(14) == 3380) }
0
Kotlin
1
2
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
1,934
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/lucaszeta/adventofcode2020/day14/day14.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day14 import com.lucaszeta.adventofcode2020.ext.getResourceAsText import kotlin.math.pow fun main() { val input = getResourceAsText("/day14/initialization-program.txt") .split("\n") .filter { it.isNotEmpty() } listOf( ::processInstructions to "old decoder", ::processInstructionsV2 to "v2 decoder" ).forEach { (method, label) -> val resultMap = method.invoke(input) val sumOfValuesInMemory = resultMap.map { it.value }.reduce(Long::plus) println("Sum of all values left ($label): $sumOfValuesInMemory") } } fun processInstructions(input: List<String>): MutableMap<Long, Long> { var bitmask = listOf<String>() val resultMap = mutableMapOf<Long, Long>() for (instruction in input) { extractMask(instruction)?.let { bitmask = it } extractMemory(instruction)?.let { (address, value) -> val maskApplied = applyMask(bitmask, value) resultMap[address.toLong()] = maskApplied } } return resultMap } fun processInstructionsV2(input: List<String>): MutableMap<Long, Long> { var bitmask = listOf<String>() val resultMap = mutableMapOf<Long, Long>() for (instruction in input) { extractMask(instruction)?.let { bitmask = it } extractMemory(instruction)?.let { (address, value) -> fetchAddressList(bitmask, address).forEach { resultMap[it] = value.fromBinaryToLong() } } } return resultMap } fun applyMask(bitmask: List<String>, value: List<String>): Long { val valueSameSizeAsMask = value.addLeadingZeros(bitmask.size) val binaryString = mutableListOf<String>() .apply { bitmask.zip(valueSameSizeAsMask).forEach { (mask, value) -> add(if (mask != "X") mask else value) } } .toList() return binaryString.fromBinaryToLong() } fun extractMemory(instruction: String): Pair<Int, List<String>>? { val memoryResult = "mem\\[([0-9]*)] = ([0-9]*)".toRegex().matchEntire(instruction) return memoryResult?.let { val address = it.groupValues[1].toInt() val value = Integer.toBinaryString(it.groupValues[2].toInt()) .chunked(1) address to value } } fun extractMask(instruction: String): List<String>? { val maskResult = "mask = ([01X]*)".toRegex().matchEntire(instruction) return maskResult?.let { it.groupValues[1].chunked(1) } } fun fetchAddressList(bitmask: List<String>, originAddress: Int): List<Long> { val addresses = mutableListOf<Long>() val binaryAddress = Integer.toBinaryString(originAddress) .chunked(1) .addLeadingZeros(bitmask.size) val (maskApplied, indicesToReplace) = applyMaskV2(bitmask, binaryAddress) val possibilities = 2.0.pow(indicesToReplace.size).toInt() for (number in 0 until possibilities) { val bits = Integer.toBinaryString(number) .chunked(1) .addLeadingZeros(indicesToReplace.size) bits.forEachIndexed { index, char -> maskApplied[indicesToReplace[index]] = char } addresses.add(maskApplied.toList().fromBinaryToLong()) } return addresses } private fun applyMaskV2( bitmask: List<String>, binaryAddress: List<String> ): Pair<MutableList<String>, List<Int>> { val indicesToReplace = mutableListOf<Int>() val maskApplied = mutableListOf<String>() bitmask.zip(binaryAddress).forEachIndexed { index, (mask, address) -> val newBit = when (mask) { "0" -> address "1" -> mask else -> { indicesToReplace.add(index) mask } } maskApplied.add(newBit) } return maskApplied to indicesToReplace.toList() } private fun List<String>.addLeadingZeros(maximumSize: Int): List<String> { return toMutableList() .apply { while (size < maximumSize) { add(0, "0") } } .toList() } private fun List<String>.fromBinaryToLong(): Long { return map { it.toLong() } .reversed() .reduceIndexed { index, acc, bit -> acc + bit * 2.0.pow(index).toLong() } }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
4,364
advent-of-code-2020
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-16.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText fun main() { val input = readInputText(2021, "16-input") val test1 = readInputText(2021, "16-test1") val test2 = readInputText(2021, "16-test2") val test3 = readInputText(2021, "16-test3") val test4 = readInputText(2021, "16-test4") println("Part1:") part1(test1).println() part1(test2).println() part1(test3).println() part1(input).println() println() println("Part2:") part2(test4).println() part2(input).println() } private fun part1(input: String): Int { val parser = PacketParser(input) return parser.parse().versionSum() } private fun part2(input: String): Long { val parser = PacketParser(input) return parser.parse().calculate() } private class PacketParser(input: String) { private val binaryRep = input .map { it.digitToInt(16).toString(2).padStart(4, '0') } .joinToString(separator = "") fun parse() = parsePacket().first private fun parsePacket(start: Int = 0): Pair<Packet, Int> { val version = binaryRep.substring(start, start + 3).toInt(2) val typeId = binaryRep.substring(start + 3, start + 6).toInt(2) return if (typeId == 4) { val (value, end) = readLiteralValue(start + 6) Literal(version, value) to end } else { val (subPackets, end) = readSubPackets(start + 6) Operator(version, typeId, subPackets) to end } } private fun readLiteralValue(start: Int): Pair<Long, Int> { var position = start var group = binaryRep.substring(position, position + 5) position += 5 return buildString { append(group.substring(1)) while (group.first() == '1') { group = binaryRep.substring(position, position + 5) append(group.substring(1)) position += 5 } }.toLong(2) to position } private fun readSubPackets(start: Int): Pair<List<Packet>, Int> { return if (binaryRep[start] == '0') { readSubPacketsByLength(start + 1) } else { readSubPacketsByCount(start + 1) } } private fun readSubPacketsByLength(start: Int): Pair<List<Packet>, Int> { var position = start var remainingLength = binaryRep.substring(position, position + 15).toInt(2) position += 15 return buildList { while (remainingLength != 0) { val (subPacket, rest) = parsePacket(position) val read = rest - position remainingLength -= read position += read this += subPacket } } to position } private fun readSubPacketsByCount(start: Int): Pair<List<Packet>, Int> { var position = start val subPacketCount = binaryRep.substring(position, position + 11).toInt(2) position += 11 return buildList { repeat(subPacketCount) { val (subPacket, rest) = parsePacket(position) val read = rest - position position += read this += subPacket } } to position } } private sealed class Packet { abstract fun versionSum(): Int abstract fun calculate(): Long } private class Literal(val version: Int, val value: Long) : Packet() { override fun versionSum(): Int = version override fun calculate(): Long = value } private class Operator(val version: Int, val typeId: Int, val subPackets: List<Packet>) : Packet() { override fun versionSum(): Int { return version + subPackets.sumOf { it.versionSum() } } override fun calculate(): Long { return when (typeId) { 0 -> subPackets.sumOf { it.calculate() } 1 -> subPackets.fold(1) { acc, item -> acc * item.calculate() } 2 -> subPackets.minOf { it.calculate() } 3 -> subPackets.maxOf { it.calculate() } 5 -> { val first = subPackets[0].calculate() val second = subPackets[1].calculate() if (first > second) 1 else 0 } 6 -> { val first = subPackets[0].calculate() val second = subPackets[1].calculate() if (first < second) 1 else 0 } 7 -> { val first = subPackets[0].calculate() val second = subPackets[1].calculate() if (first == second) 1 else 0 } else -> { error("wrong type id: $typeId") } } } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
4,788
advent-of-code
MIT License
src/main/kotlin/de/p58i/utils/tableoptimizer/io/YamlIO.kt
mspoeri
529,728,917
false
{"Kotlin": 30057}
package de.p58i.utils.tableoptimizer.io import com.fasterxml.jackson.annotation.JsonAlias import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.kotlin.kotlinModule import com.fasterxml.jackson.module.kotlin.readValue import de.p58i.utils.tableoptimizer.model.Group import de.p58i.utils.tableoptimizer.model.Pairing import de.p58i.utils.tableoptimizer.model.Problem import de.p58i.utils.tableoptimizer.model.Solution import de.p58i.utils.tableoptimizer.model.Table import de.p58i.utils.tableoptimizer.model.TableAffinity import java.nio.file.Path private object YamlIO { val mapper: ObjectMapper = ObjectMapper(YAMLFactory()).registerModule(kotlinModule()) } fun yamlToProblem(yamlFile: Path): Problem { return YamlIO.mapper.readValue<InputProblem>(yamlFile.toFile()).toProblem() } fun solutionsToYAML(path: Path, solutions: List<Solution>) { YamlIO.mapper.writeValue(path.toFile(), solutions.map { OutputSolution(it) }.sortedBy { it.score }) } data class OutputSolution( val score: Double, val tables: List<OutputTable> ) { constructor(solution: Solution) : this(solution.score, solution.tables.map { OutputTable(it) }.sortedBy { it.name }) } data class OutputTable( val name: String, val seats: UInt, val occupiedSeats: UInt, val groups: List<OutputGroup> ) { constructor(table: Table) : this(name = table.name, seats = table.seats, occupiedSeats = table.occupiedSeats(), groups = table.groups.map { OutputGroup(it) }.sortedBy { it.name }) } data class OutputGroup( val name: String, val people: Collection<String> ) { constructor(group: Group) : this(name = group.name, people = group.people.sortedBy { it }) } data class InputGroup( val name: String, val people: Collection<String>, ) { fun toGroup() = Group(name = name, people = HashSet(people)) } data class InputTable( val name: String, val seats: Int, ) { fun toTable() = Table(name = name, seats = seats.toUInt()) } data class InputPairing( @JsonAlias("person-A") val personA: String, @JsonAlias("person-B") val personB: String, val score: Double, ) { fun toPairing() = Pairing(personA = personA, personB = personB, score = score) } data class InputTableAffinity( @JsonAlias("table-name") val tableName: String, @JsonAlias("group-name") val groupName: String, val score: Double, ) { fun toTableAffinity() = TableAffinity(tableName = tableName, groupName = groupName, score = score) } data class InputProblem( val groups: Collection<InputGroup>, val tables: Collection<InputTable>, val pairings: Collection<InputPairing>, @JsonAlias("table-affinities") val tableAffinities: Collection<InputTableAffinity>, ) { fun toProblem() = Problem(groups = groups.map { it.toGroup() }.toSet(), tables = tables.map { it.toTable() }.toSet(), pairings = pairings.map { it.toPairing() }.toSet(), tableAffinities = tableAffinities.map { it.toTableAffinity() }.toSet() ) }
4
Kotlin
0
2
7e8765be47352e79b45f6ff0f8e6396e3da9abc9
3,079
table-optimizer
MIT License
app/src/main/kotlin/aoc2022/day04/Day04.kt
dbubenheim
574,231,602
false
{"Kotlin": 18742}
package aoc2022.day04 import aoc2022.day04.Day04.part1 import aoc2022.day04.Day04.part2 import aoc2022.toFile object Day04 { fun part1() = "input-day04.txt".toFile() .readLines() .map { it.toAssignmentPair() } .count { it.fullyContains() } fun part2() = "input-day04.txt".toFile() .readLines() .map { it.toAssignmentPair() } .count { it.overlaps() } private fun String.toAssignmentPair(): AssignmentPair { val (first, second) = split(",") val (firstFrom, firstTo) = first.split("-") val (secondFrom, secondTo) = second.split("-") return AssignmentPair(firstFrom.toInt()..firstTo.toInt(), secondFrom.toInt()..secondTo.toInt()) } data class AssignmentPair(val first: IntRange, val second: IntRange) { fun fullyContains() = first.all { it in second } || second.all { it in first } fun overlaps() = first.any { it in second } || second.any { it in first } } } fun main() { println(part1()) println(part2()) }
8
Kotlin
0
0
ee381bb9820b493d5e210accbe6d24383ae5b4dc
1,040
advent-of-code-2022
MIT License
dcp_kotlin/src/main/kotlin/dcp/day252/Rational.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day252 // day252.kt // By <NAME>, 2019. import java.lang.IllegalArgumentException import java.math.BigInteger class Rational(n: BigInteger, d: BigInteger): Comparable<Rational> { val numerator: BigInteger val denominator: BigInteger init { require(d != BigInteger.ZERO) {"Denominator cannot be zero"} val gcd = n.gcd(d) numerator = d.signum().toBigInteger() * n / gcd denominator = d.signum().toBigInteger() * d / gcd } operator fun plus(other: Rational): Rational = Rational(numerator * other.denominator + denominator * other.numerator, denominator * other.denominator) operator fun minus(other: Rational): Rational = Rational(numerator * other.denominator - denominator * other.numerator, denominator * other.denominator) operator fun times(other: Rational): Rational = Rational(numerator * other.numerator, denominator * other.denominator) operator fun div(other: Rational): Rational = Rational(numerator * other.denominator, denominator * other.numerator) operator fun unaryMinus(): Rational = Rational(-numerator, denominator) override fun compareTo(other: Rational): Int = (numerator * other.denominator - other.numerator * denominator).signum() override fun toString(): String { if (numerator == BigInteger.ZERO) return "0" return numerator.toString() + (if (denominator != BigInteger.ONE) "/$denominator" else "") } override fun hashCode(): Int { var result = numerator.hashCode() result = 31 * result + denominator.hashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Rational if (numerator != other.numerator) return false if (denominator != other.denominator) return false return true } // Destructuring components. operator fun component1(): BigInteger = numerator operator fun component2(): BigInteger = denominator companion object { val ZERO: Rational = Rational(BigInteger.ZERO, BigInteger.ONE) val ONE: Rational = Rational(BigInteger.ONE, BigInteger.ONE) } } infix fun BigInteger.divBy(other: BigInteger): Rational = Rational(this, other) infix fun Int.divBy(other: Int): Rational = Rational(this.toBigInteger(), other.toBigInteger()) infix fun Long.divBy(other: Long): Rational = Rational(this.toBigInteger(), other.toBigInteger()) fun String.toRational(): Rational { fun fail(): Nothing = throw IllegalArgumentException("Expecting rational in form of n/d or n, received $this") if ('/' !in this) { val number = toBigIntegerOrNull() ?: fail() return Rational(number, BigInteger.ONE) } val (numerText, denomText) = this.split('/') val numer = numerText.toBigIntegerOrNull() ?: fail() val denom = denomText.toBigIntegerOrNull() ?: fail() return Rational(numer, denom) } @kotlin.jvm.JvmName("sumOfBigInteger") fun Iterable<BigInteger>.sum(): BigInteger = this.fold(BigInteger.ZERO){acc, curr -> acc + curr} @kotlin.jvm.JvmName("sumOfRational") fun Iterable<Rational>.sum(): Rational = this.fold(Rational.ZERO){acc, curr -> acc + curr}
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
3,337
daily-coding-problem
MIT License
src/main/kotlin/g2401_2500/s2448_minimum_cost_to_make_array_equal/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2448_minimum_cost_to_make_array_equal // #Hard #Array #Sorting #Binary_Search #Prefix_Sum // #2023_07_05_Time_387_ms_(80.40%)_Space_50.7_MB_(80.41%) import java.util.Collections class Solution { private class Pair(var e: Int, var c: Int) fun minCost(nums: IntArray, cost: IntArray): Long { var sum: Long = 0 val al: MutableList<Pair> = ArrayList() for (i in nums.indices) { al.add(Pair(nums[i], cost[i])) sum += cost[i].toLong() } Collections.sort(al) { a: Pair, b: Pair -> a.e.compareTo(b.e) } var ans: Long = 0 val mid = (sum + 1) / 2 var s2: Long = 0 var t = 0 run { var i = 0 while (i < al.size && s2 < mid) { s2 += al[i].c.toLong() t = al[i].e i++ } } for (i in al.indices) { ans += Math.abs(nums[i].toLong() - t.toLong()) * cost[i] } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,023
LeetCode-in-Kotlin
MIT License
plugin/src/main/kotlin/tanvd/grazi/ide/ui/components/rules/RuleWithLang.kt
TanVD
177,469,390
false
null
package tanvd.grazi.ide.ui.components.rules import org.languagetool.rules.Category import org.languagetool.rules.Rule import tanvd.grazi.GraziConfig import tanvd.grazi.language.Lang import tanvd.grazi.language.LangTool import java.util.* data class RuleWithLang(val rule: Rule, val lang: Lang, val enabled: Boolean, var enabledInTree: Boolean) : Comparable<RuleWithLang> { val category: Category = rule.category override fun compareTo(other: RuleWithLang) = rule.description.compareTo(other.rule.description) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RuleWithLang if (lang != other.lang) return false if (rule.description != other.rule.description) return false return true } override fun hashCode(): Int { var result = rule.description.hashCode() result = 31 * result + lang.hashCode() return result } } data class ComparableCategory(val category: Category) : Comparable<ComparableCategory> { val name: String = category.name override fun compareTo(other: ComparableCategory) = name.compareTo(other.name) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ComparableCategory if (category.name != other.category.name) return false return true } override fun hashCode(): Int { return category.name.hashCode() } } typealias RulesMap = Map<Lang, Map<ComparableCategory, SortedSet<RuleWithLang>>> fun LangTool.allRulesWithLangs(langs: Collection<Lang>): RulesMap { val state = GraziConfig.get() val result = TreeMap<Lang, SortedMap<ComparableCategory, SortedSet<RuleWithLang>>>(Comparator.comparing(Lang::displayName)) langs.filter { it.jLanguage != null }.forEach { lang -> val categories = TreeMap<ComparableCategory, SortedSet<RuleWithLang>>() with(getTool(lang)) { val activeRules = allActiveRules.toSet() fun Rule.isActive() = (id in state.userEnabledRules && id !in state.userDisabledRules) || (id !in state.userDisabledRules && id !in state.userEnabledRules && this in activeRules) allRules.distinctBy { it.id }.forEach { if (!it.isDictionaryBasedSpellingRule) { categories.getOrPut(ComparableCategory(it.category), ::TreeSet).add(RuleWithLang(it, lang, enabled = it.isActive(), enabledInTree = it.isActive())) } } if (categories.isNotEmpty()) result[lang] = categories } } return result }
0
Kotlin
0
36
d12150715d19aaafcb9b7a474ea911bf1713701f
2,733
Grazi
Apache License 2.0
src/util/polylines/sortClockwise.kt
JBWills
291,822,812
false
null
package util.polylines import coordinate.Point fun List<Point>.centroid() = if (length == 0.0) Point.Zero else reduceRight { p, acc -> p + acc } / size fun clockwiseComparator(c: Point) = Comparator { a: Point, b: Point -> fun ret(boolean: Boolean) = if (boolean) -1 else 1 if (a.x >= c.x && b.x < c.x) return@Comparator ret(true) if (a.x < c.x && b.x >= c.x) return@Comparator ret(false) if (a.x == c.x && b.x == c.x) { return@Comparator ret(if (a.y >= c.y || b.y >= c.y) a.y > b.y else b.y > a.y) } // compute the cross product of vectors (c -> a) x (c -> b) // compute the cross product of vectors (c -> a) x (c -> b) val det: Double = (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y) if (det < 0) return@Comparator ret(true) if (det > 0) return@Comparator ret(false) // points a and b are on the same line from the c // check which point is closer to the c // points a and b are on the same line from the c // check which point is closer to the c val d1: Double = (a - c).squared().sum() val d2: Double = (b - c).squared().sum() return@Comparator ret(d1 > d2) } fun List<Point>.sortClockwise(center: Point? = null): List<Point> { val centerNonNull = center ?: centroid() return sortedWith(clockwiseComparator(centerNonNull)) }
0
Kotlin
0
0
569b27c1cb1dc6b2c37e79dfa527b9396c7a2f88
1,301
processing-sketches
MIT License
src/Day13.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
import java.util.Stack import kotlin.math.max private const val DEBUG = false private sealed class InnerItem private data class InnerNumber(val value: Int) : InnerItem() { override fun toString(): String { return value.toString() } } private data class InnerList(val list: List<InnerItem>) : InnerItem() { override fun toString(): String { return list.toString() } } private data class InnerChar(val c: Char) : InnerItem() fun main() { fun String.parseLine(): InnerList { val stack = Stack<InnerItem>() var i = 0 while (i < length) { when { this[i] == '[' -> stack.push(InnerChar('[')) this[i] == ']' -> { val list = mutableListOf<InnerItem>() while ((stack.peek() as? InnerChar)?.c != '[') { list.add(stack.pop()) } stack.pop() stack.add(InnerList(list.reversed())) } this[i].isDigit() -> { var j = i while (this[j + 1].isDigit()) { j++ } stack.add(InnerNumber(this.slice(i..j).toInt())) i = j } } i += 1 } return stack.pop() as? InnerList ?: throw Exception("Parsing not complete") } fun List<String>.parse(): List<Pair<InnerList, InnerList>> { return this.joinToString("\n").split("\n\n").map { pair -> val (first, second) = pair.split("\n") first.parseLine() to second.parseLine() } } fun compare(lhs: InnerItem, rhs: InnerItem): Boolean? { if (lhs is InnerNumber && rhs is InnerNumber) { if (DEBUG)println("Compare $lhs vs $rhs") val result = if (lhs.value < rhs.value) { true } else if (lhs.value > rhs.value) { false } else { null } if (DEBUG) { if (result == true) { println("Left side is smaller, so inputs are in the right order") } else if (result == false) { println("Right side is smaller, so inputs are not in the right order") } } return result } else if (lhs is InnerList && rhs is InnerList) { if (DEBUG) println("Compare $lhs vs $rhs") for (i in 0 until max(lhs.list.size, rhs.list.size)) { if (i >= rhs.list.size) { return false } if (i >= lhs.list.size) { return true } val left = lhs.list[i] val right = rhs.list[i] val cmp = compare(left, right) if (cmp != null) { return cmp } } return null } else if ((lhs is InnerNumber).xor(rhs is InnerNumber)) { if (DEBUG) print("Mixed types; ") return if (lhs is InnerNumber) { if (DEBUG) println(" convert left to ${InnerList(listOf(lhs))} and retry comparison") compare(InnerList(listOf(lhs)), rhs) } else if (rhs is InnerNumber) { if (DEBUG) println(" convert right to ${InnerList(listOf(rhs))} and retry comparison") compare(lhs, InnerList(listOf(rhs))) } else { throw Exception("Unexpected") } } throw Exception("Unexpected") } fun part1(input: List<String>): Int { return input.parse().mapIndexed { idx, (first, second) -> if (DEBUG) println("== Pair ${idx + 1} ==") val result = compare(first, second) if (DEBUG) println() result } .mapIndexed { idx, item -> idx + 1 to item } .filter { (_, item) -> item == true } .sumOf { (idx, _) -> idx } } fun part2(input: List<String>): Int { val parsed = input.parse() val additionalPackets = listOf( InnerList(mutableListOf(InnerList(mutableListOf(InnerNumber(2))))), InnerList(mutableListOf(InnerList(mutableListOf(InnerNumber(6))))) ) val sorted = (parsed.flatMap { listOf(it.first, it.second) } + additionalPackets) .sortedWith { lhs, rhs -> when (compare(lhs, rhs)) { true -> 1 false -> -1 else -> 0 } }.reversed() return additionalPackets.map { sorted.indexOf(it) + 1 }.reduce { acc, it -> acc * it } } val testInput = readInput("Day13_test") val input = readInput("Day13") assert(part1(testInput), 13) println(part1(input)) assert(part2(testInput), 140) println(part2(input)) } // Time: 01:30
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
4,980
advent-of-code-2022
Apache License 2.0
Day_07/Solution_Part2.kts
0800LTT
317,590,451
false
null
import java.io.File class Graph() { val data: MutableMap<String, Set<Pair<String, Int>>> = mutableMapOf() fun addNodes(container: String, contained: Sequence<Pair<String, Int>>) { data.put(container, contained.toSet()) } fun countBags(source: String): Int { var total = 0 for ((bag, bagCount) in data.getOrElse(source, { setOf<Pair<String, Int>>() })) { total += bagCount * countBags(bag) } return total + 1 } } fun File.toGraphOrNull(): Graph? { val sourceBagRegex = """([a-z ]+) bags contain""".toRegex() val destinationBagRegex = """(\d+)\s([a-z ]+)\sbags?\s*(,|.)""".toRegex() val graph = Graph() forEachLine { val match = sourceBagRegex.find(it) if (match != null) { val (sourceBag) = match.destructured val destinationBags = destinationBagRegex.findAll(it).map { val (count, destinationBag) = it.destructured Pair(destinationBag, count.toInt()) } graph.addNodes(sourceBag, destinationBags) } } return graph } fun main() { print( File("input.txt").toGraphOrNull()?.countBags("shiny gold")!! - 1 ) } main()
0
Kotlin
0
0
191c8c307676fb0e7352f7a5444689fc79cc5b54
1,121
advent-of-code-2020
The Unlicense
java/app/src/main/kotlin/com/github/ggalmazor/aoc2021/day20/Grid.kt
ggalmazor
434,148,320
false
{"JavaScript": 80092, "Java": 33594, "Kotlin": 14508, "C++": 3077, "CMake": 119}
package com.github.ggalmazor.aoc2021.day20 class Grid<T>(private val cells: List<Cell<T>>, private val width: Int, private val height: Int) { fun cellAt(position: Position): Cell<T>? { return cells.find { cell -> cell.isAt(position) } } fun subGridAt(position: Position, defaultValue: T): Grid<T> = Grid( listOf( cellAt(position.topLeft()) ?: Cell(position.topLeft(), defaultValue), cellAt(position.top()) ?: Cell(position.top(), defaultValue), cellAt(position.topRight()) ?: Cell(position.topRight(), defaultValue), cellAt(position.left()) ?: Cell(position.left(), defaultValue), cellAt(position.center()) ?: Cell(position.center(), defaultValue), cellAt(position.right()) ?: Cell(position.right(), defaultValue), cellAt(position.bottomLeft()) ?: Cell(position.bottomLeft(), defaultValue), cellAt(position.bottom()) ?: Cell(position.bottom(), defaultValue), cellAt(position.bottomRight()) ?: Cell(position.bottomRight(), defaultValue), ), 3, 3 ) fun asList(): List<Cell<T>> = cells fun center(): Position = cells[Math.floorDiv(cells.size, 2)].position fun pad(value: T): Grid<T> { val movedCells = cells.map { cell -> cell.moveTo(cell.position.bottomRight()) } val newCellsOnTheTop = (0..width + 1).map { x -> Cell(Position(x, 0), value) } val newCellsOnTheBottom = (0..width + 1).map { x -> Cell(Position(x, height + 1), value) } val newCellsOnTheRight = (1..height).map { y -> Cell(Position(width + 1, y), value) } val newCellsOnTheLeft = (1..height).map { y -> Cell(Position(0, y), value) } return Grid(movedCells + newCellsOnTheTop + newCellsOnTheRight + newCellsOnTheBottom + newCellsOnTheLeft, width + 2, height + 2) } fun map(mapper: (Cell<T>) -> Cell<T>): Grid<T> { return Grid(cells.parallelStream().map(mapper).toList(), width, height) } fun count(predicate: (Cell<T>) -> Boolean): Int { return cells.count(predicate) } companion object { fun <U> from(lines: List<List<Char>>, width: Int, height: Int, mapper: (Char) -> U): Grid<U> = Grid( lines.flatMapIndexed { y, chars -> chars.mapIndexed { x, char -> Cell(Position(x, y), mapper(char)) } }, width, height ) } }
0
JavaScript
0
0
7a7ec831ca89de3f19d78f006fe95590cc533836
2,389
aoc2021
Apache License 2.0
src/main/kotlin/g1401_1500/s1457_pseudo_palindromic_paths_in_a_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1457_pseudo_palindromic_paths_in_a_binary_tree // #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree #Bit_Manipulation // #2023_06_13_Time_583_ms_(50.00%)_Space_62.9_MB_(100.00%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private var ans = 0 private lateinit var arr: IntArray fun pseudoPalindromicPaths(root: TreeNode?): Int { ans = 0 arr = IntArray(10) path(root) return ans } private fun isPalidrome(): Int { var c = 0 var s = 0 for (i in 0..9) { s += arr[i] if (arr[i] % 2 != 0) { c++ } } if (s % 2 == 0) { return if (c == 0) 1 else 0 } return if (c <= 1) 1 else 0 } private fun path(root: TreeNode?) { if (root == null) { return } if (root.left == null && root.right == null) { arr[root.`val`]++ ans += isPalidrome() arr[root.`val`]-- return } arr[root.`val`]++ path(root.left) path(root.right) arr[root.`val`]-- } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,395
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-20.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.BooleanGrid import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import com.github.ferinagy.adventOfCode.toBooleanGrid private typealias Image = BooleanGrid fun main() { val input = readInputText(2021, "20-input") val test1 = readInputText(2021, "20-test1") val test2 = readInputText(2021, "20-test1") println("Part1:") part1(test1).println() part1(test2).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: String): Int { return enhance(input, 2) } private fun part2(input: String): Int { return enhance(input, 50) } private fun enhance(input: String, n: Int, print: Boolean = false): Int { val (algo, imagePart) = input.split("\n\n") require(algo.length == 512) var image = imagePart.lines().toBooleanGrid { it == '#' } if (print) { println(image.toImageString('.')) } val isBlinking = algo.first() == '#' && algo.last() == '.' repeat(n) { image = image.enhance(algo, it + 1) if (print) { println(image.toImageString(if (isBlinking && it % 2 == 0) '#' else '.')) } } return image.litPixels() } private fun Image.litPixels(): Int { return count { it } } private fun Image.toImageString(border: Char): String { return buildString { append(border.toString().repeat(width + 2)) append('\n') for (y in 0 until height) { append(border) for (x in 0 until width) { if (get(x, y)) append('#') else append('.') } append(border) append('\n') } append(border.toString().repeat(width + 2)) append('\n') } } private fun Image.enhance(algo: String, iteration: Int): Image { val isBlinking = algo.first() == '#' && algo.last() == '.' val defaultPixel = isBlinking && iteration % 2 == 0 val newImage = BooleanGrid(width + 2, height + 2) { x, y -> isLight(x - 1, y - 1, algo, defaultPixel) } return newImage } private fun Image.isLight(x: Int, y: Int, algo: String, defaultPixel: Boolean): Boolean { var index = 0 for (dy in -1..1) { for (dx in -1..1) { index = index shl 1 val value = if (x + dx in xRange && y + dy in yRange) get(x + dx, y + dy) else defaultPixel if (value) index++ } } require(index < 512) { "Bad index $index for $this" } return algo[index] == '#' }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,659
advent-of-code
MIT License
2020/day17/day17.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day17 import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: 2D grid of active (#) and inactive (.) cubes/hypercubes. Conway-style changes: each round, active cubes become inactive unless they have 2 or 3 active neighbors; inactive cubes become active if they have exactly 3 neighbors. Output: number of active cubes after 6 rounds. */ data class DimensionalCube(private val coordinates: List<Int>) { fun neighbors(): Sequence<DimensionalCube> { suspend fun SequenceScope<DimensionalCube>.recurse(prefix: List<Int>) { val position = prefix.size if (position == coordinates.size) { if (prefix != coordinates) { // cube isn't a neighbor to itself yield(DimensionalCube(prefix)) } } else { for (i in coordinates[position] - 1..coordinates[position] + 1) { recurse(prefix + i) } } } return sequence { recurse(listOf()) } } } fun countActiveAfter(rounds: Int, dimensions: Int, initialState: Sequence<String>): Int { var prevActive = initialState.withIndex().flatMap { (x, line) -> line.toCharArray().withIndex().filter { it.value == '#' }.map { it.index } .map { y -> DimensionalCube(listOf(x, y, *Array(dimensions - 2) { 0 })) } }.toSet() repeat(rounds) { // Active cells remain active with 2 or 3 neighbors, inactive cells become active with 3 prevActive = prevActive.flatMap(DimensionalCube::neighbors).groupingBy { it }.eachCount() .filter { (cube, count) -> count == 3 || (count == 2 && cube in prevActive) }.keys } return prevActive.size } object Part1 { fun solve(input: Sequence<String>): String { return countActiveAfter(6, 3, input).toString() } } object Part2 { fun solve(input: Sequence<String>): String { return countActiveAfter(6, 4, input).toString() } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
2,576
adventofcode
MIT License
src/main/kotlin/com/github/dangerground/Day13.kt
dangerground
226,153,955
false
null
package com.github.dangerground import com.github.dangerground.util.Intcode class Arcade { private var robot: Intcode = Intcode.ofFile("/day13input.txt") val map = HashMap<Coord2D, Long>() var blockCount = 0 fun run() { robot.runProgram() val data = robot.outputs for (t in 0 until data.size step 3) { val x = data[t] val y = data[t + 1] val tile = data[t + 2] map[Coord2D(x, y)] = tile if (tile == 2L) { blockCount++ } } } var currentScore = -1L fun playGame() { robot.setMem(0, 2) var ballX = 0L var paddleX = 0L do { robot.inputCode = arrayOf(if (paddleX > ballX) 1L else if (paddleX < ballX) -1L else 0L) robot.runProgram() val data = robot.outputs for (t in 0 until data.size step 3) { val x = data[t] val y = data[t + 1] val tile = data[t + 2] if (x == -1L && y == 0L) { currentScore = tile } else { map[Coord2D(x, y)] = tile if (tile == 3L) { ballX = x } else if (tile == 4L) { paddleX = x } } } blockCount = map.filter { entry -> entry.value == 2L }.size /* for (y in 0 until 20L) { for (x in 0 until 42L) { print(when (map[Coord2D(x, y)]) { 0L -> " " 1L -> "|" 2L -> "#" 3L -> "-" 4L -> "o" else -> "E" }) } println() }*/ } while (blockCount > 0) } } class Coord2D(val x: Long, val y: Long) : Comparable<Coord2D> { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Coord2D if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x.hashCode() result = 31 * result + y.hashCode() return result } override fun toString(): String { return "Coord2D(x=$x, y=$y)" } override fun compareTo(other: Coord2D): Int { val o1 = y.compareTo(other.y) if (o1 != 0) return o1 return x.compareTo(other.x) } } fun main() { /* // part1 val arcade1 = Arcade() arcade1.run() println(arcade1.blockCount) */ // part2 val arcade2 = Arcade() arcade2.playGame() println(arcade2.currentScore) }
0
Kotlin
0
1
125d57d20f1fa26a0791ab196d2b94ba45480e41
2,884
adventofcode
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[1232]缀点成线.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 // x、纵坐标为 y 的点。 // // 请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。 // // // // 示例 1: // // // // 输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] //输出:true // // // 示例 2: // // // // 输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] //输出:false // // // // // 提示: // // // 2 <= coordinates.length <= 1000 // coordinates[i].length == 2 // -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 // coordinates 中不含重复的点 // // Related Topics 几何 数组 数学 // 👍 63 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun checkStraightLine(c: Array<IntArray>): Boolean { //斜率公式 //(y1-y0)/(x1-x0)=(yi-y0)/(xi-x0) //变化乘积形式 //(y1-y0)*(xi-x0)==(x1-x0)*(yi-y0) //时间复杂度 O(n) for (i in 2 until c.size){ if((c[1][1]-c[0][1])*(c[i][0]-c[0][0])!=(c[i][1]-c[0][1])*(c[1][0]-c[0][0])){ return false } } return true } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,389
MyLeetCode
Apache License 2.0
merlin-core/src/main/java/de/micromata/merlin/data/Data.kt
micromata
145,080,847
false
null
package de.micromata.merlin.data import org.apache.commons.lang3.StringUtils import java.util.* open class Data(private val type: String) { private val properties: MutableMap<String, Any?> = HashMap() fun put(property: String?, value: Any?) { properties[property!!] = value if (value != null) { val maxLength = getMaxLength(type, property) val length = value.toString().length if (length > maxLength) { setMaxLength(type, property, length) } } } fun getString(property: String): String? { val value = getValue(property) return value?.toString() } fun getRightPadString(property: String): String { return getRightPadString(property, 0) } fun getRightPadString(prefix: String?, property: String, suffix: String?): String { val offset = StringUtils.length(prefix) + StringUtils.length(suffix) val str = getString(property) return StringUtils.rightPad( StringUtils.defaultString(prefix) + str + StringUtils.defaultString(suffix), getMaxLength( type, property ) + offset ) } /** * @param property the property for [.getString]. * @param offset offset for [StringUtils.rightPad] * @return Formatted string with fixed length of length of longest property of this type. */ fun getRightPadString(property: String, offset: Int): String { val str = getString(property) return StringUtils.rightPad( str, getMaxLength( type, property ) + offset ) } fun getMaxLength(property: String): Int { return getMaxLength(type, property) } fun getValue(property: String): Any? { return properties[property] } fun getBoolean(property: String): Boolean? { val value = getString(property) ?: return null return value.lowercase() in arrayOf("1", "y", "yes", "t", "true", "ja", "j") } companion object { // Stores max length of all properties of same type for formatting output (rightPad). private val maxPropertyLength: MutableMap<String, Int> = HashMap() private fun getMaxLength(type: String, property: String): Int { val maxLength = maxPropertyLength["$type.$property"] return maxLength ?: 0 } private fun setMaxLength(type: String, property: String, maxLength: Int) { maxPropertyLength["$type.$property"] = maxLength } } }
5
Java
4
16
091890ab85f625f76216aacda4b4ce04e42ad98e
2,574
Merlin
Apache License 2.0
src/test/kotlin/dev/bogwalk/batch7/Problem74Test.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch7 import dev.bogwalk.util.tests.Benchmark import kotlin.test.Test import kotlin.test.assertEquals import dev.bogwalk.util.tests.compareSpeed import dev.bogwalk.util.tests.getSpeed import kotlin.test.assertContentEquals internal class DigitFactorialChainsTest { private val tool = DigitFactorialChains() @Test fun `HR Problem correct for lower constraints`() { val input = listOf( 10 to 1, 24 to 3, 29 to 2, 147 to 1, 175 to 7, 210 to 2, 221 to 7, 258 to 4, 261 to 4, 265 to 8, 273 to 4 ) val expected = listOf( listOf(1, 2), emptyList(), listOf(0, 10, 11), listOf(1, 2, 145), listOf(24, 42, 104, 114, 140, 141), listOf(0, 10, 11, 154), listOf(24, 42, 104, 114, 140, 141), listOf(78, 87, 196, 236), listOf(78, 87, 196, 236), listOf(4, 27, 39, 72, 93, 107, 117, 170, 171), listOf(78, 87, 196, 236, 263) ) val solutions = listOf( tool::digitFactorialChainStarters, tool::digitFactorialChainStartersImproved, tool::digitFactorialChainStartersOptimised ) for ((i, e) in expected.withIndex()) { val (limit, length) = input[i] for (solution in solutions) { assertContentEquals( e, solution(limit, length), "Incorrect $limit, $length" ) } } } @Test fun `HR Problem correct for mid constraints`() { val input = listOf( 1999 to 50, 4000 to 60, 10_000 to 30 ) val expectedSizes = listOf(24, 6, 146) val expectedHeads = listOf( listOf(289, 298, 366, 466, 636, 646), listOf(1479, 1497, 1749, 1794, 1947, 1974), listOf(44, 126, 146, 162, 164, 206) ) val solutions = listOf( tool::digitFactorialChainStarters, tool::digitFactorialChainStartersImproved, tool::digitFactorialChainStartersOptimised ) for ((i, e) in expectedSizes.withIndex()) { val (limit, length) = input[i] for (solution in solutions) { val actual = solution(limit, length) assertEquals(e, actual.size, "Incorrect $limit, $length") assertContentEquals( expectedHeads[i], actual.take(6), "Incorrect $limit, $length" ) } } } @Test fun `HR problem correct for factorions`() { val limit = 1_000_000 val length = 1 val expected = listOf(1, 2, 145, 40585) assertContentEquals(expected, tool.digitFactorialChainStarters(limit, length)) assertContentEquals(expected, tool.digitFactorialChainStartersImproved(limit, length)) assertContentEquals(expected, tool.digitFactorialChainStartersOptimised(limit, length)) } @Test fun `HR problem speed for upper constraints`() { val limit = 1_000_000 val length = 10 val expectedSize = 26837 val solutions = mapOf( "Original" to tool::digitFactorialChainStarters, "Improved" to tool::digitFactorialChainStartersImproved, "Optimised" to tool::digitFactorialChainStartersOptimised ) val speeds = mutableListOf<Pair<String, Benchmark>>() for ((name, solution) in solutions) { getSpeed(solution, limit, length).run { speeds.add(name to second) assertEquals(expectedSize, first.size) } } compareSpeed(speeds) } @Test fun `PR problem correct`() { val limit = 1_000_000 val length = 60 val expectedSize = 402 val actual = tool.digitFactorialChainStarters(limit, length) assertEquals(expectedSize, actual.size) } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,862
project-euler-kotlin
MIT License
src/main/kotlin/co/csadev/advent2021/Day11.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 11 * Problem Description: http://adventofcode.com/2021/day/11 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Point2D import co.csadev.adventOfCode.Resources.resourceAsList class Day11(override val input: List<String> = resourceAsList("21day11.txt")) : BaseDay<List<String>, Int, Int> { private val octopuses = input.flatMapIndexed { y, l -> l.mapIndexed { x, o -> Point2D(x, y) to "$o".toInt() } }.toMap().toMutableMap() private val steps by lazy { octopuses.step() } override fun solvePart1() = steps.take(100).sum() override fun solvePart2() = steps.takeWhile { it < 100 }.count() + 101 private fun MutableMap<Point2D, Int>.step() = sequence { val flashes = mutableListOf<Point2D>() while (true) { // First, the energy level of each octopus increases by 1. forEach { (pos, energy) -> octopuses[pos] = energy + 1 } // Then, any octopus with an energy level greater than 9 flashes. // This increases the energy level of all adjacent octopuses by 1, // including octopuses that are diagonally adjacent. // If this causes an octopus to have an energy level greater than 9, it also flashes. // This process continues as long as new octopuses keep having their energy level // increased beyond 9. (An octopus can only flash at most once per step.) do { val toFlash = filter { it.value > 9 && !flashes.contains(it.key) } toFlash.keys.flatMap { it.neighbors }.forEach { octopuses[it]?.let { e -> octopuses[it] = e + 1 } } flashes.addAll(toFlash.keys) } while (toFlash.isNotEmpty()) // Finally, any octopus that flashed during this step has its energy level set to 0, // as it used all of its energy to flash. flashes.forEach { octopuses[it] = 0 } yield(flashes.size).also { flashes.clear() } } } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,180
advent-of-kotlin
Apache License 2.0
src/main/kotlin/dilivia/s2/coords/S2Projection.kt
Enovea
409,487,197
false
{"Kotlin": 3249710}
/* * Copyright © 2021 Enovea (<EMAIL>) * * 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 dilivia.s2.coords /** * Defines a projection of sphere cells to the cube-space. * * This interface defines various constants that describe the shapes and sizes of S2Cells. * They are useful for deciding which cell level to use in order to satisfy a given condition (e.g. that cell vertices * must be no further than "x" apart). All of the raw constants are differential quantities; you can use the * getValue(level) method to compute the corresponding length or area on the unit sphere for cells at a given level. * The minimum and maximum bounds are valid for cells at all levels, but they may be somewhat conservative for very * large cells (e.g. face cells). * * Three different projections from cell-space (s,t) to cube-space (u,v) are implemented: linear, quadratic, and * tangent. They have the following tradeoffs: * * Linear - This is the fastest transformation, but also produces the least * uniform cell sizes. Cell areas vary by a factor of about 5.2, with the * largest cells at the center of each face and the smallest cells in * the corners. * * Tangent - Transforming the coordinates via atan() makes the cell sizes * more uniform. The areas vary by a maximum ratio of 1.4 as opposed to a * maximum ratio of 5.2. However, each call to atan() is about as expensive * as all of the other calculations combined when converting from points to * cell ids, i.e. it reduces performance by a factor of 3. * * Quadratic - This is an approximation of the tangent projection that * is much faster and produces cells that are almost as uniform in size. * It is about 3 times faster than the tangent projection for converting * cell ids to points or vice versa. Cell areas vary by a maximum ratio of * about 2.1. * * Here is a table comparing the cell uniformity using each projection. "Area ratio" is the maximum ratio over all * subdivision levels of the largest cell area to the smallest cell area at that level, "edge ratio" is the maximum * ratio of the longest edge of any cell to the shortest edge of any cell at the same level, and "diag ratio" is the * ratio of the longest diagonal of any cell to the shortest diagonal of any cell at the same level. "ToPoint" and * "FromPoint" are the times in microseconds required to convert cell ids to and from points (unit vectors) * respectively. "ToPointRaw" is the time to convert to a non-unit-length vector, which is all that is needed for * some purposes. * * Area Edge Diag ToPointRaw ToPoint FromPoint * Ratio Ratio Ratio (microseconds) * ------------------------------------------------------------------- * Linear: 5.200 2.117 2.959 0.020 0.087 0.085 * Tangent: 1.414 1.414 1.704 0.237 0.299 0.258 * Quadratic: 2.082 1.802 1.932 0.033 0.096 0.108 * * The worst-case cell aspect ratios are about the same with all three projections. The maximum ratio of the longest * edge to the shortest edge within the same cell is about 1.4 and the maximum ratio of the diagonals within the same * cell is about 1.7. * * This data was produced using s2cell_test and s2cell_id_test. * * This class is a port of s2coords and s2metrics of the Google S2 Geometry project * (https://github.com/google/s2geometry). * * @author <NAME> <<EMAIL>> * @since 1.0 */ interface S2Projection { /** * Convert an s- or t-value to the corresponding u- or v-value. This is a non-linear transformation from [-1,1] to * [-1,1] that attempts to make the cell sizes more uniform. * * @param s s- or t-value (cell-space). * @return u- or v-value */ fun stToUv(s: Double): Double /** * The inverse of the stToUV transformation. Note that it is not always true that UVtoST(STtoUV(x)) == x due to * numerical errors. * * @param u u- or v-value (cube-space). * @return s- or t-value */ fun uvToSt(u: Double): Double /** * Cell minimum angle span. * * Each cell is bounded by four planes passing through its four edges and the center of the sphere. These metrics * relate to the angle between each pair of opposite bounding planes, or equivalently, between the planes * corresponding to two different s-values or two different t-values. For example, the maximum angle between * opposite bounding planes for a cell at level k is kMaxAngleSpan.getValue(k), and the average angle span for all * cells at level k is approximately kAvgAngleSpan.getValue(k). */ val kMinAngleSpan: LengthMetric /** * Cell maximum angle span. * @see kMinAngleSpan */ val kMaxAngleSpan: LengthMetric /** * Cell average angle span. * @see kMinAngleSpan */ val kAvgAngleSpan: LengthMetric /** * Cell min width * * The width of geometric figure is defined as the distance between two parallel bounding lines in a given * direction. For cells, the minimum width is always attained between two opposite edges, and the maximum width is * attained between two opposite vertices. However, for our purposes we redefine the width of a cell as the * perpendicular distance between a pair of opposite edges. A cell therefore has two widths, one in each direction. * The minimum width according to this definition agrees with the classic geometric one, but the maximum width is * different. (The maximum geometric width corresponds to kMaxDiag defined below.) * * For a cell at level k, the distance between opposite edges is at least kMinWidth.getValue(k) and at most * kMaxWidth.getValue(k). The average width in both directions for all cells at level k is approximately * kAvgWidth.getValue(k). * * The width is useful for bounding the minimum or maximum distance from a point on one edge of a cell to the * closest point on the opposite edge. For example, this is useful when "growing" regions by a fixed distance. * * Note that because S2Cells are not usually rectangles, the minimum width of a cell is generally smaller than its * minimum edge length. (The interior angles of an S2Cell range from 60 to 120 degrees.) */ val kMinWidth: LengthMetric /** * Cell max width * * @see kMinWidth */ val kMaxWidth: LengthMetric /** * Cell average width * * @see kMinWidth */ val kAvgWidth: LengthMetric /** * Cell min edge. * * The minimum edge length of any cell at level k is at least kMinEdge.getValue(k), and the maximum is at most * kMaxEdge.getValue(k). The average edge length is approximately kAvgEdge.getValue(k). * * The edge length metrics can also be used to bound the minimum, maximum, or average distance from the center of * one cell to the center of one of its edge neighbors. In particular, it can be used to bound the distance * between adjacent cell centers along the space-filling Hilbert curve for cells at any given level. */ val kMinEdge: LengthMetric /** * Cell max edge. * @see kMinEdge */ val kMaxEdge: LengthMetric /** * Cell average edge. * @see kMinEdge */ val kAvgEdge: LengthMetric /** * Cell minimum diagonal. * * The minimum diagonal length of any cell at level k is at least kMinDiag.getValue(k), and the maximum is at most * kMaxDiag.getValue(k). The average diagonal length is approximately kAvgDiag.getValue(k). * * The maximum diagonal also happens to be the maximum diameter of any cell, and also the maximum geometric width * (see the discussion above). So for example, the distance from an arbitrary point to the closest cell center * at a given level is at most half the maximum diagonal length. */ val kMinDiag: LengthMetric /** * Cell maximum diagonal * @see kMinDiag */ val kMaxDiag: LengthMetric /** * Cell average diagonal * @see kMinDiag */ val kAvgDiag: LengthMetric /** * Minimum cell area. * * The minimum area of any cell at level k is at least kMinArea.getValue(k), and the maximum is at most * kMaxArea.getValue(k). The average area of all cells at level k is exactly kAvgArea.getValue(k). */ val kMinArea: AreaMetric /** * Maximum cell area. * @see kMinArea */ val kMaxArea: AreaMetric /** * Maximum average area. * @see kMinArea */ val kAvgArea: AreaMetric /** * This is the maximum edge aspect ratio over all cells at any level, where the edge aspect ratio of a cell is * defined as the ratio of its longest edge length to its shortest edge length. */ val kMaxEdgeAspect: Double /** * This is the maximum diagonal aspect ratio over all cells at any level, where the diagonal aspect ratio of a cell * is defined as the ratio of its longest diagonal length to its shortest diagonal length. */ val kMaxDiagAspect: Double }
0
Kotlin
3
17
eb5139ec5c69556e8dc19c864b052e7e45a48b49
9,786
s2-geometry-kotlin
Apache License 2.0
src/questions/LongestCommonPrefix.kt
realpacific
234,499,820
false
null
package questions import kotlin.test.assertEquals /** * Write a function to find the longest common prefix string amongst an array of strings. * If there is no common prefix, return an empty string "". */ fun longestCommonPrefix(strs: Array<String>): String { var result = "" var i = 0 // Infinite loop: this way we don't have to find the shortest word while (true) { // Get element at index i val b = strs.map { it.getOrNull(i) }.toSet() // if contains null, then at least one of the element ran out of letters if (b.contains(null)) { break } // size of set == 1 then all contents same i.e. same character if (b.size == 1) { result += b.elementAt(0) i++ } else { break } } return result } fun main() { assertEquals("fl", longestCommonPrefix(arrayOf("flower", "flow", "flight"))) assertEquals("flo", longestCommonPrefix(arrayOf("flower", "flow", "floor"))) assertEquals("fl", longestCommonPrefix(arrayOf("flow", "flew", "flown"))) assertEquals("flower", longestCommonPrefix(arrayOf("flower", "flowers"))) assertEquals("", longestCommonPrefix(arrayOf("dog", "racecar", "car"))) assertEquals("", longestCommonPrefix(arrayOf("", ""))) assertEquals("", longestCommonPrefix(arrayOf(""))) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,362
algorithms
MIT License
src/Day21.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
sealed class MonkeyWithJob data class YellingMonkey(var number: Long) : MonkeyWithJob() class ComputingMonkey( private val operation: String, val left: String, val right: String ) : MonkeyWithJob() { val compute: ((Long, Long) -> Long) = when(operation) { "+" -> { x, y -> x + y } "-" -> { x, y -> x - y } "*" -> { x, y -> x * y } "/" -> { x, y -> x / y } else -> error("Unknown operation: $operation") } fun invertLeftKnown(result: Long, left: Long): Long { val right = when(operation) { "+" -> result - left "-" -> -result + left "*" -> result / left "/" -> result / left else -> error("Unknown operation: $operation") } checkInversion(result, left, right) return right } fun invertRightKnown(result: Long, right: Long): Long { val left = when(operation) { "+" -> result - right "-" -> result + right "*" -> result / right "/" -> result * right else -> error("Unknown operation: $operation") } checkInversion(result, left, right) return left } private fun checkInversion(result: Long, left: Long, right: Long) { when (operation) { "+" -> check(left + right == result) { "$left + $right != $result" } "-" -> check(left - right == result) { "$left - $right != $result" } "*" -> check(left * right == result) { "$left * $right != $result" } "/" -> check(left / right == result) { "$left / $right != $result" } } } override fun toString(): String { return "ComputingMonkey ($left $operation $right)" } } private typealias MonkeyMap = Map<String, MonkeyWithJob> fun monkeyMapOf(input: List<String>): MonkeyMap { return input.associate { line -> val name = line.substringBefore(":") val secondPart = line.substringAfter(":").trim() val number = secondPart.toLongOrNull() if (number == null) { val (left, op, right) = secondPart.split(" ") name to ComputingMonkey(op, left, right) } else { name to YellingMonkey(number) } } } private fun MonkeyMap.resultFor(name: String, visitor: ((String) -> Unit)? = null): Long { visitor?.invoke(name) return when (val monkey = this[name]!!) { is YellingMonkey -> monkey.number is ComputingMonkey -> monkey.compute(resultFor(monkey.left, visitor), resultFor(monkey.right, visitor)) } } private fun MonkeyMap.containsHuman(name: String): Pair<Boolean, Long> { var isHuman = false val result = resultFor(name) { if (it == "humn") isHuman = true } return isHuman to result } private fun MonkeyMap.computeHumanFor(expected: Long, name: String) { when (val monkey = this[name]!!) { is YellingMonkey -> monkey.number is ComputingMonkey -> { if (monkey.left == "humn") { human.number = monkey.invertRightKnown(expected, resultFor(monkey.right)) } else if (monkey.right == "humn") { human.number = monkey.invertLeftKnown(expected, resultFor(monkey.left)) } else { val (leftContainsHuman, leftResult) = containsHuman(monkey.left) val (rightContainsHuman, rightResult) = containsHuman(monkey.right) if (leftContainsHuman) { computeHumanFor(monkey.invertRightKnown(expected, rightResult), monkey.left) } else if (rightContainsHuman) { computeHumanFor(monkey.invertLeftKnown(expected, leftResult), monkey.right) } } } } } private val MonkeyMap.human: YellingMonkey get() = this["humn"] as YellingMonkey fun main() { fun part1(input: List<String>): Long { return monkeyMapOf(input).resultFor("root") } fun part2(input: List<String>): Long { val monkeys = monkeyMapOf(input) val root = monkeys["root"] as ComputingMonkey val (leftContainsHuman, leftResult) = monkeys.containsHuman(root.left) val (rightContainsHuman, rightResult) = monkeys.containsHuman(root.right) if (leftContainsHuman && rightContainsHuman) { error("Too difficult, both branches are variable") } else if (leftContainsHuman) { monkeys.computeHumanFor(rightResult, root.left) } else if (rightContainsHuman) { monkeys.computeHumanFor(leftResult, root.right) } else { error("No branch contains a human") } return monkeys.human.number } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput) == 152L) val input = readInput("Day21") check(part1(input) == 152479825094094L) check(part2(input) == 3360561285172L) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
4,987
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/io/binarysearch/TwoNumberSum.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.binarysearch // https://leetcode.com/explore/learn/card/binary-search/144/more-practices/1035/ class TwoNumberSum { fun executeSimpler(numbers: IntArray, target: Int): IntArray { var index1 = 0 var index2 = numbers.size - 1 while (numbers[index1] + numbers[index2] != target) { val sum = numbers[index1] + numbers[index2] if (sum > target) { index2-- } else if (sum < target) { index1++ } } return intArrayOf(index1 + 1, index2 + 1) } fun execute(numbers: IntArray, target: Int): IntArray { numbers.mapIndexed { index, value -> binarySearch(numbers, target - value, index)?.let { otherIndex -> return intArrayOf(index + 1, otherIndex + 1) } } return intArrayOf() } fun binarySearch(input: IntArray, target: Int, excludeIndex: Int): Int? { var start = 0 var end = input.size - 1 while (start <= end) { val pivot = start + (end - start) / 2 val value = input[pivot] when { value == target -> return when { pivot != excludeIndex -> pivot input.getOrNull(pivot - 1) == value -> pivot - 1 input.getOrNull(pivot + 1) == value -> pivot + 1 else -> null } value < target -> { start = pivot + 1 } else -> end = pivot - 1 } } return null } } fun main() { }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,402
coding
MIT License
src/main/kotlin/uk/neilgall/kanren/MicroKanren.kt
neilgall
132,669,065
false
null
package uk.neilgall.kanren typealias Substitutions = Map<out Term, Term> typealias Goal = (State) -> Sequence<State> data class State(val subs: Substitutions = mapOf(), val vars: Int = 0) { fun adding(newSubs: Substitutions): State { return State(subs + newSubs, vars) } fun withNewVar(f: (Term) -> Goal): Sequence<State> { val newVar = Term.Variable(vars) val newState = State(subs, vars + 1) val goal = f(newVar) return goal(newState) } override fun toString(): String = "[" + subs.map { "${it.key} = ${it.value}" }.joinToString(", ") + "]" } fun State.walk(t: Term): Term { fun substitute(term: Term): Term { val sub = subs[term] return if (sub != null) walk(sub) else term } return when (t) { is Term.Variable -> substitute(t) is Term.Pair -> Term.Pair(substitute(t.p), substitute(t.q)) is Term.BinaryExpr -> t.op.evaluate(substitute(t.lhs), substitute(t.rhs)) ?: t else -> t } } fun State.unifyExpr(lhs: Term, rhs: Term): Sequence<Substitutions>? { val unified: Sequence<Substitutions> = sequenceOf(mapOf()) return when { lhs is Term.None && rhs is Term.None -> unified lhs is Term.String && rhs is Term.String -> if (lhs.s == rhs.s) unified else null lhs is Term.Int && rhs is Term.Int -> if (lhs.i == rhs.i) unified else null lhs is Term.Boolean && rhs is Term.Boolean -> if (lhs.b == rhs.b) unified else null lhs is Term.Pair && rhs is Term.Pair -> { val ps = unifyExpr(lhs.p, rhs.p) val qs = unifyExpr(lhs.q, rhs.q) if (qs == null) null else ps?.flatMap { p -> qs.map { q -> p + q } } } lhs is Term.Variable -> sequenceOf(mapOf(lhs to rhs)) rhs is Term.Variable -> sequenceOf(mapOf(rhs to lhs)) lhs is Term.BinaryExpr -> when { lhs.lhs is Term.Variable -> lhs.op.reverseEvaluateLHS(lhs.rhs, rhs)?.map { mapOf(lhs.lhs to it) } lhs.rhs is Term.Variable -> lhs.op.reverseEvaluateRHS(lhs.lhs, rhs)?.map { mapOf(lhs.rhs to it) } else -> null } rhs is Term.BinaryExpr -> when { rhs.lhs is Term.Variable -> rhs.op.reverseEvaluateLHS(rhs.rhs, lhs)?.map { mapOf(rhs.lhs to it) } rhs.rhs is Term.Variable -> rhs.op.reverseEvaluateRHS(rhs.lhs, lhs)?.map { mapOf(rhs.rhs to it) } else -> null } else -> null } } fun State.unify(lhs: Term, rhs: Term): Sequence<State> = unifyExpr(walk(lhs), walk(rhs))?.map { adding(it) } ?: sequenceOf() fun State.disunify(lhs: Term, rhs: Term): Sequence<State> = unifyExpr(walk(lhs), walk(rhs))?.flatMap { sequenceOf<State>() } ?: sequenceOf(this) fun <T: Any> lazy(t: T): Sequence<T> = generateSequence({ t }, { null }) // Ensure the sequence generated by a goal is lazy fun zzz(g: Goal): Goal = { state -> generateSequence( { val it = g(state).iterator(); if (it.hasNext()) it else null }, { if (it.hasNext()) it else null } ).map { it.next() } }
0
Kotlin
1
16
28ab8ce1826149735a049f180446ba2a68d39780
3,101
KotlinKanren
MIT License
src/day24/Code.kt
fcolasuonno
225,219,560
false
null
package day24 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.withIndex().flatMap { (j, s) -> s.withIndex().mapNotNull { (i, c) -> if (c == '#') i to j else null } }.toSet() fun part1(input: Set<Pair<Int, Int>>) = mutableSetOf<Set<Pair<Int, Int>>>().let { seen -> generateSequence(input) { prev -> (prev.flatMap { it.neighbours() }.filter { it !in prev && it.neighbours().count { it in prev } in 1..2 } + prev.filter { it.neighbours().count { it in prev } == 1 }).toSet() }.first { state -> (state in seen).also { seen.add(state) } }.sumBy { 1 shl (it.second * 5 + it.first) } } fun part2(initialInput: Set<Pair<Int, Int>>) = initialInput.map { Triple(it.first, it.second, 0) }.toSet().let { input -> generateSequence(input) { prev -> (prev.flatMap { it.neighbours() }.filter { it !in prev && it.neighbours().count { it in prev } in 1..2 } + prev.filter { it.neighbours().count { it in prev } == 1 }).toSet() }.take(1 + 200).last().size } private fun Triple<Int, Int, Int>.neighbours() = when { first == 2 && second == 1 -> listOf( copy(first = first - 1), copy(second = second - 1), copy(first = first + 1), copy(first = 0, second = 0, third = third + 1), copy(first = 1, second = 0, third = third + 1), copy(first = 2, second = 0, third = third + 1), copy(first = 3, second = 0, third = third + 1), copy(first = 4, second = 0, third = third + 1) ) first == 2 && second == 3 -> listOf( copy(first = first - 1), copy(first = first + 1), copy(second = second + 1), copy(first = 0, second = 4, third = third + 1), copy(first = 1, second = 4, third = third + 1), copy(first = 2, second = 4, third = third + 1), copy(first = 3, second = 4, third = third + 1), copy(first = 4, second = 4, third = third + 1) ) first == 1 && second == 2 -> listOf( copy(first = first - 1), copy(second = second - 1), copy(second = second + 1), copy(first = 0, second = 0, third = third + 1), copy(first = 0, second = 1, third = third + 1), copy(first = 0, second = 2, third = third + 1), copy(first = 0, second = 3, third = third + 1), copy(first = 0, second = 4, third = third + 1) ) first == 3 && second == 2 -> listOf( copy(second = second - 1), copy(first = first + 1), copy(second = second + 1), copy(first = 4, second = 0, third = third + 1), copy(first = 4, second = 1, third = third + 1), copy(first = 4, second = 2, third = third + 1), copy(first = 4, second = 3, third = third + 1), copy(first = 4, second = 4, third = third + 1) ) else -> listOf( if (first == 0) copy(first = 1, second = 2, third = third - 1) else copy(first = first - 1), if (second == 0) copy(first = 2, second = 1, third = third - 1) else copy(second = second - 1), if (first == 4) copy(first = 3, second = 2, third = third - 1) else copy(first = first + 1), if (second == 4) copy(first = 2, second = 3, third = third - 1) else copy(second = second + 1) ) } private fun Pair<Int, Int>.neighbours() = listOf( copy(first = first - 1), copy(second = second - 1), copy(first = first + 1), copy(second = second + 1) ).filter { it.first in 0 until 5 && it.second in 0 until 5 }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
3,824
AOC2019
MIT License
src/day6/Code.kt
fcolasuonno
225,219,560
false
null
package day6 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.map { it.split(')').let { it[0] to it[1] } }.requireNoNulls().groupBy({ it.first }) { it.second } fun part1(input: Map<String, List<String>>) = generateSequence(listOf("COM")) { it.mapNotNull { input[it] }.flatten().takeIf { it.isNotEmpty() } }.map { it.size }.foldIndexed(0) { rank, acc, size -> acc + size * rank } fun part2(input: Map<String, List<String>>): Any? { val reverseMap = input.flatMap { entry -> entry.value.map { it to entry.key } }.toMap() val yourOrbits = generateSequence("YOU") { reverseMap[it] }.toSet() val santaOrbits = generateSequence("SAN") { reverseMap[it] }.toSet() return ((yourOrbits - santaOrbits).size - 1) + ((santaOrbits - yourOrbits).size - 1) }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
1,110
AOC2019
MIT License
src/main/kotlin/me/peckb/aoc/pathing/Dijkstra.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc.pathing import java.util.PriorityQueue /** * NOTE: whatever class you use for `Node` should be a `data class` */ interface Dijkstra<Node, Cost : Comparable<Cost>, NodeWithCost: DijkstraNodeWithCost<Node, Cost>> { fun solve(start: Node, end: Node? = null, comparator: Comparator<Node>? = null): MutableMap<Node, Cost> { val toVisit = PriorityQueue<NodeWithCost>().apply { add(start.withCost(minCost())) } val visited = mutableSetOf<Node>() val currentCosts = mutableMapOf<Node, Cost>() .withDefault { maxCost() } .apply { this[start] = minCost() } while (toVisit.isNotEmpty()) { val current: NodeWithCost = toVisit.poll().also { visited.add(it.node()) } val foundEnd: Boolean? = end?.let { node: Node -> comparator?.let { it.compare(current.node(), end) == 0 } ?: (current.node() == node) } if (foundEnd == true) return currentCosts current.neighbors().forEach { neighbor -> if (!visited.contains(neighbor.node())) { val newCost = current.cost() + neighbor.cost() if (newCost < currentCosts.getValue(neighbor.node())) { currentCosts[neighbor.node()] = newCost toVisit.add(neighbor.node().withCost(newCost)) } } } } return currentCosts } infix operator fun Cost.plus(cost: Cost): Cost fun Node.withCost(cost: Cost): NodeWithCost fun minCost(): Cost fun maxCost(): Cost } interface DijkstraNodeWithCost<Node, Cost> : Comparable<DijkstraNodeWithCost<Node, Cost>> { fun neighbors(): List<DijkstraNodeWithCost<Node, Cost>> fun node(): Node fun cost(): Cost }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
1,653
advent-of-code
MIT License
src/pl/shockah/aoc/y2015/Day18.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2015 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.unikorn.collection.Array2D class Day18: AdventTask<Array2D<Boolean>, Int, Int>(2015, 18) { override fun parseInput(rawInput: String): Array2D<Boolean> { val lines = rawInput.lines() return Array2D(lines[0].length, lines.size) { x, y -> lines[y][x] == '#' } } private fun task(input: Array2D<Boolean>, steps: Int, cornerOn: Boolean): Int { fun advance(grid: Array2D<Boolean>): Array2D<Boolean> { fun activeNeighbors(x: Int, y: Int): Int { return ((y - 1)..(y + 1)).map { yy -> ((x - 1)..(x + 1)).map isActive@ { xx -> if (xx < 0 || yy < 0 || xx >= grid.width || yy >= grid.height || (xx == x && yy == y)) return@isActive 0 else return@isActive if (grid[xx, yy]) 1 else 0 }.sum() }.sum() } return Array2D(grid.width, grid.height) { x, y -> if (cornerOn && ((x == 0 && (y == 0 || y == grid.height - 1)) || (x == grid.width - 1 && (y == 0 || y == grid.height - 1)))) return@Array2D true if (grid[x, y]) return@Array2D activeNeighbors(x, y) in 2..3 else return@Array2D activeNeighbors(x, y) == 3 } } var current = input if (cornerOn) { current = Array2D(current.width, current.height) { x, y -> if ((x == 0 && (y == 0 || y == current.height - 1)) || (x == current.width - 1 && (y == 0 || y == current.height - 1))) return@Array2D true else return@Array2D current[x, y] } } repeat(steps) { current = advance(current) } return current.toList().filter { it }.size } override fun part1(input: Array2D<Boolean>): Int { return task(input, 100, false) } override fun part2(input: Array2D<Boolean>): Int { return task(input, 100, true) } class Tests { private val task = Day18() private val rawInput = """ .#.#.# ...##. #....# ..#... #.#..# ####.. """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(4, task.task(input, 4, false)) } @Test fun part2() { val input = task.parseInput(rawInput) Assertions.assertEquals(17, task.task(input, 5, true)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
2,244
Advent-of-Code
Apache License 2.0
solutions/mediansort/medianSort.kt
arcadioramos
418,717,198
true
{"Java": 85120, "Elixir": 51650, "Go": 50067, "Ruby": 24382, "Scala": 19921, "Dart": 19382, "JavaScript": 14831, "Python": 10246, "Rust": 6885, "Clojure": 5403, "F#": 3328, "Kotlin": 2040, "C#": 1590}
fun main(){ var (a, b, c) = readLine()!!.split(' ') var testCases = a.toInt() var numOfElemnts = b.toInt() var numOfQueries = c.toInt() while(testCases > 0){ if(!medianSort(numOfElemnts, numOfQueries)) return } testCases = testCases - 1 } // Median Sort fun medianSort( nE: Int, nQ: Int): Boolean{ var nQL = nQ var numbers = intArrayOf(1,2) for (i in 3..nE+1){ var left = 0 var right = numbers.size-1 while (right - left >= 1 && nQL > 0){ var leftP = left + ((right-left)/3) var rightP = right - ((right-left)/3) println(" ${numbers[leftP]} ${numbers[rightP]} ${i}") System.out.flush() var med = readLine()!!.toInt() nQL = nQL-1 if(med == numbers[leftP]){ right = leftP - 1 if(left == right){ right += 1 } }else if(med == numbers[rightP]){ left = rightP + 1 if(left == right){ left -= 1 } }else{ left = leftP + 1 right = rightP - 1 if(left == right){ left -= 1 } } } numbers = insertAt(numbers, i, left) } return output(numbers) } fun output(numbers: IntArray): Boolean{ println(numbers.contentToString()) System.out.flush() var response = readLine()!!.toInt() return response == 1 } fun insertAt(arr: IntArray, key: Int, index: Int): IntArray{ val array = arr.copyOf(arr.size + 1) for(i in 0 until index){ array[i] = arr[i] } array[index] = key for(i in index+1..arr.size){ array[i] = arr[i-1] } return array }
0
Java
0
0
57451e0ea2c9836adfcae8964bda11e4d86eaa94
2,040
google-code-jam
MIT License
src/main/kotlin/turfkt/Conversions.kt
hudsonb
172,511,286
false
null
package turfkt /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ const val EARTH_RADIUS = 6371008.8 /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ private val factors = mapOf( "centimeters" to EARTH_RADIUS * 100, "centimetres" to EARTH_RADIUS * 100, "degrees" to EARTH_RADIUS / 111325, "feet" to EARTH_RADIUS * 3.28084, "inches" to EARTH_RADIUS * 39.370, "kilometers" to EARTH_RADIUS / 1000, "kilometres" to EARTH_RADIUS / 1000, "meters" to EARTH_RADIUS, "metres" to EARTH_RADIUS, "miles" to EARTH_RADIUS / 1609.344, "millimeters" to EARTH_RADIUS * 1000, "millimetres" to EARTH_RADIUS * 1000, "nauticalmiles" to EARTH_RADIUS / 1852, "radians" to 1.0, "yards" to EARTH_RADIUS / 1.0936 ) /** * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit. * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet * * @param radians Radians across the sphere * @param units The length units to convert to. Can be degrees, radians, miles, or kilometers inches, yards, metres, * meters, kilometres, kilometers. Default to kilometers. * @returns The length in the given units. */ fun radiansToLength(radians: Double, units: String = "kilometers"): Double { if(!factors.containsKey(units)) throw IllegalArgumentException("Unrecognized units: $units") val factor = factors[units] ?: throw IllegalStateException("Factor for units $units was null") return radians * factor } /** * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet * * @param distance The distance in real units * @param units The units of the given distance. Can be degrees, radians, miles, or kilometers inches, yards, metres, * meters, kilometres, kilometers. Defaults to kilometers. * @returns The length in radians. */ fun lengthToRadians(distance: Double, units: String = "kilometers"): Double { if(!factors.containsKey(units)) throw IllegalArgumentException("Unrecognized units: $units") val factor = factors[units] ?: throw IllegalStateException("Factor for units $units was null") return distance / factor } /** * Converts a length to the requested unit. * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet * * @param length length to be converted * @param originalUnit [originalUnit="kilometers"] of the length * @param finalUnit [finalUnit="kilometers"] returned unit * @return the converted length */ fun convertLength(length: Double, originalUnit: String = "kilometers", finalUnit: String = "kilometers"): Double { require(length >= 0) { "length must be a positive number" } return radiansToLength(lengthToRadians(length, originalUnit), finalUnit) }
19
Kotlin
1
1
e39bf4f24366bc569129a3b3b2239c1909f6b7f1
3,010
turf.kt
MIT License
src/main/kotlin/com/leetcode/P486.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://leetcode.com/problems/predict-the-winner/ class P486 { fun PredictTheWinner(nums: IntArray): Boolean { if (nums.size <= 2) return true return predict(nums, 0, 0, nums.lastIndex, 1) >= 0 } private fun predict(nums: IntArray, score: Int, l: Int, r: Int, t: Int): Int { if (l > r) return score return if (t % 2 == 0) { // p1 maxOf( predict(nums, score + nums[l], l + 1, r, t * -1), predict(nums, score + nums[r], l, r - 1, t * -1) ) } else { // p2 minOf( predict(nums, score - nums[l], l + 1, r, t * -1), predict(nums, score - nums[r], l, r - 1, t * -1) ) } } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
770
algorithm
MIT License
Kotlin/5 kyu String incrementer.kt
MechaArms
508,384,440
false
{"Kotlin": 22917, "Python": 18312}
/* Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number. the number 1 should be appended to the new string. Examples: foo -> foo1 foobar23 -> foobar24 foo0042 -> foo0043 foo9 -> foo10 foo099 -> foo100 Attention: If the number has leading zeros the amount of digits should be considered. */ //My Solution //=========== fun incrementString(str: String) : String { var numberZ = 0 var wordsZ = "" var number = numberZ.toString() + str.filter({ it -> it.isDigit() }) // Filter only Digits From String var words = wordsZ + str.filter({ it -> it.isLetter() }) // Filter only Letters From String var incNumber: Int = number.toInt() + 1 // incrementing + 1 var newNumber = incNumber.toString() // transforming to string var contZero = number.length // conting the numbers length contZero = contZero.toInt() contZero -- // removing the extra zero val numWithZero = newNumber.padStart(contZero, '0') // add zero // println("'$numWithZero'") // '001' val answer = words + numWithZero return "$answer" } //Clever Solution //=============== fun incrementString(str: String) : String { val s = str.filter { !it.isDigit() } val d = str.filter { it.isDigit() } if (d.length == 0) return s + "1" val n = (d.toInt() + 1).toString() val digit = if (n.length < d.length) "0".repeat(d.length - n.length) + n else n return s + digit } //Best Solution //============= fun incrementString(str: String) : String { val i = str.takeLastWhile { it.isDigit() } return str.dropLast(i.length) + ((i.toIntOrNull() ?: 0) + 1).toString().padStart(i.length, '0') }
0
Kotlin
0
1
b23611677c5e2fe0f7e813ad2cfa21026b8ac6d3
1,873
My-CodeWars-Solutions
MIT License
calendar/day02/Day2.kt
starkwan
573,066,100
false
{"Kotlin": 43097}
package day02 import Day import Lines class Day2 : Day() { override fun part1(input: Lines): Any { return input.map { Round.fromPart1(it).toScore() }.sum() } override fun part2(input: Lines): Any { return input.map { Round.fromPart2(it).toScore() }.sum() } sealed class Shape { object Rock : Shape() object Paper : Shape() object Scissors : Shape() fun toScore() = when (this) { Rock -> 1 Paper -> 2 Scissors -> 3 } fun winDrawLose(opponent: Shape) = when (toScore() - opponent.toScore()) { 1, -2 -> 1 // win 0 -> 0 // draw else -> -1 // lose } companion object { fun from(code: String): Shape { return when (code) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> error("incorrect code") } } private val testShapes = listOf(Rock, Paper, Scissors) fun getMyShapeFromResult(opponent: Shape, result: String): Shape { val expectedResult = when (result) { "Z" -> 1 "Y" -> 0 "X" -> -1 else -> error("incorrect code") } return testShapes.stream().filter { it.winDrawLose(opponent) == expectedResult }.findFirst().get() } } } class Round(val opponentShape: Shape, val myShape: Shape) { companion object { fun fromPart1(line: String): Round { line.split(" ").apply { val opponentShape = Shape.from(this[0]) val myShape = Shape.from(this[1]) return Round(opponentShape, myShape) } } fun fromPart2(line: String): Round { line.split(" ").apply { val opponent = Shape.from(this[0]) val myShape = Shape.getMyShapeFromResult(opponent, this[1]) return Round(opponent, myShape) } } } fun toScore(): Int { val roundScore = when (myShape.winDrawLose(opponentShape)) { 1 -> 6 0 -> 3 else -> 0 } return roundScore + myShape.toScore() } } }
0
Kotlin
0
0
13fb66c6b98d452e0ebfc5440b0cd283f8b7c352
2,488
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LFUCache.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 /** * Least Frequently Used Cache */ interface LFUCache { fun get(key: Int): Int fun put(key: Int, value: Int) } class LFUCacheImpl(capacity: Int) : LFUCache { private val vals = hashMapOf<Int, Int>() private val counts = hashMapOf<Int, Int>() private val lists = hashMapOf<Int, LinkedHashSet<Int>>() private var cap = capacity private var min = -1 init { lists[1] = LinkedHashSet() } override fun get(key: Int): Int { if (!vals.containsKey(key)) { return -1 } val count = counts[key] ?: 0 counts[key] = count + 1 lists[count]?.remove(key) if (count == min && lists[count]?.size == 0) { min++ } if (!lists.containsKey(count + 1)) { lists[count + 1] = LinkedHashSet() } lists[count + 1]?.add(key) return vals[key] ?: -1 } override fun put(key: Int, value: Int) { if (cap <= 0) return if (vals.containsKey(key)) { vals[key] = value get(key) return } if (vals.size >= cap) { val evit = lists[min]?.iterator()?.next() lists[min]?.remove(evit) vals.remove(evit) } vals[key] = value counts[key] = 1 min = 1 lists[1]?.add(key) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,002
kotlab
Apache License 2.0
src/main/kotlin/day10/Day10.kt
daniilsjb
434,765,082
false
{"Kotlin": 77544}
package day10 import java.io.File fun main() { val data = parse("src/main/kotlin/day10/Day10.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 10 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private fun parse(path: String) = File(path).readLines() private fun part1(lines: List<String>): Long { var sum = 0L for (line in lines) { val stack = ArrayDeque<Char>() for (char in line) { when (char) { '(' -> stack.addLast(')') '[' -> stack.addLast(']') '{' -> stack.addLast('}') '<' -> stack.addLast('>') else -> if (char != stack.removeLast()) { when (char) { ')' -> sum += 3 ']' -> sum += 57 '}' -> sum += 1197 '>' -> sum += 25137 } break } } } } return sum } private fun part2(lines: List<String>): Long { val scores = mutableListOf<Long>() outer@ for (line in lines) { val stack = ArrayDeque<Char>() for (char in line) { when (char) { '(' -> stack.addFirst(')') '[' -> stack.addFirst(']') '{' -> stack.addFirst('}') '<' -> stack.addFirst('>') else -> if (char != stack.removeFirst()) { continue@outer } } } val score = stack.fold(0) { acc: Long, expected -> when (expected) { ')' -> acc * 5 + 1 ']' -> acc * 5 + 2 '}' -> acc * 5 + 3 '>' -> acc * 5 + 4 else -> error("Invalid closing character") } } scores.add(score) } return scores.sorted().run { this[size / 2] } }
0
Kotlin
0
1
bcdd709899fd04ec09f5c96c4b9b197364758aea
2,056
advent-of-code-2021
MIT License
assertk/src/commonMain/kotlin/assertk/assertions/support/ListDiffer.kt
willowtreeapps
88,210,079
false
{"Kotlin": 386666, "Java": 133}
package assertk.assertions.support /** * List diffing using the Myers diff algorithm. */ internal object ListDiffer { fun diff(a: List<*>, b: List<*>): List<Edit> { val diff = mutableListOf<Edit>() backtrack(a, b) { prevX, prevY, x, y -> diff.add( 0, when { x == prevX -> Edit.Ins(prevY, b[prevY]) y == prevY -> Edit.Del(prevX, a[prevX]) else -> Edit.Eq(prevX, a[prevX], prevY, b[prevY]) } ) } return diff } sealed class Edit { sealed class Mod : Edit() data class Ins(val newIndex: Int, val newValue: Any?) : Mod() data class Del(val oldIndex: Int, val oldValue: Any?) : Mod() data class Eq(val oldIndex: Int, val oldValue: Any?, val newIndex: Int, val newValue: Any?) : Edit() } private fun shortestEdit(a: List<*>, b: List<*>): List<IntArray> { val n = a.size val m = b.size val max = n + m if (max == 0) { return emptyList() } val v = IntArray(2 * max + 1) val trace = mutableListOf<IntArray>() for (d in 0..max) { trace += v.copyOf() for (k in -d..d step 2) { var x = if (k == -d || (k != d && v.ringIndex(k - 1) < v.ringIndex(k + 1))) { v.ringIndex(k + 1) } else { v.ringIndex(k - 1) + 1 } var y = x - k while (x < n && y < m && a[x] == b[y]) { x += 1 y += 1 } v.ringIndexAssign(k, x) if (x >= n && y >= m) { return trace } } } return trace } private fun IntArray.ringIndex(index: Int): Int = this[if (index < 0) size + index else index] private fun IntArray.ringIndexAssign(index: Int, value: Int) { this[if (index < 0) size + index else index] = value } private fun backtrack(a: List<*>, b: List<*>, yield: (Int, Int, Int, Int) -> Unit) { var x = a.size var y = b.size val shortestEdit = shortestEdit(a, b) for (d in shortestEdit.size - 1 downTo 0) { val v = shortestEdit[d] val k = x - y val prevK = if (k == -d || (k != d && v.ringIndex(k - 1) < v.ringIndex(k + 1))) { k + 1 } else { k - 1 } val prevX = v.ringIndex(prevK) val prevY = prevX - prevK while (x > prevX && y > prevY) { yield(x - 1, y - 1, x, y) x -= 1 y -= 1 } if (d > 0) { yield(prevX, prevY, x, y) } x = prevX y = prevY } } }
31
Kotlin
77
687
5ff8a09f63543a18365dee1bb48dc9c4684aab9e
2,916
assertk
MIT License
src/main/kotlin/leetcode/Problem2044.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/ */ class Problem2044 { fun countMaxOrSubsets(nums: IntArray): Int { var max = 0 for (num in nums) { max = max or num } var answer = 0 for (i in nums.indices) { answer += countMaxOrSubsets(nums, max, i + 1, false, nums[i]) } return answer } private fun countMaxOrSubsets(nums: IntArray, max: Int, index: Int, skipped: Boolean, accu: Int): Int { if (index == nums.size) { return if (!skipped && accu == max) 1 else 0 } val count = if (!skipped && accu == max) 1 else 0 val a = countMaxOrSubsets(nums, max, index + 1, false, accu or nums[index]) val b = countMaxOrSubsets(nums, max, index + 1, true, accu) return a + b + count } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
885
leetcode
MIT License
src/main/kotlin/kt/kotlinalgs/app/searching/QuickSelect.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.searching println("test") val array1 = intArrayOf(3, 2, 1) val array2 = intArrayOf(2000, 234, 21, 41, 1, 21, 75, 0, -4) println(QuickSelect().select(intArrayOf(3, 2, 1), 1)) println(QuickSelect().select(intArrayOf(3, 2, 1), 2)) println(QuickSelect().select(intArrayOf(3, 2, 1), 3)) println(QuickSelect().select(intArrayOf(3, 2, 1), 2)) // runtime: O(N) best + average, O(N^2) worst case // space: O(log N) best + average, O(N) worst case // unstable class QuickSelect { fun select(array: IntArray, k: Int): Int? { if (array.isEmpty() || k < 1 || k > array.size) return null if (k == 1 && array.size == 1) return array[0] // Improvement: Randomize array (avoid worst case when array is sorted) return select(array, k - 1, 0, array.lastIndex) } private fun select(array: IntArray, k: Int, low: Int, high: Int): Int? { if (low == high) { return if (low == k) array[k] else null } val pivot = partition(array, low, high) return when { pivot == k -> array[k] pivot < k -> select(array, k, pivot + 1, high) else -> select(array, k, low, pivot - 1) } } private fun partition(array: IntArray, low: Int, high: Int): Int { val pivotIndex = low + (high - low) / 2 val pivot = array[pivotIndex] exchange(array, low, pivotIndex) var left = low + 1 var right = high while (left <= right) { while (left < array.size && array[left] < pivot) left++ while (right >= 0 && array[right] > pivot) right-- if (left <= right) { exchange(array, left, right) left++ right-- } } exchange(array, low, right) return right } private fun exchange(array: IntArray, firstIndex: Int, secondIndex: Int) { val temp = array[firstIndex] array[firstIndex] = array[secondIndex] array[secondIndex] = temp } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,067
KotlinAlgs
MIT License
kotlin/structures/KdTreePointQuery.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures import java.util.Random class KdTreePointQuery(var x: IntArray, var y: IntArray) { fun build(low: Int, high: Int, divX: Boolean) { if (high - low <= 1) return val mid = low + high ushr 1 nth_element(low, high, mid, divX) build(low, mid, !divX) build(mid + 1, high, !divX) } // See http://www.cplusplus.com/reference/algorithm/nth_element fun nth_element(low: Int, high: Int, n: Int, divX: Boolean) { var low = low var high = high while (true) { val k = partition(low, high, low + rnd.nextInt(high - low), divX) if (n < k) high = k else if (n > k) low = k + 1 else return } } fun partition(fromInclusive: Int, toExclusive: Int, separatorIndex: Int, divX: Boolean): Int { var i = fromInclusive var j = toExclusive - 1 if (i >= j) return j val separator = if (divX) x[separatorIndex] else y[separatorIndex] swap(i++, separatorIndex) while (i <= j) { while (i <= j && (if (divX) x[i] else y[i]) < separator) ++i while (i <= j && (if (divX) x[j] else y[j]) > separator) --j if (i >= j) break swap(i++, j--) } swap(j, fromInclusive) return j } fun swap(i: Int, j: Int) { var t = x[i] x[i] = x[j] x[j] = t t = y[i] y[i] = y[j] y[j] = t } var bestDist: Long = 0 var bestNode = 0 fun findNearestNeighbour(px: Int, py: Int): Int { bestDist = Long.MAX_VALUE findNearestNeighbour(0, x.size, px, py, true) return bestNode } fun findNearestNeighbour(low: Int, high: Int, px: Int, py: Int, divX: Boolean) { if (high - low <= 0) return val mid = low + high ushr 1 val dx = (px - x[mid]).toLong() val dy = (py - y[mid]).toLong() val dist = dx * dx + dy * dy if (bestDist > dist) { bestDist = dist bestNode = mid } val delta = if (divX) dx else dy val delta2 = delta * delta if (delta <= 0) { findNearestNeighbour(low, mid, px, py, !divX) if (delta2 < bestDist) findNearestNeighbour(mid + 1, high, px, py, !divX) } else { findNearestNeighbour(mid + 1, high, px, py, !divX) if (delta2 < bestDist) findNearestNeighbour(low, mid, px, py, !divX) } } companion object { val rnd: Random = Random(1) // random test fun main(args: Array<String?>?) { for (step in 0..99999) { val qx: Int = rnd.nextInt(100) - 50 val qy: Int = rnd.nextInt(100) - 50 val n: Int = rnd.nextInt(100) + 1 val x = IntArray(n) val y = IntArray(n) var minDist = Long.MAX_VALUE for (i in 0 until n) { x[i] = rnd.nextInt(100) - 50 y[i] = rnd.nextInt(100) - 50 minDist = Math.min(minDist, (x[i] - qx).toLong() * (x[i] - qx) + (y[i] - qy).toLong() * (y[i] - qy)) } val kdTree = KdTreePointQuery(x, y) val index = kdTree.findNearestNeighbour(qx, qy) if (minDist != kdTree.bestDist || (x[index] - qx).toLong() * (x[index] - qx) + (y[index] - qy).toLong() * (y[index] - qy) != minDist ) throw RuntimeException() } } } init { build(0, x.size, true) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,589
codelibrary
The Unlicense
kotlin/2022/day07/Day07.kt
nathanjent
48,783,324
false
{"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966}
class Day07 { data class File(val name: String, val size: Int) class FileSystem { private var pwd: String = "/" private val fileSystemStructure = mutableMapOf( Pair(pwd, mutableMapOf<String, Int>()), ) fun cd(path: String) { if (path == "..") { pwd = pwd.substring(0, pwd.lastIndexOf("/")) } else if (path != pwd) { pwd += "${if (pwd != "/") "/" else ""}${path}" } } fun ls(): List<File> { return fileSystemStructure.getOrDefault(pwd, mutableMapOf()).map { File(it.key, it.value) } } fun add(path: String, size: Int = 0) { val dirContents = fileSystemStructure.getOrPut(pwd) { mutableMapOf() } dirContents[path] = size } fun du(fullPath: String): Int { val dirContents = fileSystemStructure[fullPath] return dirContents?.map { if (it.value == 0) { du(it.key) } else { it.value } }?.sum() ?: 0 } } fun part1(input: Iterable<String>): Int { val lines = input.toList() val fileSystem = FileSystem() var cursor = 0 main@ while (cursor < lines.size) { var line = lines[cursor++] if (line.isBlank()) continue val args = line.split(" ") if (args[0] == "$") { if (args[1] == "cd") { fileSystem.cd(args[2]) } if (args[1] == "ls") { ls@ while (cursor < lines.size) { line = lines[cursor++] if (line.isBlank()) continue@ls val words = line.split(" ") if (words[0] == "dir") { fileSystem.add(words[1]) } else if (words[0] == "$") { cursor-- continue@main } else { val size = words[0].toInt() fileSystem.add(words[1], size) } } } } } val f = fileSystem.ls() return 0 } fun part2(input: Iterable<String>): Int { return 0 } }
0
Rust
0
0
7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf
1,981
adventofcode
MIT License
roboquant/src/logging/MetricsEntry.kt
idanakav
465,612,930
true
{"Kotlin": 1144731, "Jupyter Notebook": 134242}
/* * Copyright 2021 Neural Layer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.roboquant.logging import org.roboquant.RunInfo import org.roboquant.common.Summary import org.roboquant.common.clean import org.roboquant.common.std /** * Single metric entry with the [RunInfo]. This is a read-only class. * * @property metric * @property value * @property info * @constructor Create empty Metrics entry */ data class MetricsEntry(val metric: String, val value: Double, val info: RunInfo) : Comparable<MetricsEntry> { /** * Get a key that uniquely defines the metric across a run and episode. */ internal val groupId get() = """${metric}/${info.run}/${info.episode}""" /** * Validate if another entry is from the same recorded phase, run and episode. * * @param other * @return */ fun sameEpisode(other: MetricsEntry): Boolean { val i = other.info return i.phase == info.phase && i.run == info.run && i.episode == info.episode } /** * Compare two metric entries based on their [value] */ override fun compareTo(other: MetricsEntry): Int { return value.compareTo(other.value) } } /** * Group a collection of metrics by thier unique name, run and episode */ fun Collection<MetricsEntry>.group() : Map<String, List<MetricsEntry>> = groupBy { it.groupId } fun Map<String, List<MetricsEntry>>.max() : Map<String, MetricsEntry> = mapValues { it.value.max() } fun Map<String, List<MetricsEntry>>.min() : Map<String, MetricsEntry> = mapValues { it.value.min() } /** * Get the [n] highest entries, default being 10 */ fun Collection<MetricsEntry>.high(n:Int = 10) = sortedBy { it }.takeLast(n) /** * Get the [n] lowest entries, default being 10 */ fun Collection<MetricsEntry>.low(n:Int = 10) = sortedBy { it }.take(n) fun Collection<MetricsEntry>.diff() : List<MetricsEntry> { val result = mutableListOf<MetricsEntry>() var first = true var prev = 0.0 for (entry in this) { if (first) { prev = entry.value first = false } else { val newValue = entry.value - prev val newEntry = entry.copy(value = newValue) result.add(newEntry) prev = entry.value } } return result } fun Collection<MetricsEntry>.perc() : List<MetricsEntry> { val result = mutableListOf<MetricsEntry>() var first = true var prev = 0.0 for (entry in this) { if (first) { prev = entry.value first = false } else { val newValue = 100.0 * (entry.value - prev) / prev val newEntry = entry.copy(value = newValue) result.add(newEntry) prev = entry.value } } return result } fun Collection<MetricsEntry>.summary(): Summary { val result = Summary("Metrics") val m = groupBy { it.metric } for ((name, values) in m) { val child = Summary(name) child.add("size", values.size) if (values.isNotEmpty()) { val arr = values.toDoubleArray().clean() child.add("min", arr.minOrNull()) child.add("max", arr.maxOrNull()) child.add("avg", arr.average()) child.add("std", arr.std()) child.add("runs", values.map { it.info.run }.distinct().size) val timeline = map { it.info.time }.sorted() child.add("first time", timeline.first()) child.add("last time", timeline.last()) } result.add(child) } return result }
0
Kotlin
0
0
9be1931fa0d4a76fc5013009c60e418322a77e60
4,120
roboquant
Apache License 2.0
src/Day04.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day4A(readFile("Day04"))) println(day4B(readFile("Day04"))) } fun day4A(input: String): Int = input.trim().split("\n").count { pair -> pair.split("-", ",").let { overlapAll(it[0].toInt(), it[1].toInt(), it[2].toInt(), it[3].toInt()) } } fun day4B(input: String): Int = input.trim().split("\n").count { pair -> pair.split("-", ",").let { overlapSome(it[0].toInt(), it[1].toInt(), it[2].toInt(), it[3].toInt()) } } fun overlapAll(a1: Int, a2: Int, b1: Int, b2: Int): Boolean = (a1 <= b1 && a2 >= b2) || (b1 <= a1 && b2 >= a2) fun overlapSome(a1: Int, a2: Int, b1: Int, b2: Int): Boolean = b1 in a1..a2 || b2 in a1..a2 || a1 in b1..b2 || a2 in b1..b2
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
691
AdventOfCode22
Apache License 2.0
src/day1/Day01.kt
dean95
571,923,107
false
{"Kotlin": 21240}
package day1 import readInput private fun main() { fun part1(input: List<String>): Int { val res = mutableListOf<Int>() var i = 0 while (i < input.size) { var totalCalories = 0 while (i < input.size && input[i].isNotBlank()) { totalCalories += input[i].toInt() i++ } res.add(totalCalories) i++ } return res.max() } fun part2(input: List<String>): Int { val res = mutableListOf<Int>() var i = 0 while (i < input.size) { var totalCalories = 0 while (i < input.size && input[i].isNotBlank()) { totalCalories += input[i].toInt() i++ } res.add(totalCalories) i++ } return res.sortedDescending().take(3).sum() } val testInput = readInput("day1/Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("day1/Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ddf1bdaf9bcbb45116c70d7328b606c2a75e5a5
1,108
advent-of-code-2022
Apache License 2.0
precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/RouteParser.kt
Tlaster
349,750,473
false
{"Kotlin": 185353}
package moe.tlaster.precompose.navigation import moe.tlaster.precompose.navigation.route.Route import kotlin.math.min internal class RouteParser { data class Segment( val nodeType: Int = 0, val rexPat: String = "", val tail: Char = 0.toChar(), val startIndex: Int = 0, val endIndex: Int = 0, ) private data class Node( var type: Int = 0, var prefix: String = "", var label: Char = 0.toChar(), var tail: Char = 0.toChar(), var rex: Regex? = null, var paramsKey: String? = null, var route: Route? = null, ) : Comparable<Node> { // subroutes on the leaf node // Routes subroutes; // child nodes should be stored in-order for iteration, // in groups of the node type. var children = linkedMapOf<Int, Array<Node>>() override operator fun compareTo(other: Node): Int { return label - other.label } fun insertRoute(pattern: String, route: Route): Node { var n = this var parent: Node var search = pattern while (true) { // Handle key exhaustion if (search.isEmpty()) { // Insert or update the node's leaf handler n.applyRoute(route) return n } // We're going to be searching for a wild node next, // in this case, we need to get the tail val label = search[0] // char segTail; // int segEndIdx; // int segTyp; val seg = if (label == '{' || label == '*') { // segTyp, _, segRexpat, segTail, _, segEndIdx = patNextSegment(search) patNextSegment(search) } else { Segment() } val prefix = if (seg.nodeType == ntRegexp) { seg.rexPat } else { "" } // Look for the edge to attach to parent = n n = n.getEdge(seg.nodeType, label, seg.tail, prefix) ?: run { val child = Node(label = label, tail = seg.tail, prefix = search) val hn = parent.addChild(child, search) hn.applyRoute(route) return hn } // Found an edge to newRuntimeRoute the pattern if (n.type > ntStatic) { // We found a param node, trim the param from the search path and continue. // This param/wild pattern segment would already be on the tree from a previous // call to addChild when creating a new node. search = search.substring(seg.endIndex) continue } // Static nodes fall below here. // Determine longest prefix of the search key on newRuntimeRoute. val commonPrefix = longestPrefix(search, n.prefix) if (commonPrefix == n.prefix.length) { // the common prefix is as long as the current node's prefix we're attempting to insert. // keep the search going. search = search.substring(commonPrefix) continue } // Split the node val child = Node(type = ntStatic, prefix = search.substring(0, commonPrefix)) parent.replaceChild(search[0], seg.tail, child) // Restore the existing node n.label = n.prefix[commonPrefix] n.prefix = n.prefix.substring(commonPrefix) child.addChild(n, n.prefix) // If the new key is a subset, set the route on this node and finish. search = search.substring(commonPrefix) if (search.isEmpty()) { child.applyRoute(route) return child } // Create a new edge for the node val subchild = Node(type = ntStatic, label = search[0], prefix = search) val hn = child.addChild(subchild, search) hn.applyRoute(route) return hn } } // addChild appends the new `child` node to the tree using the `pattern` as the trie key. // For a URL router like chi's, we split the static, param, regexp and wildcard segments // into different nodes. In addition, addChild will recursively call itself until every // pattern segment is added to the url pattern tree as individual nodes, depending on type. fun addChild(child: Node, search: String): Node { var searchStr = search val n = this // String search = prefix.toString(); // handler leaf node added to the tree is the child. // this may be overridden later down the flow var hn = child // Parse next segment // segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search) val seg = patNextSegment(searchStr) val segTyp = seg.nodeType var segStartIdx = seg.startIndex val segEndIdx = seg.endIndex when (segTyp) { ntStatic -> { } else -> { // Search prefix contains a param, regexp or wildcard if (segTyp == ntRegexp) { child.prefix = seg.rexPat child.rex = seg.rexPat.toRegex() } if (segStartIdx == 0) { // Route starts with a param child.type = segTyp segStartIdx = if (segTyp == ntCatchAll) { -1 } else { segEndIdx } if (segStartIdx < 0) { segStartIdx = searchStr.length } child.tail = seg.tail // for params, we set the tail child.paramsKey = findParamKey(searchStr) // set paramsKey if it has keys if (segStartIdx != searchStr.length) { // add static edge for the remaining part, split the end. // its not possible to have adjacent param nodes, so its certainly // going to be a static node next. searchStr = searchStr.substring(segStartIdx) // advance search position val nn = Node(type = ntStatic, label = searchStr[0], prefix = searchStr) hn = child.addChild(nn, searchStr) } } else if (segStartIdx > 0) { // Route has some param // starts with a static segment child.type = ntStatic child.prefix = searchStr.substring(0, segStartIdx) child.rex = null // add the param edge node searchStr = searchStr.substring(segStartIdx) val nn = Node(type = segTyp, label = searchStr[0], tail = seg.tail, paramsKey = findParamKey(searchStr)) hn = child.addChild(nn, searchStr) } } } n.children[child.type] = append(n.children[child.type], child).also { tailSort(it) } return hn } private fun findParamKey(pattern: String): String? { val startChar = "{" val endChar = "}" val regexStart = ":" if (!pattern.startsWith("{") && !pattern.endsWith("}")) return null val startIndex = pattern.indexOf(startChar) val endIndex = pattern.indexOf(endChar) val regexIndex = pattern.indexOf(regexStart).let { if (it == -1) pattern.length else it } return pattern.substring(min(startIndex + 1, pattern.length - 1), min(endIndex, regexIndex)) } fun replaceChild(label: Char, tail: Char, child: Node) { val n = this val children = n.children[child.type] ?: return var i = 0 while (i < children.size) { if (children[i].label == label && children[i].tail == tail) { children[i] = child children[i].label = label children[i].tail = tail return } i++ } throw IllegalArgumentException("chi: replacing missing child") } fun getEdge(ntyp: Int, label: Char, tail: Char, prefix: String): Node? { val n = this val nds = n.children[ntyp] ?: return null var i = 0 while (i < nds.size) { if (nds[i].label == label && nds[i].tail == tail) { if (ntyp == ntRegexp && nds[i].prefix != prefix) { i++ continue } return nds[i] } i++ } return null } fun applyRoute(route: Route?) { val n = this n.route = route } // Recursive edge traversal by checking all nodeTyp groups along the way. // It's like searching through a multi-dimensional radix trie. fun findRoute(rctx: RouteMatch, path: String): Route? { for (ntyp in 0 until NODE_SIZE) { val nds = children[ntyp] if (nds == null) { continue } var xn: Node? = null var xsearch = path val label = if (path.isNotEmpty()) path[0] else ZERO_CHAR when (ntyp) { ntStatic -> { xn = findEdge(nds, label) if (xn == null || !xsearch.startsWith(xn.prefix)) { continue } xsearch = xsearch.substring(xn.prefix.length) } ntParam, ntRegexp -> { // short-circuit and return no matching route for empty param values if (xsearch.isEmpty()) { continue } // serially loop through each node grouped by the tail delimiter var idx = 0 while (idx < nds.size) { xn = nds[idx] if (xn.type != ntStatic) { xn.paramsKey?.let { rctx.keys.add(it) } } // label for param nodes is the delimiter byte var p = xsearch.indexOf(xn.tail) if (p < 0) { p = if (xn.tail == '/') { xsearch.length } else { idx++ continue } } val rex = xn.rex if (ntyp == ntRegexp && rex != null) { if (!rex.matches(xsearch.substring(0, p))) { idx++ continue } } else if (xsearch.substring(0, p).indexOf('/') != -1) { // avoid a newRuntimeRoute across path segments idx++ continue } // rctx.routeParams.Values = append(rctx.routeParams.Values, xsearch[:p]) val prevlen: Int = rctx.vars.size rctx.value(xsearch.substring(0, p)) xsearch = xsearch.substring(p) if (xsearch.isEmpty()) { if (xn.isLeaf) { val h = xn.route if (h != null) { rctx.key() return h } } } // recursively find the next node on this branch val fin = xn.findRoute(rctx, xsearch) if (fin != null) { return fin } // not found on this branch, reset vars rctx.truncate(prevlen) xsearch = path idx++ } } else -> { // catch-all nodes // rctx.routeParams.Values = append(rctx.routeParams.Values, search) if (xsearch.isNotEmpty()) { rctx.value(xsearch) } xn = nds[0] xsearch = "" } } if (xn == null) { continue } // did we returnType it yet? if (xsearch.isEmpty()) { if (xn.isLeaf) { val h = xn.route if (h != null) { // rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...) rctx.key() return h } } } // recursively returnType the next node.. val fin = xn.findRoute(rctx, xsearch) if (fin != null) { return fin } // Did not returnType final handler, let's remove the param here if it was set if (xn.type > ntStatic) { // if len(rctx.routeParams.Values) > 0 { // rctx.routeParams.Values = rctx.routeParams.Values[:len(rctx.routeParams.Values) - 1] // } rctx.pop() } } return null } fun findEdge(ns: Array<Node>, label: Char): Node? { val num = ns.size var idx = 0 var i = 0 var j = num - 1 while (i <= j) { idx = i + (j - i) / 2 when { label > ns[idx].label -> { i = idx + 1 } label < ns[idx].label -> { j = idx - 1 } else -> { i = num // breaks cond } } } return if (ns[idx].label != label) { null } else { ns[idx] } } val isLeaf: Boolean get() = route != null // longestPrefix finds the filesize of the shared prefix of two strings fun longestPrefix(k1: String, k2: String): Int { val len: Int = min(k1.length, k2.length) for (i in 0 until len) { if (k1[i] != k2[i]) { return i } } return len } fun tailSort(ns: Array<Node>) { if (ns.size > 1) { ns.sort() for (i in ns.indices.reversed()) { if (ns[i].type > ntStatic && ns[i].tail == '/') { val tmp = ns[i] ns[i] = ns[ns.size - 1] ns[ns.size - 1] = tmp return } } } } private fun append(src: Array<Node>?, child: Node): Array<Node> { if (src == null) { return arrayOf(child) } val result = src.copyOf() return result + child } // patNextSegment returns the next segment details from a pattern: // node type, param key, regexp string, param tail byte, param starting index, param ending index fun patNextSegment(pattern: String): Segment { val ps = pattern.indexOf('{') val ws = pattern.indexOf('*') if (ps < 0 && ws < 0) { return Segment( ntStatic, "", ZERO_CHAR, 0, pattern.length, ) // we return the entire thing } // Sanity check require(!(ps >= 0 && ws >= 0 && ws < ps)) { "chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'" } var tail = '/' // Default endpoint tail to / byte if (ps >= 0) { // Param/Regexp pattern is next var nt = ntParam // Read to closing } taking into account opens and closes in curl count (cc) var cc = 0 var pe = ps val range = pattern.substring(ps) for (i in range.indices) { val c = range[i] if (c == '{') { cc++ } else if (c == '}') { cc-- if (cc == 0) { pe = ps + i break } } } require(pe != ps) { "Router: route param closing delimiter '}' is missing" } val key = pattern.substring(ps + 1, pe) pe++ // set end to next position if (pe < pattern.length) { tail = pattern[pe] } var rexpat = "" val idx = key.indexOf(':') if (idx >= 0) { nt = ntRegexp rexpat = key.substring(idx + 1) // key = key.substring(0, idx); } if (rexpat.isNotEmpty()) { if (rexpat[0] != '^') { rexpat = "^$rexpat" } if (rexpat[rexpat.length - 1] != '$') { rexpat = "$rexpat$" } } return Segment(nt, rexpat, tail, ps, pe) } // Wildcard pattern as finale // EDIT: should we panic if there is stuff after the * ??? // We allow naming a wildcard: *path // String key = ws == pattern.length() - 1 ? "*" : pattern.substring(ws + 1).toString(); return Segment(ntCatchAll, "", ZERO_CHAR, ws, pattern.length) } } private val root = Node() private val staticPaths = linkedMapOf<String, Route>() fun insert(pattern: String, route: Route) { var patternStr = pattern val baseCatchAll = baseCatchAll(patternStr) if (baseCatchAll.length > 1) { // Add route pattern: /static/?* => /static insert(baseCatchAll, route) val tail = patternStr.substring(baseCatchAll.length + 2) patternStr = "$baseCatchAll/$tail" } if (patternStr == BASE_CATCH_ALL) { patternStr = "/*" } if (pathKeys(patternStr).isEmpty()) { staticPaths[patternStr] = route } root.insertRoute(patternStr, route) } private fun baseCatchAll(pattern: String): String { val i = pattern.indexOf(BASE_CATCH_ALL) return if (i > 0) { pattern.substring(0, i) } else { "" } } fun insert(route: Route) { insert(route.route, route) } fun find(path: String): RouteMatchResult? { val staticRoute = staticPaths[path] return if (staticRoute == null) { findInternal(path) } else { return RouteMatchResult(staticRoute) } } private fun findInternal(path: String): RouteMatchResult? { // use radix tree val result = RouteMatch() val route = root.findRoute(result, path) ?: return null return RouteMatchResult(route, result.pathMap) } companion object { fun pathKeys( pattern: String, onItem: (key: String, value: String?) -> Unit = { _, _ -> }, ): List<String> { val result = arrayListOf<String>() var start = -1 var end = Int.MAX_VALUE val len = pattern.length var curly = 0 var i = 0 while (i < len) { val ch = pattern[i] if (ch == '{') { if (curly == 0) { start = i + 1 end = Int.MAX_VALUE } curly += 1 } else if (ch == ':') { end = i } else if (ch == '}') { curly -= 1 if (curly == 0) { val id = pattern.substring(start, min(i, end)) if (end == Int.MAX_VALUE) { null } else { pattern.substring(end + 1, i) }.let { onItem.invoke(id, it) } result.add(id) start = -1 end = Int.MAX_VALUE } } else if (ch == '*') { val id: String = if (i == len - 1) { "*" } else { pattern.substring(i + 1) } onItem.invoke(id, "\\.*") result.add(id) i = len } i++ } return result } fun expandOptionalVariables(pattern: String): List<String> { if (pattern.isEmpty() || pattern == "/") { return listOf("/") } val len = pattern.length var key = 0 val paths = linkedMapOf<Int, StringBuilder>() val pathAppender = { index: Int, segment: StringBuilder -> for (i in index until index - 1) { paths[i]?.append(segment) } paths.getOrPut(index) { val value = StringBuilder() if (index > 0) { val previous = paths[index - 1] if (previous.toString() != "/") { value.append(previous) } } value }.append(segment) } val segment = StringBuilder() var isLastOptional = false var i = 0 while (i < len) { val ch = pattern[i] if (ch == '/') { if (segment.isNotEmpty()) { pathAppender.invoke(key, segment) segment.setLength(0) } segment.append(ch) i += 1 } else if (ch == '{') { segment.append(ch) var curly = 1 var j = i + 1 while (j < len) { val next = pattern[j++] segment.append(next) if (next == '{') { curly += 1 } else if (next == '}') { curly -= 1 if (curly == 0) { break } } } if (j < len && pattern[j] == '?') { j += 1 isLastOptional = true if (paths.isEmpty()) { paths[0] = StringBuilder("/") } pathAppender.invoke(++key, segment) } else { isLastOptional = false pathAppender.invoke(key, segment) } segment.setLength(0) i = j } else { segment.append(ch) i += 1 } } if (paths.isEmpty()) { return listOf(pattern) } if (segment.isNotEmpty()) { pathAppender.invoke(key, segment) if (isLastOptional) { paths[++key] = segment } } return paths.values.map { it.toString() } } private const val ntStatic = 0 // /home private const val ntRegexp = 1 // /{id:[0-9]+} private const val ntParam = 2 // /{user} private const val ntCatchAll = 3 // /api/v1/* private const val NODE_SIZE = ntCatchAll + 1 private const val ZERO_CHAR = 0.toChar() private const val BASE_CATCH_ALL = "/?*" } }
24
Kotlin
39
657
e914ffbf2e92eb17aefc43aba82c7b575228eb1c
26,403
PreCompose
MIT License
aoc-2023/src/main/kotlin/aoc/aoc1.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocRunner import aoc.util.getDayInput val input = getDayInput(1, 2023) val digits = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val sum1 = input .sumOf { it.first { it.isDigit() }.digitToInt() * 10 + it.last { it.isDigit() }.digitToInt() } val sum2 = input.sumOf { it.firstAndLastDigit() } fun String.digitAt(index: Int) = digits.indexOfFirst { substring(index).startsWith(it) } + 1 fun String.firstAndLastDigit(): Int { val firstNum = indexOfFirst { it.isDigit() } val firstStr = digits.map { indexOf(it) }.filter { it != -1 }.minOrNull() val lastNum = indexOfLast { it.isDigit() } val lastStr = digits.map { lastIndexOf(it) }.filter { it != -1 }.maxOrNull() val firstDig = when { firstNum == -1 -> digitAt(firstStr!!) firstStr == null || firstStr > firstNum -> get(firstNum).digitToInt() else -> digitAt(firstStr) } val lastDig = when { lastNum == -1 -> digitAt(lastStr!!) lastStr == null || lastStr < lastNum -> get(lastNum).digitToInt() else -> digitAt(lastStr) } return firstDig * 10 + lastDig } AocRunner(1, part1 = sum1, part2 = sum2 ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
1,196
advent-of-code
Apache License 2.0
src/main/kotlin/g1101_1200/s1156_swap_for_longest_repeated_character_substring/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1156_swap_for_longest_repeated_character_substring // #Medium #String #Sliding_Window #2023_10_02_Time_198_ms_(100.00%)_Space_37.4_MB_(100.00%) class Solution { private class Pair(var character: Char, var count: Int) fun maxRepOpt1(text: String): Int { val pairs: MutableList<Pair> = ArrayList() val map: MutableMap<Char, Int> = HashMap() // collect counts for each char-block var i = 0 while (i < text.length) { val c = text[i] var count = 0 while (i < text.length && text[i] == c) { count++ i++ } pairs.add(Pair(c, count)) map[c] = map.getOrDefault(c, 0) + count } var max = 0 // case 1, swap 1 item to the boundary of a consecutive cha-block to achieve possible max // length // we need total count to make sure whether a swap is possible! for (p in pairs) { val totalCount = map.getValue(p.character) max = if (totalCount > p.count) { Math.max(max, p.count + 1) } else { Math.max(max, p.count) } } // case 2, find xxxxYxxxxx pattern // we need total count to make sure whether a swap is possible! for (j in 1 until pairs.size - 1) { if (pairs[j - 1].character == pairs[j + 1].character && pairs[j].count == 1 ) { val totalCount = map.getValue(pairs[j - 1].character) val groupSum = pairs[j - 1].count + pairs[j + 1].count max = if (totalCount > groupSum) { Math.max(max, groupSum + 1) } else { Math.max(max, groupSum) } } } return max } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,870
LeetCode-in-Kotlin
MIT License
src/main/kotlin/leetcode/Problem1438.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import java.util.* import kotlin.math.max /** * https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/ */ class Problem1438 { fun longestSubarray(nums: IntArray, limit: Int): Int { var answer = 1 val minDeque = LinkedList<Int>() val maxDeque = LinkedList<Int>() var left = 0 for (right in nums.indices) { while (minDeque.isNotEmpty() && nums[right] < minDeque.peekLast()) { minDeque.pollLast() } minDeque.addLast(nums[right]) while (maxDeque.isNotEmpty() && nums[right] > maxDeque.peekLast()) { maxDeque.pollLast() } maxDeque.addLast(nums[right]) while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) { if (minDeque.peekFirst() == nums[left]) { minDeque.pollFirst() } if (maxDeque.peekFirst() == nums[left]) { maxDeque.pollFirst() } left++ } answer = max(answer, right - left + 1) } return answer } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,203
leetcode
MIT License
src/main/kotlin/problems/Day17.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems import kotlin.math.min class Day17(override val input: String) : Problem { override val number: Int = 17 private val inputMatch = """target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""" .toRegex() .find(input) ?.groupValues ?.drop(1) ?.map { it.toInt() }!! private val xRange = inputMatch[0]..inputMatch[1] private val yRange = inputMatch[2]..inputMatch[3] override fun runPartOne(): String { val positions = mutableSetOf<Pair<Int,Int>>() for (vx in 0..xRange.last) { for (vy in yRange.first..500) { val position = positions(Pair(vx, vy)) if (position != null) { positions.addAll(position) } } } return positions .maxOf { it.second } .toString() } override fun runPartTwo(): String { var count = 0 for (vx in 0..xRange.last) { for (vy in yRange.first..500) { val position = positions(Pair(vx, vy)) if (position != null) { count++ } } } return count .toString() } private fun positions(velocity: Pair<Int, Int>) : Set<Pair<Int, Int>>? { val positions = mutableSetOf<Pair<Int, Int>>() var (x, y) = Pair(0,0) var (vx,vy) = velocity while(true) { x += vx y += vy positions.add(Pair(x,y)) vx = when { vx < 0 -> vx + 1 vx > 0 -> vx - 1 else -> vx } vy -= 1 val withinBounds = x in xRange && y in yRange val outOfBounds = x > xRange.last || y < min(yRange.first, yRange.last) if (withinBounds) { return positions } if (outOfBounds) { return null } } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
2,044
AdventOfCode2021
MIT License
Essays/Testability/REPL/src/main/kotlin/palbp/laboratory/essays/testability/repl/Tokenizer.kt
palbp
463,200,783
false
{"Kotlin": 722657, "C": 16710, "Assembly": 891, "Dockerfile": 610, "Swift": 594, "Makefile": 383}
package palbp.laboratory.essays.testability.repl data class Token(val container: String, val range: IntRange) { constructor(container: String, startsAt: Int) : this(container, startsAt until container.length) init { require(range.first >= 0 && range.last <= container.length) require(container.isNotBlank()) } val value = container.substring(range.first, range.last) } fun tokenize(input: String): List<Token> = coRecursiveTokenize(input) fun iterativeTokenize(input: String): List<Token> { var tokenStart = -1 val tokens = mutableListOf<Token>() input.forEachIndexed { index, c -> if (c.isWhitespace()) { if (tokenStart != -1) { tokens.add(Token(input, tokenStart..index)) tokenStart = -1 } } else { if (tokenStart == -1) tokenStart = index } } if (tokenStart != -1) { tokens.add(Token(input, tokenStart..input.length)) } return tokens } fun recursiveTokenize(input: String, startIndex: Int = 0): List<Token> = nextToken(input, inputIndex = startIndex).let { if (it == null) emptyList() else listOf(it) + recursiveTokenize(input, startIndex = it.range.last) } tailrec fun coRecursiveTokenize(input: String, startIndex: Int = 0, acc: List<Token> = emptyList()): List<Token> { val nextToken = nextToken(input, inputIndex = startIndex) return if (nextToken == null) acc else coRecursiveTokenize(input, startIndex = nextToken.range.last, acc = acc + nextToken) } private fun nextToken(input: String, inputIndex: Int): Token? { tailrec fun skipToTokenStart(currIndex: Int): Int = if (currIndex >= input.length || !input[currIndex].isWhitespace()) currIndex else skipToTokenStart(currIndex + 1) tailrec fun buildToken(startIndex: Int, currIndex: Int): Token = if (currIndex == input.length || input[currIndex].isWhitespace()) Token(input, startIndex..currIndex) else buildToken(startIndex, currIndex + 1) val nextTokenStart = skipToTokenStart(inputIndex) return if (nextTokenStart >= input.length) null else buildToken(nextTokenStart, nextTokenStart) }
1
Kotlin
0
4
66fb17fcd9d7b1690492def0bf671cfb408eb6db
2,223
laboratory
MIT License
src/Day17.kt
frungl
573,598,286
false
{"Kotlin": 86423}
fun main() { val figures = listOf( listOf(-1 to 0, 0 to 0, 1 to 0, 2 to 0), listOf(0 to 0, -1 to 1, 0 to 1, 1 to 1, 0 to 2), listOf(-1 to 0, 0 to 0, 1 to 0, 1 to 1, 1 to 2), listOf(-1 to 0, -1 to 1, -1 to 2, -1 to 3), listOf(-1 to 0, 0 to 0, -1 to 1, 0 to 1) ) operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> { return first + other.first to second + other.second } fun List<Pair<Int, Int>>.applyFigure(pos: Pair<Int, Int>): List<Pair<Int, Int>> { val tmp = map { it + pos } val mn = tmp.minBy { it.first }.first val mx = tmp.maxBy { it.first }.first return when(mn < 0 || mx > 6) { true -> this else -> tmp } } fun part1(input: List<String>): Int { val go = input[0] val set = mutableSetOf<Pair<Int, Int>>() (0..6).forEach { set.add(it to - 1) } val down = 0 to -1 val left = -1 to 0 val right = 1 to 0 var nowCord = 3 to 3 var nowPos = 0 var nowInd = 0 repeat(2022) { var nowFigure = figures[nowInd].applyFigure(nowCord) while (true) { val tmp = when (go[nowPos]) { '>' -> nowFigure.applyFigure(right) '<' -> nowFigure.applyFigure(left) else -> throw Exception("Error") } if ((tmp intersect set).isEmpty()) nowFigure = tmp nowPos = (nowPos + 1) % go.length if((nowFigure.applyFigure(down) intersect set).isNotEmpty()) break nowFigure = nowFigure.applyFigure(down) } set.addAll(nowFigure) nowCord = 3 to (set.maxBy { it.second }.second + 4) nowInd = (nowInd + 1) % figures.size } return set.maxBy { it.second }.second + 1 } fun part2(input: List<String>): Long { val need: Long = 1_000_000_000_000L val go = input[0] val set = mutableSetOf<Pair<Int, Int>>() (0..6).forEach { set.add(it to - 1) } val down = 0 to -1 val left = -1 to 0 val right = 1 to 0 var nowCord = 3 to 3 var nowPos = 0 var nowInd = 0 val fiveSet = mutableMapOf<Int, Pair<Int, Set<Pair<Int, Int>>>>() val heights = mutableListOf<Int>() var lastHeight = 0 var cnt = 0 while(true) { val nowSet = mutableSetOf<Pair<Int, Int>>() repeat(5) { var nowFigure = figures[nowInd].applyFigure(nowCord) while (true) { val tmp = when (go[nowPos]) { '>' -> nowFigure.applyFigure(right) '<' -> nowFigure.applyFigure(left) else -> throw Exception("Error") } if ((tmp intersect set).isEmpty()) nowFigure = tmp nowPos = (nowPos + 1) % go.length if((nowFigure.applyFigure(down) intersect set).isNotEmpty()) break nowFigure = nowFigure.applyFigure(down) } set.addAll(nowFigure) nowSet.addAll(nowFigure) val mxH = set.maxBy { it.second }.second heights.add(mxH + 1) nowCord = 3 to (mxH + 4) nowInd = (nowInd + 1) % figures.size } if (fiveSet[nowPos] == null) { fiveSet[nowPos] = cnt to nowSet.toSet() } else { val (oldCnt, oldFiveSet) = fiveSet[nowPos]!! val mnNow = nowSet.minBy { it.second }.second val mnOld = oldFiveSet.minBy { it.second }.second val newSet = nowSet.map { it.first to it.second - mnNow + mnOld }.toSet() if (oldFiveSet == newSet) { val needCnt = (need - oldCnt) / (cnt - oldCnt) val needPos = (need - oldCnt) % (cnt - oldCnt) return needCnt * (lastHeight - mnOld) + heights[oldCnt + needPos.toInt() - 1] } } lastHeight = heights.last() cnt += 5 } return -1L } val testInput = readInput("Day17_test") check(part1(testInput) == 3068) check(part2(testInput) == 1_514_285_714_288L) val input = readInput("Day17") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
4,582
aoc2022
Apache License 2.0
src/Day11.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private data class Monkey ( val id: Int, val items: MutableList<Long> = mutableListOf(), val operation: (Long) -> Long, val testDivisor: Int, val testTrueMonkey: Int, val testFalseMonkey: Int, var inspectedItems:Int = 0 ) private fun monkeys(input: List<String>): List<Monkey> { var currentLine = 0 val monkeys = mutableListOf<Monkey>() while (currentLine < input.size) { var line = input[currentLine] assert(line.startsWith("Monkey ")) val id = line.substring(7, line.length - 1).toInt() assert(id == monkeys.size) line = input[++currentLine] assert(line.startsWith(" Starting items: ")) val items = line.substring(18).split(", ").map { it.toLong() }.toMutableList() line = input[++currentLine] assert(line.startsWith(" Operation: new = old ")) val operand = line[23] val num = line.substring(25) val operation = if (operand == '+') { if (num == "old") { { old: Long -> old + old } } else { { old: Long -> old + num.toLong() } } } else if (operand == '*') { if (num == "old") { { old: Long -> old * old } } else { { old: Long -> old * num.toLong() } } } else { throw IllegalArgumentException("Unknown operand $operand") } line = input[++currentLine] assert(line.startsWith(" Test: divisible by ")) val testDivisor = line.substring(21).toInt() line = input[++currentLine] assert(line.startsWith(" If true: throw to monkey ")) val testTrueMonkey = line.substring(29).toInt() assert(testTrueMonkey != id) line = input[++currentLine] assert(line.startsWith(" If false: throw to monkey ")) val testFalseMonkey = line.substring(30).toInt() assert(testFalseMonkey != id) currentLine += 2 monkeys.add(Monkey(id, items, operation, testDivisor, testTrueMonkey, testFalseMonkey)) } return monkeys } private fun simulateRounds(monkeys: List<Monkey>, numOfRounds: Int, worryLevelDivisor: Int) { val longDivisorLCM = monkeys .map { it.testDivisor.toLong() } .reduce { d1, d2 -> d1 * d2 } for (round in 1..numOfRounds) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val newItem = (monkey.operation(item) / worryLevelDivisor) % longDivisorLCM val nextMonkey = if (newItem % monkey.testDivisor == 0L) { monkey.testTrueMonkey } else { monkey.testFalseMonkey } monkey.inspectedItems++ monkeys[nextMonkey].items.add(newItem) } } } } private fun monkeyBusiness(monkeys: List<Monkey>): Long { var mostActive = Int.MIN_VALUE var secondActive = Int.MIN_VALUE for (monkey in monkeys) { if (monkey.inspectedItems > mostActive) { secondActive = mostActive mostActive = monkey.inspectedItems } else if (monkey.inspectedItems > secondActive) { secondActive = monkey.inspectedItems } } return mostActive.toLong() * secondActive } private fun part1(input: List<String>): Long { val monkeys = monkeys(input) simulateRounds(monkeys, 20, 3) return monkeyBusiness(monkeys) } private fun part2(input: List<String>): Long { val monkeys = monkeys(input) simulateRounds(monkeys, 10000, 1) return monkeyBusiness(monkeys) } fun main() { val input = readInput("Day11") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
3,875
advent-of-code-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day08.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.* fun main() = Day08.run() object Day08 : Day(2016, 8) { private const val width = 50 private const val heigh = 6 override fun part1(): Any { val grid = Grid('.') List(width){it}.flatMap{ x -> List(heigh){it}.map { y-> x to y } }.forEach{ grid[it.first, it.second] = '.' } input.lines().forEach{ when(it.split(" ")[0]) { "rect" -> rect(grid, it) "rotate" -> rotate(grid, it) } } return grid.points().map { it.second }.count { it == '#'} } private fun rotate(grid: Grid<Char>, it: String) { val splitCommand = it.split(" ") val isRow = splitCommand[1] == "row" val rowCol = ints(it)[0] val by = ints(it)[1] if (isRow) { grid.shiftRow(rowCol, by) } else { grid.shiftCol(rowCol, by) } } private fun rect(grid: Grid<Char>, it: String) { val rectW = ints(it)[0] val rectH = ints(it)[1] for (x in 0 until rectW) { for (y in 0 until rectH) { grid[x, y] = '#' } } } override fun part2(): Any { val grid = Grid('.') List(width){it}.flatMap{ x -> List(heigh){it}.map { y-> x to y } }.forEach{ grid[it.first, it.second] = '.' } input.lines().forEach{ when(it.split(" ")[0]) { "rect" -> rect(grid, it) "rotate" -> rotate(grid, it) } } grid.scale(5, 6) // println(grid) return "RURUCEOEIL" } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,651
adventofkotlin
MIT License
src/main/kotlin/days/Solution04.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf object Solution04 : Solution<List<Int>>(AOC_YEAR, 4) { override fun getInput(handler: InputHandler): List<Int> { return handler.getInput("\n") .map { it.substringAfter(": ").split(" | ") } .map { halves -> halves.map { it.split(' ') .mapNotNull(String::toIntOrNull) .toSet() } } .map { it.reduce(Set<Int>::intersect) } .map(Set<Int>::size) } override fun solve(input: List<Int>): PairOf<Int> { val cardCounts = input.indices .associateWith { 1 } .toMutableMap() val ans1 = input.withIndex() .filter { it.value > 0 } .sumOf { (i, overlaps) -> val cardCount = cardCounts.getValue(i) (i + 1..i + overlaps) .filter(cardCounts.keys::contains) .forEach { cardCounts.merge(it, cardCount, Int::plus) } 1.shl(overlaps - 1) } val ans2 = cardCounts.values.sum() return ans1 to ans2 } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
1,249
Advent-of-Code-2023
MIT License
src/iii_conventions/MyDate.kt
pleshkov631
350,749,403
true
{"Kotlin": 71902, "Java": 4952}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { return when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } } } operator fun MyDate.rangeTo(other: MyDate): DateRange { return DateRange(this, other) } enum class TimeInterval { DAY, WEEK, YEAR } operator fun TimeInterval.times(n:Int): MultiTimeInterval{ return MultiTimeInterval(this, n) } class MultiTimeInterval(val timeInterval: TimeInterval, val num: Int = 1) class DateRange(val start: MyDate, val endInclusive: MyDate): Iterable<MyDate> { operator fun contains(d: MyDate): Boolean { return start <= d && endInclusive >= d } override operator fun iterator(): Iterator<MyDate> = DateIterator(this) } class DateIterator(val dateRange: DateRange): Iterator<MyDate>{ var current: MyDate = dateRange.start override fun hasNext(): Boolean { return current <= dateRange.endInclusive } override fun next(): MyDate { var temp = current current = current.nextDay() return temp } } operator fun MyDate.plus(timeInterval: TimeInterval):MyDate { return this.addTimeIntervals(timeInterval, 1) } operator fun MyDate.plus(multiTimeInterval: MultiTimeInterval):MyDate { return this.addTimeIntervals(multiTimeInterval.timeInterval, multiTimeInterval.num) }
0
Kotlin
0
0
7cad67d77ed9ce2c70503c297de43574c3854086
1,564
kotlin-koans
MIT License
src/main/kotlin/aoc2023/Day10.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import Point import readInput import to2dCharArray private data class PipeNetwork(val map: Array<CharArray>, val start: Point) { companion object { fun fromStrings(input: List<String>): PipeNetwork { val map = input.to2dCharArray() val start = map.withIndex().firstNotNullOf { (x, column) -> column.withIndex().find { (y, char) -> char == 'S' }?.index?.let { y -> Point(x, y) } } return PipeNetwork(map, start) } fun fromStringsExtended(input: List<String>): PipeNetwork { val map = Array(input.first().length * 2) { CharArray(input.size * 2) { '.' } } for (y in input.indices) { for ((x, char) in input[y].withIndex()) { map[x * 2][y * 2] = char map[x * 2 + 1][y * 2] = when (char) { '|' -> '.' '-' -> '-' 'L' -> '-' 'J' -> '.' '7' -> '.' 'F' -> '-' '.' -> '.' 'S' -> '+' else -> throw IllegalArgumentException("invalid input at $x,$y: $char") } map[x * 2][y * 2 + 1] = when (char) { '|' -> '|' '-' -> '.' 'L' -> '.' 'J' -> '.' '7' -> '|' 'F' -> '|' '.' -> '.' 'S' -> '+' else -> throw IllegalArgumentException("invalid input at $x,$y: $char") } } } val start = map.withIndex().firstNotNullOf { (x, column) -> column.withIndex().find { (y, char) -> char == 'S' }?.index?.let { y -> Point(x, y) } } return PipeNetwork(map, start) } } val loop by lazy { findMainLoop() } val validGrid = Point(0, 0) to Point(map.size - 1, map.first().size - 1) private fun findMainLoop(): Set<Point> { val neighbours = start.getNeighbours(validGrid = validGrid) return neighbours.firstNotNullOf { it.getMainLoop(listOf(start)) }.toSet() } private tailrec fun Point.getMainLoop(history: List<Point>): List<Point>? { val thisPipe = map[x][y] if (thisPipe == '.') return null val newHistory = buildList { addAll(history) add(this@getMainLoop) } if (thisPipe == 'S') return newHistory val nextPipe = getNext().filter { map[it.x][it.y] != '.' }.firstOrNull { it != history.last() } return nextPipe?.getMainLoop(newHistory) } private fun Point.getNext(): List<Point> { val thisPipe = map[x][y] val north = if (y > 0) Point(x, y - 1) else null val south = if (y < map.first().size - 1) Point(x, y + 1) else null val east = if (x < map.size - 1) Point(x + 1, y) else null val west = if (x > 0) Point(x - 1, y) else null val next = when (thisPipe) { /* | is a vertical pipe connecting north and south. - is a horizontal pipe connecting east and west. L is a 90-degree bend connecting north and east. J is a 90-degree bend connecting north and west. 7 is a 90-degree bend connecting south and west. F is a 90-degree bend connecting south and east. */ '|' -> listOf(north, south) '-' -> listOf(east, west) 'L' -> listOf(north, east) 'J' -> listOf(north, west) '7' -> listOf(south, west) 'F' -> listOf(south, east) '+' -> listOf(north, south, east, west) // additional "+" for the part2 quiz else -> throw IllegalArgumentException("invalid input at $this: $thisPipe") } return next.filterNotNull() } } private fun growArea(pipeNetwork: PipeNetwork, area: MutableSet<Point>) { var sizeBefore = 0 while (area.size > sizeBefore) { sizeBefore = area.size val additions = mutableSetOf<Point>() area.forEach { additions.addAll(it.getNeighbours(validGrid = pipeNetwork.validGrid).filter { n -> n !in pipeNetwork.loop }) } area.addAll(additions) } } object Day10 { fun part1(input: List<String>) = PipeNetwork.fromStrings(input).loop.size / 2 fun part2(input: List<String>): Int { val pipeNetwork = PipeNetwork.fromStringsExtended(input) val outsideTiles = mutableSetOf<Point>() val enclosedTiles = mutableSetOf<Point>() // add all points on the edge, which are not part of the loop, to the "outside" set for (x in pipeNetwork.map.indices) { var p = Point(x, 0) if (p !in pipeNetwork.loop) { outsideTiles.add(p) } p = Point(x, pipeNetwork.map.first().size - 1) if (p !in pipeNetwork.loop) { outsideTiles.add(p) } } for (y in pipeNetwork.map.first().indices) { var p = Point(0, y) if (p !in pipeNetwork.loop) { outsideTiles.add(p) } p = Point(pipeNetwork.map.size - 1, y) if (p !in pipeNetwork.loop) { outsideTiles.add(p) } } // blow up the outside area until all reachable tiles are part of it (BFS) growArea(pipeNetwork, outsideTiles) // print extended map and add all "unaccounted tiles" to the "enclosedTiles" set for (y in pipeNetwork.map.first().indices) { for (x in pipeNetwork.map.indices) { when (val point = Point(x, y)) { in pipeNetwork.loop -> print(pipeNetwork.map[x][y]) in outsideTiles -> print('O') else -> { print(" ") enclosedTiles.add(point) } } } println() } // shrink to original size by ignoring all added columns & rows return enclosedTiles.filter { it.x % 2 == 0 && it.y % 2 == 0 }.size } } fun main() { val testInput = readInput("Day10_test", 2023) val testInput2 = """FF7FSF7F7F7F7F7F---7 L|LJ||||||||||||F--J FL-7LJLJ||||||LJL-77 F--JF--7||LJLJ7F7FJ- L---JF-JLJ.||-FJLJJ7 |F|F-JF---7F7-L7L|7| |FFJF7L7F-JF7|JL---7 7-L-JL7||F7|L7F-7F7| L.L7LFJ|||||FJL7||LJ L7JLJL-JLJLJL--JLJ.L""" check(Day10.part1(testInput) == 8) check(Day10.part2(testInput2.split("\n")) == 10) val input = readInput("Day10", 2023) println(Day10.part1(input)) println(Day10.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
6,856
adventOfCode
Apache License 2.0
solutions/round1/A/append-sort/src/main/kotlin/append/sort/AppendSortSolution.kt
Lysoun
351,224,145
false
null
import java.math.BigInteger fun main(args: Array<String>) { val casesNumber = readLine()!!.toInt() for (i in 1..casesNumber) { // Ignore list size readLine() println("Case #$i: ${countDigitsRequiredForAppendSort(readLine()!!.split(" ").map { it.toBigInteger() })}") } } fun countDigitsRequiredForAppendSort(list: List<BigInteger>): Int { var digitsRequired = 0 var digitsToAdd: String val sortedList = mutableListOf(list[0]) var last = list[0] for (i in 1 until list.size) { var elt = list[i] digitsToAdd = diff(last, elt) elt = (elt.toString() + digitsToAdd).toBigInteger() digitsRequired += digitsToAdd.length last = elt sortedList.add(last) } return digitsRequired } fun diff(int1: BigInteger, int2: BigInteger): String { if (int1 < int2) { return "" } if(int1 == int2) { return "0" } val str1 = int1.toString() val str2 = int2.toString() val lengthDifference = str1.length - str2.length val startOfStr1 = str1.substring(0, str2.length).toBigInteger() if (startOfStr1 > int2) { return "0".repeat(lengthDifference + 1) } if (startOfStr1 < int2) { return "0".repeat(lengthDifference) } return incrementDigitsToAdd(str1.substring(str2.length, str1.length)) } fun incrementDigitsToAdd(digitsToAdd: String): String { return if (digitsToAdd == "") { "0" } else { if (digitsToAdd.all { it == '9' }) { "0".repeat(digitsToAdd.length + 1) } else { val result = (digitsToAdd.toBigInteger() + BigInteger.ONE).toString() "0".repeat(digitsToAdd.length - result.length) + result } } }
0
Kotlin
0
0
98d39fcab3c8898bfdc2c6875006edcf759feddd
1,761
google-code-jam-2021
MIT License
src/main/kotlin/year2022/day11/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day11 import IProblem import java.lang.Exception class Problem : IProblem { private val monkeys = mutableListOf<Monkey>() private var divisor = 1UL init { javaClass .getResourceAsStream("/2022/11.txt")!! .bufferedReader() .use { while (true) { val line = it.readLine() ?: break if (line.isEmpty()) continue val id = line.substring(7, line.lastIndex).toInt() val items = it.readLine().substring(18).split(", ").map(String::toULong) val operation = parseOperation(it.readLine()) val test = parseTest(it.readLine(), it.readLine(), it.readLine()) monkeys.add(Monkey(id, items, operation, test)) } } } private fun parseOperation(s: String): (ULong) -> ULong { val split = s.substring(19).split(' ') val left = if (split[0] == "old") null else split[0].toULong() val right = if (split[2] == "old") null else split[2].toULong() return { val l = left ?: it val r = right ?: it when (split[1]) { "+" -> (l + r) % divisor "*" -> (l * r) % divisor else -> throw Exception("bruh moment") } } } private fun parseTest(test: String, ifTrue: String, ifFalse: String): (ULong) -> Int { val d = test.substring(21).toULong() val destTrue = ifTrue.substring(29).toInt() val destFalse = ifFalse.substring(30).toInt() divisor *= d return { if (it % d == 0UL) destTrue else destFalse } } private fun getBusinessLevel(rounds: Int, relief: UInt): ULong { val copy = Array(monkeys.size) { monkeys[it].copy() } for (i in 0 until rounds) { for (monkey in copy) { monkey.round(copy, relief) } } return copy .map(Monkey::inspections) .sortedDescending() .take(2) .reduce { a, i -> a * i } } override fun part1(): ULong { return getBusinessLevel(20, 3U) } override fun part2(): ULong { return getBusinessLevel(10000, 1U) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,321
advent-of-code
The Unlicense
ceria/12/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; val startNodes = mutableSetOf<String>() val endNodes = mutableSetOf<String>() val nodePaths = mutableListOf<Pair<String, String>>() fun main(args : Array<String>) { val input = File(args.first()).readLines() for (line in input) { var nodes = line.split("-") if (nodes[0].equals("start")) { startNodes.add(nodes[1]) } else if (nodes[1].equals("start")) { startNodes.add(nodes[0]) } else if (nodes[0].equals("end")) { endNodes.add(nodes[1]) } else if (nodes[1].equals("end")) { endNodes.add(nodes[0]) } else { nodePaths.add(Pair<String, String>(nodes[0], nodes[1])) } } println("Solution 1: ${solution1()}") println("Solution 2: ${solution2()}") } private fun solution1() :Int { var paths = mutableSetOf<MutableList<String>>() for (node in startNodes) { // If the start node is also an end node, add it as a single path to paths before // executing findPath() if (node in endNodes) { paths.add(mutableListOf<String>(node)) } paths.addAll(findPath(node, mutableListOf<String>(node), mutableSetOf<MutableList<String>>(), false)) } return paths.size } private fun solution2() :Int { var paths = mutableSetOf<MutableList<String>>() for (node in startNodes) { // If the start node is also an end node, add it as a single path to paths before // executing findPath() if (node in endNodes) { paths.add(mutableListOf<String>(node)) } paths.addAll(findPath(node, mutableListOf<String>(node), mutableSetOf<MutableList<String>>(), true)) } return paths.size } private fun findPath(n: String, path: MutableList<String>, paths: MutableSet<MutableList<String>>, extended: Boolean) :MutableSet<MutableList<String>> { // find all the nodes we can go to from n val possibles = mutableSetOf<String>() for (nodePair in nodePaths) { if (nodePair.first.equals(n)) { possibles.add(nodePair.second) } else if (nodePair.second.equals(n)) { possibles.add(nodePair.first) } } // Iterate over all the possible paths for (node in possibles) { // copy the path thus far var pathCopy = ArrayList<String>(path) // make sure we follow the rules about being able to visit a node if ((node.all{ it.isLowerCase() } && !pathCopy.contains(node)) || node.all{ it.isUpperCase() }) { // if this isn't the same node passed into the algorithm, add it to // the path copy if (!node.equals(n)) { pathCopy.add(node) } // path copy is complete - add it to the paths if (node in endNodes) { paths.add(pathCopy) } // continue to look for paths until the enclosing if condition isn't met paths.addAll(findPath(node, pathCopy, paths, extended)) } else { if (extended) { // check to see if there are other small caves in the path at least twice var canUseAgain = true var smallCaves = pathCopy.filter{ it.all{ it.isLowerCase() } }.groupingBy{ it }.eachCount() if (smallCaves.values.filter{ it == 2 }.size > 0) { canUseAgain = false } if (canUseAgain) { // if this isn't the same node passed into the algorithm, add it to // the path copy if (!node.equals(n)) { pathCopy.add(node) } // path copy is complete - add it to the paths if (node in endNodes) { paths.add(pathCopy) } // continue to look for paths until the enclosing if condition isn't met paths.addAll(findPath(node, pathCopy, paths, extended)) } } } } return paths }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
4,172
advent-of-code-2021
MIT License
src/day03/Day03.kt
GrzegorzBaczek93
572,128,118
false
{"Kotlin": 44027}
package day03 import readInput import utils.asNumber import utils.withStopwatch fun main() { val testInput = readInput("input03_test") withStopwatch { println(part1(testInput)) } withStopwatch { println(part2(testInput)) } val input = readInput("input03") withStopwatch { println(part1(input)) } withStopwatch { println(part2(input)) } } private fun part1(input: List<String>) = input.sumOf { it.findCommon().asNumber() } private fun part2(input: List<String>) = input.chunked(3).sumOf { it.findCommon().asNumber() } private fun String.findCommon(): Char { val (s1, s2) = chunked(length / 2) return s2.first { s1.contains(it) } } private fun List<String>.findCommon(): Char { val (s1, s2, s3) = this val commonElements = mutableSetOf<Char>() s2.forEach { if (s1.contains(it)) commonElements.add(it) } return s3.first { commonElements.contains(it) } }
0
Kotlin
0
0
543e7cf0a2d706d23c3213d3737756b61ccbf94b
907
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/g2401_2500/s2402_meeting_rooms_iii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2402_meeting_rooms_iii // #Hard #Array #Sorting #Heap_Priority_Queue // #2023_07_03_Time_976_ms_(100.00%)_Space_108.7_MB_(66.67%) import java.util.Arrays class Solution { fun mostBooked(n: Int, meetings: Array<IntArray>): Int { val counts = IntArray(n) val endTimes = LongArray(n) Arrays.sort(meetings) { a: IntArray, b: IntArray -> Integer.compare(a[0], b[0]) } for (meeting in meetings) { val id = findRoomId(endTimes, meeting[0]) counts[id]++ endTimes[id] = endTimes[id].coerceAtLeast(meeting[0].toLong()) + meeting[1] - meeting[0] } var res = 0 var count: Long = 0 for (i in 0 until n) { if (counts[i] > count) { count = counts[i].toLong() res = i } } return res } private fun findRoomId(endTimes: LongArray, start: Int): Int { val n = endTimes.size // Find the first one for (i in 0 until n) { if (endTimes[i] <= start) { return i } } // Only when non is not delayed, then we find the smallest one var id = 0 var min = Long.MAX_VALUE for (i in 0 until n) { if (endTimes[i] < min) { min = endTimes[i] id = i } } return id } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,418
LeetCode-in-Kotlin
MIT License
src/aoc2022/day08/Day08.kt
svilen-ivanov
572,637,864
false
{"Kotlin": 53827}
package aoc2022.day08 import readInput @OptIn(ExperimentalStdlibApi::class) fun main() { fun part1(input: List<String>) { val map: MutableList<List<Int>> = mutableListOf() for (line in input) { map.add(line.map { it.toString().toInt() }) } val rows = map.size val cols = map.first().size val visible = mutableSetOf<Pair<Int, Int>>() for (x in 0.rangeUntil(rows)) { var max = Int.MIN_VALUE for (y in 0.rangeUntil(cols)) { val tree = map[x][y] if (tree > max) { max = tree visible.add(x to y) } } } for (x in 0.rangeUntil(rows)) { var max = Int.MIN_VALUE for (y in 0.rangeUntil(cols).reversed()) { val tree = map[x][y] if (tree > max) { max = tree visible.add(x to y) } } } for (y in 0.rangeUntil(cols)) { var max = Int.MIN_VALUE for (x in 0.rangeUntil(rows)) { val tree = map[x][y] if (tree > max) { max = tree visible.add(x to y) } } } for (y in 0.rangeUntil(cols)) { var max = Int.MIN_VALUE for (x in 0.rangeUntil(rows).reversed()) { val tree = map[x][y] if (tree > max) { max = tree visible.add(x to y) } } } println(visible.size) check(visible.size == 1820) } fun calcScore(map: MutableList<List<Int>>, x: Int, y: Int): Int { val rows = map.size val cols = map.first().size // left val tree = map[y][x] var count1 = 0 for (cx in (0 until x).reversed()) { val h = map[y][cx] if (h < tree) { count1++ } if (h >= tree) { count1++ break } } // right var count2 = 0 for (cx in (x + 1 until cols)) { val h = map[y][cx] if (h < tree) { count2++ } if (h >= tree) { count2++ break } } // down var count3 = 0 for (cy in (0 until y).reversed()) { val h = map[cy][x] if (h < tree) { count3++ } if (h >= tree) { count3++ break } } // down var count4 = 0 for (cy in (y + 1 until rows)) { val h = map[cy][x] if (h < tree) { count4++ } if (h >= tree) { count4++ break } } return count1 * count2 * count3 * count4 } fun part2(input: List<String>) { val map: MutableList<List<Int>> = mutableListOf() for (line in input) { map.add(line.map { it.toString().toInt() }) } val rows = map.size val cols = map.first().size var score = Int.MIN_VALUE for (y in (0 + 1).rangeUntil(rows - 1)) { for (x in (0 + 1).rangeUntil(cols - 1)) { val currentScore = calcScore(map, x, y) score = maxOf(score, currentScore) } } println(score) check(score == 385112) } val testInput = readInput("day08/day08") part1(testInput) part2(testInput) }
0
Kotlin
0
0
456bedb4d1082890d78490d3b730b2bb45913fe9
3,737
aoc-2022
Apache License 2.0
src/Day01.kt
peterphmikkelsen
573,069,935
false
{"Kotlin": 7834}
import java.io.File fun main() { fun part1(input: List<List<Int>>) = input.maxOf { it.sum() } fun part2(input: List<List<Int>>) = input.map(List<Int>::sum).sortedDescending().take(3).sum() // test if implementation meets criteria from the description, like: val testInput = readDayOneInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readDayOneInput("Day01") println(part1(input)) println(part2(input)) } private fun readDayOneInput(name: String): List<List<Int>> { return File("src", "$name.txt").readText() .split("\n\n") .map { it.replace("\n", " ") } .format() } private fun List<String>.format(): List<List<Int>> { return this.map { it.split(" ").map(String::toInt) } }
0
Kotlin
0
0
374c421ff8d867a0bdb7e8da2980217c3455ecfd
796
aoc-2022
Apache License 2.0
libraries/stdlib/test/OrderingTest.kt
AlexeyTsvetkov
17,321,988
true
{"Java": 22837096, "Kotlin": 18913890, "JavaScript": 180163, "HTML": 47571, "Protocol Buffer": 46162, "Lex": 18051, "Groovy": 13300, "ANTLR": 9729, "CSS": 9358, "IDL": 6426, "Shell": 4704, "Batchfile": 3703}
package test.comparisons import kotlin.test.* import org.junit.Test import kotlin.comparisons.* data class Item(val name: String, val rating: Int) : Comparable<Item> { public override fun compareTo(other: Item): Int { return compareValuesBy(this, other, { it.rating }, { it.name }) } } val STRING_CASE_INSENSITIVE_ORDER: Comparator<String> = compareBy { it: String -> it.toUpperCase() }.thenBy { it.toLowerCase() }.thenBy { it } class OrderingTest { val v1 = Item("wine", 9) val v2 = Item("beer", 10) @Test fun compareByCompareTo() { val diff = v1.compareTo(v2) assertTrue(diff < 0) } @Test fun compareByNameFirst() { val diff = compareValuesBy(v1, v2, { it.name }, { it.rating }) assertTrue(diff > 0) } @Test fun compareByRatingFirst() { val diff = compareValuesBy(v1, v2, { it.rating }, { it.name }) assertTrue(diff < 0) } @Test fun compareSameObjectsByRatingFirst() { val diff = compareValuesBy(v1, v1, { it.rating }, { it.name }) assertTrue(diff == 0) } @Test fun compareNullables() { val v1: Item? = this.v1 val v2: Item? = null val diff = compareValuesBy(v1, v2) { it?.rating } assertTrue(diff > 0) val diff2 = nullsLast(compareBy<Item> { it.rating }.thenBy { it.name }).compare(v1, v2) assertTrue(diff2 < 0) } @Test fun sortComparatorThenComparator() { val comparator = Comparator<Item> { a, b -> a.name.compareTo(b.name) }.thenComparator { a, b -> a.rating.compareTo(b.rating) } val diff = comparator.compare(v1, v2) assertTrue(diff > 0) val items = arrayListOf(v1, v2).sortedWith(comparator) assertEquals(v2, items[0]) assertEquals(v1, items[1]) } @Test fun combineComparators() { val byName = compareBy<Item> { it.name } val byRating = compareBy<Item> { it.rating } val v3 = Item(v1.name, v1.rating + 1) val v4 = Item(v2.name + "_", v2.rating) assertTrue( (byName then byRating).compare(v1, v2) > 0 ) assertTrue( (byName then byRating).compare(v1, v3) < 0 ) assertTrue( (byName thenDescending byRating).compare(v1, v3) > 0 ) assertTrue( (byRating then byName).compare(v1, v2) < 0 ) assertTrue( (byRating then byName).compare(v4, v2) > 0 ) assertTrue( (byRating thenDescending byName).compare(v4, v2) < 0 ) } @Test fun reversedComparator() { val comparator = compareBy<Item> { it.name } val reversed = comparator.reversed() assertEquals(comparator.compare(v2, v1), reversed.compare(v1, v2)) assertEquals(comparator, reversed.reversed()) } @Test fun naturalOrderComparator() { val v1 = "a" val v2 = "beta" assertTrue(naturalOrder<String>().compare(v1, v2) < 0) assertTrue(reverseOrder<String>().compare(v1, v2) > 0) assertTrue(reverseOrder<Int>() === naturalOrder<Int>().reversed()) assertTrue(naturalOrder<Int>() === reverseOrder<Int>().reversed()) } @Test fun sortByThenBy() { val comparator = compareBy<Item> { it.rating }.thenBy { it.name } val diff = comparator.compare(v1, v2) assertTrue(diff < 0) val items = arrayListOf(v1, v2).sortedWith(comparator) assertEquals(v1, items[0]) assertEquals(v2, items[1]) } @Test fun sortByThenByDescending() { val comparator = compareBy<Item> { it.rating }.thenByDescending { it.name } val diff = comparator.compare(v1, v2) assertTrue(diff < 0) val items = arrayListOf(v1, v2).sortedWith(comparator) assertEquals(v1, items[0]) assertEquals(v2, items[1]) } @Test fun sortUsingFunctionalComparator() { val comparator = compareBy<Item>({ it.name }, { it.rating }) val diff = comparator.compare(v1, v2) assertTrue(diff > 0) val items = arrayListOf(v1, v2).sortedWith(comparator) assertEquals(v2, items[0]) assertEquals(v1, items[1]) } @Test fun sortUsingCustomComparator() { val comparator = object : Comparator<Item> { override fun compare(o1: Item, o2: Item): Int { return compareValuesBy(o1, o2, { it.name }, { it.rating }) } override fun equals(other: Any?): Boolean { return this == other } } val diff = comparator.compare(v1, v2) assertTrue(diff > 0) val items = arrayListOf(v1, v2).sortedWith(comparator) assertEquals(v2, items[0]) assertEquals(v1, items[1]) } }
1
Java
1
2
72a84083fbe50d3d12226925b94ed0fe86c9d794
4,720
kotlin
Apache License 2.0
src/net/sheltem/aoc/y2023/Day25.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.SearchGraph import net.sheltem.common.SearchGraph.Edge import net.sheltem.common.SearchGraph.Node import org.jgrapht.alg.StoerWagnerMinimumCut import org.jgrapht.graph.DefaultWeightedEdge import org.jgrapht.graph.SimpleWeightedGraph suspend fun main() { Day25().run() } class Day25 : Day<Long>(54, 5) { override suspend fun part1(input: List<String>) = input.solve() override suspend fun part2(input: List<String>) = 5L } private fun List<String>.solve(): Long { val graph = SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge::class.java) this.forEach { line -> val (name, targets) = line.split(": ") graph.addVertex(name) targets.split(" ").forEach { other -> graph.addVertex(other) graph.addEdge(name, other) } } val oneSide = StoerWagnerMinimumCut(graph).minCut() return (graph.vertexSet().size - oneSide.size) * oneSide.size.toLong() } private fun List<String>.parseGraph(): SearchGraph<String> { val nodes = mutableSetOf<Node<String>>() val edges = mutableSetOf<Edge<String>>() this.forEach { line -> val currNode = line.take(3).let(::Node) val components = line.drop(5).split(" ").map(::Node) nodes.add(currNode) components.forEach { conNode -> nodes.add(conNode) val edge = Edge(currNode, conNode, 0L) if (edge !in edges && edge.reversed() !in edges) { edges.add(edge) } } } return SearchGraph(nodes, edges, true) }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,621
aoc
Apache License 2.0
src/main/kotlin/days/Day13.kt
TheMrMilchmann
725,205,189
false
{"Kotlin": 61669}
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* fun main() { val patterns = readInput().joinToString(separator = "\n").split("\n\n").map { it -> it.split("\n").map { it.toList() }.toGrid() } fun Grid<Char>.indexOfHorizontalReflection(isEqual: (List<Char>, List<Char>) -> Boolean): Int { for (i in 1 until height) { val up = buildList { for (j in verticalIndices.filter { it.intValue < i }.asReversed()) { val start = GridPos(0.hPos, j) add(start) addAll(beam(start, ::shiftRight)) } } val down = buildList { for (j in verticalIndices.filter { it.intValue >= i }) { val start = GridPos(0.hPos, j) add(start) addAll(beam(start, ::shiftRight)) } } val n = minOf(up.size, down.size) if (isEqual(up.subList(0, n).map { this[it] }, down.subList(0, n).map { this[it] })) return i } return 0 } fun Grid<Char>.indexOfVerticalReflection(isEqual: (List<Char>, List<Char>) -> Boolean): Int { for (i in 1 until width) { val left = buildList { for (j in horizontalIndices.filter { it.intValue < i }.asReversed()) { val start = GridPos(j, 0.vPos) add(start) addAll(beam(start, ::shiftDown)) } } val right = buildList { for (j in horizontalIndices.filter { it.intValue >= i }) { val start = GridPos(j, 0.vPos) add(start) addAll(beam(start, ::shiftDown)) } } val n = minOf(left.size, right.size) if (isEqual(left.subList(0, n).map { this[it] }, right.subList(0, n).map { this[it] })) return i } return 0 } fun <E> List<E>.isAlmostEqual(other: List<E>): Boolean { if (size != other.size) return false var corrected = false for (i in indices) { if (this[i] != other[i]) { if (corrected) return false corrected = true } } return corrected } println("Part 1: ${patterns.sumOf { pattern -> 100 * pattern.indexOfHorizontalReflection(List<*>::equals) + pattern.indexOfVerticalReflection(List<*>::equals) }}") println("Part 2: ${patterns.sumOf { pattern -> 100 * pattern.indexOfHorizontalReflection(List<*>::isAlmostEqual) + pattern.indexOfVerticalReflection(List<*>::isAlmostEqual) }}") }
0
Kotlin
0
1
f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152
3,768
AdventOfCode2023
MIT License
Kotlin/Maths/HappyNumber.kt
HarshCasper
274,711,817
false
{"C++": 1488046, "Java": 948670, "Python": 703942, "C": 615475, "JavaScript": 228879, "Go": 166382, "Dart": 107821, "Julia": 82766, "C#": 76519, "Kotlin": 40240, "PHP": 5465}
/* A number is called happy if it leads to 1 after a sequence of steps wherein each step number is replaced by the sum of squares of its digit that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1. Examples of Happy numbers are:- 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70,... */ import java.util.* fun squaredSum(n: Int): Int{ var sum_of_square:Int = 0 var c:Int = n while(c!=0){ sum_of_square += c%10 * (c % 10) c /= 10 } return sum_of_square } //defining a boolean function to check whether the number is happy number or not fun Happynumber(number: Int): Boolean { var slow: Int var fast: Int fast = number slow = fast do { slow = squaredSum(slow) fast = squaredSum(squaredSum(fast)) } while (slow != fast) return slow == 1 } //Testing code fun main(){ val input = Scanner(System.`in`) println("Enter the number which you want to check") val n = input.nextInt() if (Happynumber(n)) println("$n is a Happy number") else println("$n is not a happy number") } /* Enter the number which you want to check 19 19 is a Happy number Enter the number which you want to check 20 20 is not a happy number */ /* Time complexity :- O(N) Space complexity :- O(1), which is constant */
2
C++
1,086
877
4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be
1,351
NeoAlgo
MIT License
src/main/kotlin/Day06.kt
SimonMarquis
724,825,757
false
{"Kotlin": 30983}
class Day06(private val input: List<String>) { fun part1(): Long = input .map { """\d+""".toRegex().findAll(it).map(MatchResult::value).map(String::toLong) } .let { (times, distances) -> (times zip distances) } .map { (time, distance) -> wins(time, distance) } .product() fun part2(): Long = input .map { it.filter(Char::isDigit).toLong() } .let { (time, distance) -> wins(time, distance) } private fun wins(time: Long, distance: Long): Long { var min = 0 while (min * (time - min) <= distance) min++ var max = time while (max * (time - max) <= distance) max-- return (max - min + 1) } }
0
Kotlin
0
1
043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e
696
advent-of-code-2023
MIT License
kts/aoc2016/aoc2016_11.kts
miknatr
576,275,740
false
{"Kotlin": 413403}
fun solve(input: String, extraOnFirstFloor: Int): Int { val floorItems = input.split("\n").map { it.split(" a ").count() - 1 }.toMutableList() floorItems[0] += extraOnFirstFloor return (1..floorItems.size - 1).map { floorItems.subList(0, it).sum() * 2 - 3 }.sum() } val input11 = """The first floor contains a thulium generator, a thulium-compatible microchip, a plutonium generator, and a strontium generator. The second floor contains a plutonium-compatible microchip and a strontium-compatible microchip. The third floor contains a promethium generator, a promethium-compatible microchip, a ruthenium generator, and a ruthenium-compatible microchip. The fourth floor contains nothing relevant.""" println("Part One") println(solve(input11, 0)) println("Part Two") println(solve(input11, 4))
0
Kotlin
0
0
400038ce53ff46dc1ff72c92765ed4afdf860e52
808
aoc-in-kotlin
Apache License 2.0
src/main/kotlin/io/tree/RearrangeTree.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.tree import io.models.TreeNode import io.utils.runTests import java.util.* // https://leetcode.com/problems/increasing-order-search-tree/ class RearrangeTree { fun executeRecursive(input: TreeNode?, acc: TreeNode? = null): TreeNode? = when (input) { null -> acc else -> { executeRecursive(input.right, executeRecursive(input.left, acc)?.also { var current = it while (current.right != null) current = current.right!! current.right = TreeNode(input.`val`) } ?: TreeNode(input.`val`)) } } fun executeIterative(input: TreeNode?): TreeNode? { var root: TreeNode? = null var current = input var last: TreeNode? = null val stack = LinkedList<TreeNode>() while (current != null || stack.isNotEmpty()) { while (current != null) { stack.push(current) current = current.left } if (stack.isNotEmpty()) { val item = stack.pop() TreeNode(item.`val`).let { newNode -> if (last == null) { root = newNode last = newNode } else { last!!.right = newNode last = newNode } } current = item?.right } } return root } } fun main() { runTests( listOf( Pair(TreeNode(5, left = TreeNode(3, left = TreeNode(2, left = TreeNode(1)), right = TreeNode(4)), right = TreeNode(6, right = TreeNode(8, left = TreeNode(7), right = TreeNode(9)))), TreeNode(1, right = TreeNode(2, right = TreeNode(3, right = TreeNode(4, right = TreeNode(5, right = TreeNode(6, right = TreeNode(7, right = TreeNode(8, right = TreeNode(9))))))))) ) ) ) { (input, value) -> Pair(value, RearrangeTree().executeRecursive(input)) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,110
coding
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/DesignHashMap.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 class DesignHashMap { private val nodes = Array<ListNode?>(10_000) { null } fun put(key: Int, value: Int) { val i = idx(key) if (nodes[i] == null) { nodes[i] = ListNode(-1, -1) } val prev = find(nodes[i], key) if (prev?.next == null) { prev?.next = ListNode(key, value) } else { prev.next?.value = value } } fun get(key: Int): Int { val i = idx(key) if (nodes[i] == null) return -1 val node = find(nodes[i], key) return if (node?.next == null) -1 else node.next?.value ?: -1 } fun remove(key: Int) { val i = idx(key) if (nodes[i] == null) return val prev = find(nodes[i], key) if (prev?.next == null) return prev.next = prev.next?.next } private fun idx(key: Int): Int = Integer.hashCode(key) % nodes.size private fun find(bucket: ListNode?, key: Int): ListNode? { var node: ListNode? = bucket var prev: ListNode? = null while (node != null && node.key != key) { prev = node node = node.next } return prev } class ListNode(val key: Int, var value: Int) { var next: ListNode? = null } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,918
kotlab
Apache License 2.0
src/main/kotlin/g2201_2300/s2272_substring_with_largest_variance/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2272_substring_with_largest_variance // #Hard #Array #Dynamic_Programming #2023_06_28_Time_338_ms_(100.00%)_Space_36.8_MB_(100.00%) class Solution { fun largestVariance(s: String): Int { val freq = IntArray(26) for (i in 0 until s.length) { freq[s[i].code - 'a'.code]++ } var maxVariance = 0 for (a in 0..25) { for (b in 0..25) { var remainingA = freq[a] val remainingB = freq[b] if (a == b || remainingA == 0 || remainingB == 0) { continue } var currBFreq = 0 var currAFreq = 0 for (i in 0 until s.length) { val c = s[i].code - 'a'.code if (c == b) { currBFreq++ } if (c == a) { currAFreq++ remainingA-- } if (currAFreq > 0) { maxVariance = Math.max(maxVariance, currBFreq - currAFreq) } if (currBFreq < currAFreq && remainingA >= 1) { currBFreq = 0 currAFreq = 0 } } } } return maxVariance } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,390
LeetCode-in-Kotlin
MIT License
Kotlin/Reference/src/basics.kt
mrkajetanp
83,730,170
false
null
fun sum(a: Int, b: Int): Int { return a + b } fun sum2(a: Int, b: Int) = a + b fun sum3(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") } fun functions() { println(sum(3, 5)) println(sum2(3, 5)) sum3(3, 5) } val PI = 3.14 fun variables() { val a: Int = 1 val b = 2 val c: Int c = 3 println("a = $a, b = $b, c = $c") var x = 5 x += 1 println("x = $x") println("PI = $PI") } // magic comment /* better comment */ fun stringTemplates() { var a = 1 val s1 = "a is $a" a = 2 val s2 = "${s1.replace("is", "was")}, but now is $a" println(s2) } fun maxOf(a: Int, b: Int): Int { if (a > b) return a else return b } fun maxOf2(a: Int, b: Int) = if (a > b) a else b fun parseInt(str: String): Int? { return str.toIntOrNull() } fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) if (x != null && y != null) println(x * y) else println("either '$arg1' or '$arg2' is not a number") } fun getStringLength(obj: Any): Int? { if (obj is String) return obj.length return null } fun getStringLength2(obj: Any): Int? { if (obj !is String) return null return obj.length } fun loops() { val items = listOf("apple", "banana", "kiwi") for (item in items) println(item) for (index in items.indices) println("item at $index is ${items[index]}") var idx = 0 while (idx < items.size) { println("item at $idx is ${items[idx]}") idx++ } if (10 in 1..12) println("fits in range") if (18 !in 1..12) println("does not fit in range") if (7 !in items.indices) println("index not in range") for (x in 1..5) print(x) println() for (x in 1..18 step 2) print("$x ") println() } fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a String" else -> "Unknown" } fun collections() { val items = listOf("apple", "banana", "kiwi", "avocado") when { "kiwi" in items -> println("kiwi's there") "orange" in items -> println("juicy") "apple" in items -> println("apple's fine too") } items.filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach {println(it)} } interface RectangleProperties { val isSquare: Boolean fun test(a: Int): Boolean } class Rectangle(var height: Double, var length: Double) : RectangleProperties { override val isSquare: Boolean get() = length == height override fun test(a: Int): Boolean { return true } } fun basics() { functions() variables() stringTemplates() printProduct("2", "3") printProduct("2", "3x") fun printLength(obj: Any) { println("'$obj' string length is ${getStringLength(obj) ?: ".. err, not a string"}") } printLength("something") printLength(1000) printLength(listOf(Any())) printLength(listOf("test", "test")) loops() collections() val rect = Rectangle(8.0, 8.0) println() }
31
Rust
2
1
85aea40a61fb824a2b4e142331d9ac7971fef263
3,318
learning-programming
MIT License
src/main/kotlin/algorithms/Utils.kt
Furetur
439,579,145
false
{"Kotlin": 21223, "ANTLR": 246}
package algorithms import model.Lang import model.Term import model.TermString fun kProduct(lang1: Lang, lang2: Lang, k: Int): Lang { require(k >= 1) val result = mutableSetOf<TermString>() for (s1 in lang1) { for (s2 in lang2) { result.add((s1 + s2).take(k)) } } return result } fun kProduct(term: Term, lang: Lang, k: Int): Lang = kProduct(setOf(listOf(term)), lang, k) fun <A, B> cartesianProduct(xs: Iterable<A>, ys: Iterable<B>): Set<Pair<A, B>> { val result = mutableSetOf<Pair<A, B>>() for (x in xs) { for (y in ys) { result.add(Pair(x, y)) } } return result } fun <T> List<T>.findAll(value: T): List<Int> { val result = mutableListOf<Int>() for ((index, el) in withIndex()) { if (el == value) { result.add(index) } } return result } fun TermString.debugString() = "<${joinToString(",")}>" fun Lang.debugString() = this.map { it.debugString() }.toString()
0
Kotlin
0
1
002cc53bcca6f9b591c4090d354f03fe3ffd3ed6
1,005
LLkChecker
MIT License
Java_part/AssignmentD/src/Q1.kt
enihsyou
58,862,788
false
{"Java": 77446, "Python": 65409, "Kotlin": 35032, "C++": 6214, "C": 3796, "CMake": 818}
import java.util.* data class Vertex(val name: String) data class Edge(val from: Vertex, val to: Vertex, val name: String = "$from -> $to") class Graph(private val vertexes: List<Vertex>, private val edges: List<Edge>) {//todo 应该使用Set val adjacencyMatrix = Array(vertexes.size) { row -> BooleanArray(vertexes.size) { col -> edges.filter { it.from == vertexes[row] && it.to == vertexes[col] }.any() } } val adjacencyList = List(vertexes.size) { vert -> val list = mutableListOf<Vertex>() edges.filter { it.from == vertexes[vert] }.forEach { list.add(it.to) } list.toList() } /*记录已访问的节点*/ private val matrixVisited = mutableSetOf<Int>() private val listVisited = mutableSetOf<Vertex>() /*滤出接下来要访问的节点*/ private val matrixMapToValue = { i: BooleanArray -> i .mapIndexed { index, b -> if (b) index else -1 } .filter { it >= 0 } .filter { !matrixVisited.contains(it) } } private val listMapToValue = { i: List<Vertex> -> i .filter { !listVisited.contains(it) } // .map { vertexes.indexOf(it) } } fun dfsMatrix(source: Vertex): List<Vertex> { matrixVisited.clear() fun dfs(which: Int) { if (matrixVisited.contains(which)) return matrixVisited += which adjacencyMatrix[which] .run(matrixMapToValue) .forEach(::dfs) } assert(source in vertexes) { "$source 应该在顶点列表里" } /*初始调用*/ dfs(vertexes.indexOf(source)) return matrixVisited.map { vertexes[it] } } fun bfsMatrix(source: Vertex): List<Vertex> { matrixVisited.clear() val next: Queue<Int> = LinkedList<Int>() fun bfs(which: Int) { next.add(which) while (next.isNotEmpty()) { val next_vertex = next.poll() if (matrixVisited.contains(next_vertex)) continue matrixVisited += next_vertex adjacencyMatrix[next_vertex] .run(matrixMapToValue) .forEach { next.add(it) } } } assert(source in vertexes) { "$source 应该在顶点列表里" } /*初始调用*/ bfs(vertexes.indexOf(source)) return matrixVisited.map { vertexes[it] } } fun dfsList(source: Vertex): List<Vertex> { listVisited.clear() fun dfs(which: Vertex) { if (listVisited.contains(which)) return listVisited += which adjacencyList[vertexes.indexOf(which)] .run(listMapToValue) .forEach(::dfs) } assert(source in vertexes) { "$source 应该在顶点列表里" } /*初始调用*/ dfs(source) return listVisited.toList() } fun bfsList(source: Vertex): List<Vertex> { listVisited.clear() val next: Queue<Vertex> = LinkedList<Vertex>() fun bfs(which: Vertex) { next.add(which) while (next.isNotEmpty()) { val next_vertex = next.poll() if (listVisited.contains(next_vertex)) continue listVisited += next_vertex adjacencyList[vertexes.indexOf(next_vertex)] .run(listMapToValue) .forEach { next.add(it) } } } assert(source in vertexes) { "$source 应该在顶点列表里" } /*初始调用*/ bfs(source) return listVisited.toList() } } fun main(args: Array<String>) { val a = Vertex("a") val b = Vertex("b") val c = Vertex("c") val d = Vertex("d") val e = Vertex("e") val graph = Graph(listOf( a, b, c, d, e ), listOf( Edge(a, b), Edge(a, c), Edge(b, d), Edge(b, e) )) println("先输入点的名字,以一个空行分隔") println("接下来输入<a, b>形式的二元组,代表从a到b有条有向边。最后以空行结束") println("例如:") println("a b c d e") println() println("a b") println("a c") println("b d") println("b e") println() println("结果如下:") println("DFS邻接矩阵: ${graph.dfsMatrix(a).joinToString { it.name }}") println("DFS邻接表: ${graph.dfsList(a).joinToString { it.name }}") println("BFS邻接矩阵: ${graph.bfsMatrix(a).joinToString { it.name }}") println("BFS邻接表: ${graph.bfsList(a).joinToString { it.name }}") println() println("接下来试试:") userInput() } fun userInput() { val s = Scanner(System.`in`) with(s) { val vertexList = nextLine() .split("\\s+".toRegex()) .map(::Vertex) nextLine() val edgeList = mutableListOf<Edge>() while (hasNextLine()) { val nextLine = nextLine() if (nextLine.isEmpty()) break val split = nextLine.split("\\s+".toRegex()) .map(::Vertex) .filter { vertexList.contains(it) } if (split.size != 2) error("一行应该只有有效的两个顶点名字") edgeList += Edge(split[0], split[1]) } val graph = Graph( vertexList, edgeList ) println("输入完成") println("邻接矩阵:") graph.adjacencyMatrix .map { it.joinToString { if (it) "1" else "0" } } .forEach(::println) println("邻接表:") graph.adjacencyList .map { it.joinToString() } .forEachIndexed { index, s -> println("${vertexList[index]} -> $s") } println("接下来输入搜索起始顶点: ") val from = Vertex(nextLine()) println("结果如下:") println("DFS邻接矩阵: ${graph.dfsMatrix(from).joinToString { it.name }}") println("DFS邻接表 : ${graph.dfsList(from).joinToString { it.name }}") println("BFS邻接矩阵: ${graph.bfsMatrix(from).joinToString { it.name }}") println("BFS邻接表 : ${graph.bfsList(from).joinToString { it.name }}") } }
0
Java
0
0
09a109bb26e0d8d165a4d1bbe18ec7b4e538b364
6,363
Sorting-algorithm
MIT License
archive/2022/Day10.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 13140 private const val EXPECTED_2 = 0 private class Day10(isTest: Boolean) : Solver(isTest) { fun generateX() = readAsLines().flatMap { val parts = it.split(" ") when (parts[0]) { "noop" -> listOf(0) "addx" -> listOf(0, parts[1].toInt()) else -> error("") } }.runningFold(1, Int::plus) fun part1() = (listOf(0) + generateX()).withIndex().filter { (index, _) -> (index - 20) % 40 == 0 }.sumOf { (index, value) -> (index * value) } fun part2(): Any { generateX().chunked(40).forEach { row -> for ((index, x) in row.withIndex()) { if (index in x - 1..x + 1) print('#') else print(" ") } println() } println() return 0 } } fun main() { val testInstance = Day10(true) val instance = Day10(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,229
advent-of-code-2022
Apache License 2.0
kotlin-math/src/main/kotlin/com/baeldung/math/sum/SumNaturalNumbers.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.math.sum fun sumUsingForLoop(n: Int): Int { var sum = 0 for (i in 1..n) { sum += i } return sum } fun sumUsingWhileLoop(n: Int): Int { var sum = 0 var i = 1 while (i <= n) { sum += i i++ } return sum } fun sumUsingArithmeticProgressionFormula(n: Int): Int { return (n * (n + 1)) / 2 } fun sumUsingRecursion(n: Int): Int { return if (n <= 1) { n } else { n + sumUsingRecursion(n - 1) } } fun sumUsingRangeAndSum(n: Int): Int { return (1..n).sum() } fun sumUsingRangeAndReduce(n: Int): Int { return (1..n).reduce { acc, num -> acc + num } } fun sumUsingRangeAndSumBy(n: Int): Int { return (1..n).sumBy { it } } fun sumUsingRangeAndFold(n: Int): Int { return (1..n).fold(0) { acc, num -> acc + num } } fun sumUsingSequence(n: Int): Int { return generateSequence(1) { it + 1 } .take(n) .sum() }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
949
kotlin-tutorials
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/EditDistance.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min fun interface EditDistance { operator fun invoke(word1: String, word2: String): Int } class EditDistanceDP : EditDistance { override operator fun invoke(word1: String, word2: String): Int { val n: Int = word1.length val m: Int = word2.length // if one of the strings is empty if (n * m == 0) return n + m // array to store the convertion history val d = Array(n + 1) { IntArray(m + 1) } // init boundaries for (i in 0 until n + 1) { d[i][0] = i } for (j in 0 until m + 1) { d[0][j] = j } // DP compute for (i in 1 until n + 1) { for (j in 1 until m + 1) { val left = d[i - 1][j] + 1 val down = d[i][j - 1] + 1 var leftDown = d[i - 1][j - 1] if (word1[i - 1] != word2[j - 1]) leftDown += 1 d[i][j] = min(left, min(down, leftDown)) } } return d[n][m] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,684
kotlab
Apache License 2.0
src/stack/CodilityStackTest1.kt
develNerd
456,702,818
false
{"Kotlin": 37635, "Java": 5892}
package stack import java.util.Stack /* * * * A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: S is empty; S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; S has the form "VW" where V and W are properly nested strings. For example, the string "{[()()]}" is properly nested but "([)()]" is not. Write a function: fun solution(S: String): Int that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise. For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..200,000]; string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")". * * * * * */ fun main(){ println(solution("(]VW")) } fun solution(S: String): Int { // write your code in Kotlin 1.3.11 (Linux) // Space complexity O(n), Time complexity O(n) if (S.isEmpty()) return 1 val stack = Stack<Char>() for (char in S){ when(char){ '{' -> stack.push(char) '(' -> stack.push(char) '[' -> stack.push(char) ']' -> { if (stack.isEmpty()) return 0 if (stack.pop() != '['){ return 0 } } ')' -> { if (stack.isEmpty()) return 0 if (stack.pop() != '('){ return 0 } } '}' -> { if (stack.isEmpty()) return 0 if (stack.pop() != '{'){ return 0 } } } } return if (stack.isEmpty()) 1 else 0 }
0
Kotlin
0
0
4e6cc8b4bee83361057c8e1bbeb427a43622b511
1,848
Blind75InKotlin
MIT License
day6/src/main/kotlin/aoc2015/day6/Day6.kt
sihamark
581,653,112
false
{"Kotlin": 263428, "Shell": 467, "Batchfile": 383}
package aoc2015.day6 /** * Created by <NAME> on 29.01.2019. */ object Day6 { fun calculateLitLights(): Int { val matrix = ToggleLightMatrix() input.forEach { rawCommand -> val command = Parser.parse(rawCommand) command.positions.forEach { position -> when (command.type) { Command.Type.TURN_ON -> matrix.turnOn(position) Command.Type.TURN_OFF -> matrix.turnOff(position) Command.Type.TOGGLE -> matrix.toggle(position) } } } return matrix.countTurnedOn() } fun calculateTotalBrightness(): Int { val matrix = BrightnessLightMatrix() input.forEach { rawCommand -> val command = Parser.parse(rawCommand) command.positions.forEach { position -> when (command.type) { Command.Type.TURN_ON -> matrix.turnOn(position) Command.Type.TURN_OFF -> matrix.turnOff(position) Command.Type.TOGGLE -> matrix.toggle(position) } } } return matrix.countTurnedOn() } private object Parser { private val regex = Regex("""(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)""") fun parse(rawCommand: String): Command { val matches = regex.find(rawCommand)?.groupValues ?: error("invalid raw command: $rawCommand") assert(matches.size == 6) val type = when (val rawType = matches[1]) { "turn on" -> Command.Type.TURN_ON "turn off" -> Command.Type.TURN_OFF "toggle" -> Command.Type.TOGGLE else -> error("unknown command: $rawType") } val start = parsePosition(matches[2], matches[3]) val end = parsePosition(matches[4], matches[5]) return Command(type, start..end) } private fun parsePosition(x: String, y: String) = Position(x.toInt(), y.toInt()) } private data class Command( val type: Type, val positions: PositionRange ) { enum class Type { TURN_ON, TURN_OFF, TOGGLE } } private operator fun Position.rangeTo(other: Position) = PositionRange(this, other) private data class PositionRange( val start: Position, val endInclusive: Position ) : Iterable<Position> { fun contains(position: Position) = position.x >= start.x && position.x <= endInclusive.x && position.y >= start.y && position.y <= endInclusive.y override fun iterator(): Iterator<Position> = PositionRangeIterator() private fun Position.next(): Position? { if (!contains(this)) return null if (this.x < endInclusive.x) return Position(this.x + 1, this.y) if (this.y < endInclusive.y) return Position(start.x, this.y + 1) return null } inner class PositionRangeIterator : Iterator<Position> { private var hasNext = true private var current = start override fun next(): Position { val result = current val next = current.next() if (next == null) { hasNext = false return result } current = next return result } override fun hasNext(): Boolean = hasNext } } private data class Position( val x: Int, val y: Int ) : Comparable<Position> { val index: Int get() = y * MAX + x init { validRange.let { validRange -> if (!validRange.contains(x)) error("x") if (!validRange.contains(y)) error("y") } } override fun compareTo(other: Position) = index.compareTo(other.index) companion object { const val MIN = 0 const val MAX = 1000 private const val ERROR = "%s must be greater or equals than $MIN and lower than $MAX" val validRange = MIN until MAX private fun error(variable: String): Nothing = throw IllegalArgumentException(ERROR.format(variable)) } } private class BrightnessLightMatrix { private val lights = mutableMapOf<Position, Int>() private operator fun get(position: Position): Int = lights[position] ?: 0 private operator fun set(position: Position, value: Int) { lights[position] = value } fun toggle(position: Position) { this[position] = this[position] + 2 } fun turnOn(position: Position) { this[position] = this[position] + 1 } fun turnOff(position: Position) { this[position] = (this[position] - 1).let { if (it < 0) 0 else it } } fun countTurnedOn() = lights.map { it.value }.sum() } private class ToggleLightMatrix { private val lights = mutableMapOf<Position, Boolean>() private operator fun get(position: Position): Boolean = lights[position] ?: false private operator fun set(position: Position, value: Boolean) { lights[position] = value } fun toggle(position: Position) { this[position] = !this[position] } fun turnOn(position: Position) { this[position] = true } fun turnOff(position: Position) { this[position] = false } fun countTurnedOn() = lights.count { it.value } } }
0
Kotlin
0
0
6d10f4a52b8c7757c40af38d7d814509cf0b9bbb
5,740
aoc2015
Apache License 2.0
src/main/kotlin/aoc/year2022/Day04.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2022 import aoc.Puzzle /** * [Day 4 - Advent of Code 2022](https://adventofcode.com/2022/day/4) */ object Day04 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int = input.lineSequence() .count { it.split(',') .map { range -> range.split('-') .map(String::toInt) .let { (a, b) -> a..b } } .let { (a, b) -> a in b || b in a } } override fun solvePartTwo(input: String): Int = input.lineSequence() .count { it.split(',') .map { range -> range.split('-') .map(String::toInt) .let { (a, b) -> a..b } } .let { (a, b) -> a overlaps b || b overlaps a } } private operator fun IntRange.contains(other: IntRange): Boolean = first in other && last in other private infix fun IntRange.overlaps(other: IntRange): Boolean = first in other || last in other }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,174
advent-of-code
Apache License 2.0
src/Day01.kt
lassebe
573,423,378
false
{"Kotlin": 33148}
fun main() { fun solve(input: List<String>): List<Int> { val elves = input.joinToString(":") .split("::") .map { it.split(":") } .map { it.map { it.toInt() } } .map { it.sum() } return elves.sorted() } fun part1(input: List<String>): Int { return solve(input).last() } fun part2(input: List<String>): Int { val elves = solve(input) return elves.last() + elves.get(elves.size - 2) + elves.get(elves.size - 3) } val testInput = readInput("Day01_test") println(part1(testInput)) check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c3157c2d66a098598a6b19fd3a2b18a6bae95f0c
726
advent_of_code_2022
Apache License 2.0
src/main/java/com/barneyb/aoc/aoc2022/day25/FullOfHotAir.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2022.day25 import com.barneyb.aoc.util.Solver import com.barneyb.aoc.util.toSlice fun main() { Solver.execute( ::parse, ::totalFuel, // 2-212-2---=00-1--102 ) } internal fun CharSequence.fromSnafu() = this.fold(0L) { n, c -> n * 5 + when (c) { '2' -> 2 '1' -> 1 '0' -> 0 '-' -> -1 '=' -> -2 else -> throw IllegalArgumentException("unrecognized '$c' digit") } } internal fun Long.toSnafu() = buildString { var n = this@toSnafu while (n > 0) { when (val d = n % 5) { 0L, 1L, 2L -> append(d) 3L -> { n += 5 append('=') } 4L -> { n += 5 append('-') } } n /= 5 } reverse() } internal fun parse(input: String) = input.toSlice() .trim() .lines() internal fun totalFuel(numbers: List<CharSequence>) = numbers.sumOf(CharSequence::fromSnafu) .toSnafu()
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
1,166
aoc-2022
MIT License
src/main/kotlin/Main.kt
ronhombre
753,669,759
false
{"Kotlin": 2448}
//These values below should be saved since we assume that Q is a constant. //The Q value for Kyber (ML-KEM). This is a prime number ((2^8 * 13) + 1) const val Q: Short = 3329 //Negative Modular Inverse of Q base 2^16 const val Q_INV = -62209 //Base 2^16. const val R_shift = 16 //R const val R = 1 shl R_shift //R * R = R^2 const val R_squared = R.toLong() shl R_shift fun main() { println("Short Int Montgomery Arithmetic in Kotlin") println("Author: <NAME>\n") val a: Short = 3228 val b: Short = 3228 val aMont = toMontgomeryForm(a) val bMont = toMontgomeryForm(b) val mulMont = montgomeryMultiply(aMont, bMont) //Simple Test Case println("Modulo : " + (a * b % Q)) println("Montgomery: " + montgomeryReduce(mulMont.toInt())) //Comprehensive Test Case comprehensiveTest() } fun comprehensiveTest() { //0 up to 32768 (excluding 32768). println("Running comprehensive test [0, 32768)...") var count = 0 var correct = 0 for(i in 0..<Short.MAX_VALUE.toInt()) { count++ val certain = (i * (Q - 1) % Q).toShort() val aMont = toMontgomeryForm(i.toShort()) val bMont = toMontgomeryForm((Q - 1).toShort()) val mulMont = montgomeryMultiply(aMont, bMont) val guess = montgomeryReduce(mulMont.toInt()) if(guess == certain) correct++ else println("$i/$certain/$guess") } println("Ratio(Correct/Total/Ratio): $correct/$count/" + (correct/count.toDouble() * 100) + "%") } //Convert values to Montgomery Form fun toMontgomeryForm(a: Short): Short { //Here R_squared % Q can be precomputed and Barrett Reduction can be used for a % Q. // (a * R_squared) % Q = ((a % Q) * (R_squared % Q)) % Q return montgomeryReduce((a * R_squared % Q).toInt()) } /* * Montgomery Reduction (REDC) * Source: Montgomery modular multiplication. (2023, November 28). In Wikipedia. https://en.wikipedia.org/wiki/Montgomery_modular_multiplication */ fun montgomeryReduce(t: Int): Short { //N = Q //N' = Q_INV //TN' mod R //Modulo for base 2 values is a simple AND operation. val m = (t * Q_INV) and ((R shl 1) - 1) //0xFFFF //(T + mN) / R val u = (t + m * Q) ushr R_shift return if (u >= Q) (u - Q).toShort() else u.toShort() } fun montgomeryMultiply(a: Short, b: Short): Short { val t = a * b //Automatically converts to Int return montgomeryReduce(t) }
0
Kotlin
0
0
24eac84091199663636eab59338e1abe0ae94a9b
2,448
MontgomeryArithmeticKotlinExample
Creative Commons Zero v1.0 Universal
src/Day01.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
fun main() { fun mostCaloriesCarriedBySingleElf(input: List<List<Int>>) = input.maxOfOrNull { bundle -> bundle.sum() } fun mostCaloriesCarriedByThreeElves(input: List<List<Int>>): Int { val caloriesPerElf = input .map { bundle -> bundle.sum() } .sorted() return caloriesPerElf.slice(caloriesPerElf.lastIndex - 2..caloriesPerElf.lastIndex).sum() } // test if implementation meets criteria from the description, like: val testInput = readBundledNumbers("Day01_test") check(mostCaloriesCarriedBySingleElf(testInput) == 24000) val input = readBundledNumbers("Day01") println(mostCaloriesCarriedBySingleElf(input)) println(mostCaloriesCarriedByThreeElves(input)) }
0
Kotlin
0
0
8f33c74e14f30d476267ab3b046b5788a91c642b
756
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/aoc2018/SettlersOfTheNorthPole.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2018 import komu.adventofcode.aoc2018.MapElement.* import komu.adventofcode.utils.Point fun settlersOfTheNorthPoleTest(input: String) = (1..10).fold(SettlersMap.parse(input)) { m, _ -> m.step() }.resourceValue fun settlersOfTheNorthPoleTest2(input: String): Int { var map = SettlersMap.parse(input) val maps = mutableListOf(map) while (true) { map = map.step() if (map in maps) { val prefixLength = maps.indexOf(map) val loopLength = maps.size - prefixLength return maps[prefixLength + (1_000_000_000 - prefixLength) % loopLength].resourceValue } maps += map } } private enum class MapElement(val code: Char) { GROUND('.'), TREE('|'), LUMBERYARD('#'); companion object { fun forCode(code: Char) = values().find { it.code == code } ?: error("invalid code '$code'") } } private class SettlersMap(private val width: Int, private val height: Int, init: (Point) -> MapElement) { private val data = Array(width * height) { init(Point(it % width, it / width)) } override fun equals(other: Any?): Boolean = other is SettlersMap && data.contentEquals(other.data) override fun hashCode() = data.contentHashCode() val resourceValue: Int get() = count(TREE) * count(LUMBERYARD) operator fun get(p: Point) = data[p.y * width + p.x] operator fun contains(p: Point) = p.x in (0 until width) && p.y in (0 until height) fun step() = SettlersMap(width, height) { p -> step(p) } fun step(p: Point): MapElement = when (this[p]) { GROUND -> if (countAdjacent(p, TREE) >= 3) TREE else GROUND TREE -> if (countAdjacent(p, LUMBERYARD) >= 3) LUMBERYARD else TREE LUMBERYARD -> if (countAdjacent(p, LUMBERYARD) >= 1 && countAdjacent(p, TREE) >= 1) LUMBERYARD else GROUND } private fun countAdjacent(p: Point, type: MapElement): Int = p.allNeighbors.count { it in this && this[it] == type } fun count(type: MapElement): Int = data.count { it == type } companion object { fun parse(input: String): SettlersMap { val lines = input.lines() val height = lines.size val width = lines[0].length return SettlersMap(width, height) { p -> MapElement.forCode(lines[p.y][p.x]) } } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,376
advent-of-code
MIT License
src/main/kotlin/advent/Day7.kt
chjaeggi
229,756,763
false
null
/** * Quest can be found here: * http://adventofcode.com/2019/day/7 */ package advent import com.marcinmoskala.math.permutations class Day7(input: List<Int>) : Day { private val intCodeProgram = input.toIntArray() override fun solvePart1(): Int { return listOf(0, 1, 2, 3, 4).permutations().map { phases -> runPhase(phases) }.max() ?: -1 } override fun solvePart2(): Int { return listOf(5, 6, 7, 8, 9).permutations().map { phases -> runAmplified(phases) }.max() ?: -1 } private fun runPhase(phases: List<Int>): Int { return (phases.indices).fold(0) { past, id -> IntCode(intCodeProgram).start(mutableListOf(phases[id], past)) } } private fun runAmplified(phases: List<Int>): Int { val intCodeMachines = listOf( IntCode(intCodeProgram, immediateReturnOnOutput = true), IntCode(intCodeProgram, immediateReturnOnOutput = true), IntCode(intCodeProgram, immediateReturnOnOutput = true), IntCode(intCodeProgram, immediateReturnOnOutput = true), IntCode(intCodeProgram, immediateReturnOnOutput = true) ) var active = 0 var output = 0 val phaseSet = mutableMapOf(0 to false, 1 to false, 2 to false, 3 to false, 4 to false) while (!(intCodeMachines.last()).halted) { val args = mutableListOf<Int>() if (phaseSet[active] != true) { args.add(phases[active]) phaseSet[active] = true } args.add(output) output = intCodeMachines[active].start(args) active += 1 active %= 5 } return output } }
0
Kotlin
0
1
d31bdf97957794a631e684a2136bd1bd89c55f0e
1,773
aoc-2019-kotlin
Apache License 2.0
src/main/kotlin/adventofcode/y2021/Day16.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
import adventofcode.* import java.math.BigInteger import java.util.* import java.util.concurrent.atomic.AtomicInteger fun main() { val testInput = """ C200B40A82 """.trimIndent() runDay( day = Day16::class, testInput = testInput, testAnswer1 = 14, testAnswer2 = 3 ) } open class Day16(staticInput: String? = null) : Y2021Day(16, staticInput) { private val input = fetchInput() data class Packet(val version: Int, val typeId: Int, val subPackets: List<Packet>, val value: BigInteger) val packet: Packet init { fun hexToString(s: Char): String { return when (s) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'A' -> "1010" 'B' -> "1011" 'C' -> "1100" 'D' -> "1101" 'E' -> "1110" 'F' -> "1111" else -> throw RuntimeException() } } val translated = input[0].map { hexToString(it) }.joinToString(separator = "") { it } packet = readPacket(translated, AtomicInteger(0)) } fun readPacket(s: String, i: AtomicInteger): Packet { val V = s.substring(i.get(), i.addAndGet(3)).binaryStringToInt() val T = s.substring(i.get(), i.addAndGet(3)).binaryStringToInt() if (T == 4) { var num = "" while (true) { val nextNum = s.substring(i.get(), i.addAndGet(5)) num += nextNum.substring(1, 5) if (nextNum[0] == '0') { break } } return Packet(V, T, emptyList(), num.binaryStringToBigInteger()) } else { val lengthType = s.substring(i.get(), i.addAndGet(1)) val bits = if (lengthType == "1") 11 else 15 val subPacketLength = s.substring(i.get(), i.addAndGet(bits)).binaryStringToInt() val subPackets = arrayListOf<Packet>() val subPacketString = s.substring(i.get(), i.get() + subPacketLength) if (lengthType == "0") { val subPacketI = AtomicInteger(0) while (subPacketI.get() < subPacketLength) { subPackets.add(readPacket(subPacketString, subPacketI)) } i.addAndGet(subPacketI.get()) } else if (lengthType == "1") { for (i_ in 0 until subPacketLength) { subPackets.add(readPacket(s, i)) } } return Packet(V, T, subPackets, BigInteger.ZERO) } } override fun reset() { super.reset() } override fun part1(): Number? { val left = LinkedList<Packet>() left.add(packet) while (left.isNotEmpty()) { val p = left.pop() left.addAll(p.subPackets) sum += p.version.toBigInteger() } return sum } override fun part2(): Number? { return packetValue(packet) } fun packetValue(p: Packet): BigInteger { return when (p.typeId) { 0 -> p.subPackets.sumOf { packetValue(it) } 1 -> p.subPackets.map { packetValue(it) }.reduce { a, b -> a * b } 2 -> { val m = MinValue() p.subPackets.map { packetValue(it) }.forEach { m.next(it) } m.get() } 3 -> { val m = MaxValue() p.subPackets.map { packetValue(it) }.forEach { m.next(it) } m.get() } 4 -> { p.value } 5 -> { val a = packetValue(p.subPackets[0]) val b = packetValue(p.subPackets[1]) if (a > b) { BigInteger.ONE } else { BigInteger.ZERO } } 6 -> { val a = packetValue(p.subPackets[0]) val b = packetValue(p.subPackets[1]) if (a < b) { BigInteger.ONE } else { BigInteger.ZERO } } 7 -> { val a = packetValue(p.subPackets[0]) val b = packetValue(p.subPackets[1]) if (a == b) { BigInteger.ONE } else { BigInteger.ZERO } } else -> throw java.lang.RuntimeException() } } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
4,808
adventofcode2021
The Unlicense
year2018/src/main/kotlin/net/olegg/aoc/year2018/day20/Day20.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day20 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.NEXT_4 import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 20](https://adventofcode.com/2018/day/20) */ object Day20 : DayOf2018(20) { private val START = Vector2D() private val MOVES = mapOf( 'W' to L, 'E' to R, 'N' to U, 'S' to D, ) override fun first(): Any? { val route = data.trim('^', '$', ' ', '\n') return visitAll(route).values.max() } override fun second(): Any? { val route = data.trim('^', '$', ' ', '\n') return visitAll(route).count { it.value >= 1000 } } private fun visitAll(route: String): Map<Vector2D, Int> { val stack = ArrayDeque(listOf(START)) val edges = mutableSetOf<Pair<Vector2D, Vector2D>>() val verts = mutableSetOf<Vector2D>() route.fold(START) { curr, char -> val next = when (char) { in MOVES -> (curr + (MOVES[char]?.step ?: Vector2D())) ')' -> stack.removeLast() '|' -> stack.last() '(' -> curr.also { stack.addLast(curr) } else -> curr } edges += curr to next edges += next to curr verts += next return@fold next } val queue = ArrayDeque(listOf(START)) val visited = mutableMapOf(START to 0).withDefault { 0 } while (queue.isNotEmpty()) { val curr = queue.removeFirst() val dist = visited.getValue(curr) + 1 val nexts = NEXT_4 .map { curr + it.step } .filter { it in verts } .filter { it !in visited } .filter { curr to it in edges } queue += nexts visited += nexts.map { it to dist } } return visited } } fun main() = SomeDay.mainify(Day20)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,951
adventofcode
MIT License
src/main/kotlin/com/jacobhyphenated/advent2023/day18/Day18.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day18 import com.jacobhyphenated.advent2023.Day import kotlin.math.absoluteValue /** * Day 18: Lavaduct Lagoon * * Workers need to dig a lagoon to hold excess lava. The puzzle input is instructions on how to dig * Each instruction has a direction, a value, and a color * By following the directions, the workers will dig out a border or the lagoon and return to the starting location */ class Day18: Day<List<Instruction>> { override fun getInput(): List<Instruction> { return parseInput(readInputFile("18")) } /** * Part 1: By following the instructions, we can see the border of the lagoon. * Calculate the number of interior spaces within this border and return the total area of the lagoon. * * Algorithm. This is a modified ray tracing algorithm (modified because the general algorithm doesn't * handle co-linear edges). Example, is the '?' an interior space? * ...####?.. * * Solve this by looking at how the edge is formed: * ......# * ...####? exterior ...####? Interior * ...#..# ...# */ override fun part1(input: List<Instruction>): Int { var current = Pair(0,0) // build a set of all points along the border val digBorder = mutableSetOf(current) for (instruction in input) { val (row, col) = current val line = when (instruction.direction) { Direction.DOWN -> (row + 1 .. row + instruction.value).map { Pair(it, col) } Direction.UP -> (row - 1 downTo row - instruction.value).map { Pair(it, col) } Direction.RIGHT -> (col + 1 .. col + instruction.value).map { Pair(row, it) } Direction.LEFT -> (col - 1 downTo col - instruction.value).map { Pair(row, it) } } digBorder.addAll(line) current = line.last() } // find the bounding box of the dig site val minX = digBorder.minOf { (_, c) -> c } val maxX = digBorder.maxOf { (_, c) -> c } val minY = digBorder.minOf { (r, _) -> r } val maxY = digBorder.maxOf { (r, _) -> r } // A ray starts at the far left. When it encounters a border point, // subsequent open spaces are interior until the next border point is reached. // repeat for the length of each row var interiorSpaces = 0 for (r in minY .. maxY) { var isInterior = false var borderStart: Int? = null for (c in minX .. maxX) { val isBorder = Pair(r,c) in digBorder if (isBorder) { if (borderStart == null) { borderStart = c } } else { if (borderStart != null && borderStart == c - 1) { isInterior = !isInterior } // the tricky part here is how to handle a border "line" else if (borderStart != null && borderStart != c - 1) { val startUp = Pair(r - 1, borderStart) in digBorder val endUp = Pair(r - 1, c - 1) in digBorder // If the border "line" comes from different directions, flip the interior flag // otherwise treat the line as an empty space, rather than a border if (startUp != endUp) { isInterior = !isInterior } } borderStart = null if (isInterior) { interiorSpaces++ } } } } return interiorSpaces + digBorder.size } /** * Part 2: The color is actually the instructions * The first 5 digits of the hex value or the dig length. * The last digit represents direction (0: right, 1: Down, etc) * * The bounding box is in the hundreds of trillions. There is no way to make ray tracing from part 1 work. * Even calculating each point would be impossible. * * Instead, we solve this with weird math shit. I spent most of this part on wikipedia * https://en.wikipedia.org/wiki/Pick%27s_theorem * https://en.wikipedia.org/wiki/Shoelace_formula */ override fun part2(input: List<Instruction>): Long { val instructions = input.map { (_, _, color) -> val value = color.substring(1, color.length - 1).toInt(16) val direction = when (color.last()) { '0' -> Direction.RIGHT '1' -> Direction.DOWN '2' -> Direction.LEFT '3' -> Direction.UP else -> throw IllegalArgumentException("Invalid direction") } Instruction(direction, value, color) } // build a list of vertices. // Note: our polygon is closed, does not intersect itself, and has no interior holes var current = Pair(0,0) val vertices = mutableListOf(current) instructions.forEach { (direction, value) -> val (row, col) = current current = when(direction) { Direction.DOWN -> Pair(row + value, col) Direction.UP -> Pair(row - value, col) Direction.RIGHT -> Pair(row, col + value) Direction.LEFT -> Pair(row, col - value) } vertices.add(current) } // This is the shoelace formula. I don't know why it works. var area: Long = 0 for (i in 0 until vertices.size - 1) { val (x1, y1) = vertices[i] val (x2, y2) = vertices[i+1] area += x1.toLong() * y2.toLong() - y1.toLong() * x2.toLong() } area = area.absoluteValue / 2 // but the area is not actually the full area. This is why we need Pick's theorem // A = i + b/2 - 1 // where i is the interior spaces (from the shoelace formula) and b is the perimeter length val perimeter = instructions.sumOf { it.value } return area + perimeter / 2 + 1 } fun parseInput(input: String): List<Instruction> { return input.lines().map { line -> val (dir, num, colorString) = line.split(" ") val color = colorString.removePrefix("(").removeSuffix(")") Instruction(Direction.fromString(dir), num.toInt(), color) } } } data class Instruction(val direction: Direction, val value: Int, val color: String) enum class Direction { RIGHT, LEFT, UP, DOWN; companion object { fun fromString(input: String): Direction { return when (input) { "R" -> RIGHT "L" -> LEFT "U" -> UP "D" -> DOWN else -> throw IllegalArgumentException("Invalid direction $input") } } } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day18().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
6,341
advent2023
The Unlicense
movement/src/main/java/com/hawkeye/movement/utils/AngleMeasure.kt
kirvader
495,356,524
false
{"Kotlin": 116363}
package com.hawkeye.movement.utils import kotlin.math.PI fun cos(angle: AngleMeasure): Float = kotlin.math.cos(angle.radian()) fun sin(angle: AngleMeasure): Float = kotlin.math.sin(angle.radian()) fun abs(angle: AngleMeasure): AngleMeasure = Degree(kotlin.math.abs(angle.degree())) fun sign(angle: AngleMeasure): Float { return if (angle > Degree(0f)) { 1f } else if (angle < Degree(0f)) { -1f } else { 0f } } fun min(a: AngleMeasure, b: AngleMeasure): AngleMeasure = Degree(kotlin.math.min(a.degree(), b.degree())) fun max(a: AngleMeasure, b: AngleMeasure): AngleMeasure = Degree(kotlin.math.max(a.degree(), b.degree())) interface AngleMeasure : Comparable<AngleMeasure> { fun degree(): Float { return this.radian() * 180.0f / PI.toFloat() } fun radian(): Float { return this.degree() * PI.toFloat() / 180.0f } override operator fun compareTo(angle: AngleMeasure): Int { val deltaAngle = this.degree() - angle.degree() if (deltaAngle < -eps) { return -1 } if (deltaAngle > eps) { return 1 } return 0 } operator fun plus(angle: AngleMeasure): AngleMeasure { return Degree(this.degree() + angle.degree()) } operator fun minus(angle: AngleMeasure): AngleMeasure { return Degree(this.degree() - angle.degree()) } operator fun times(factor: Float): AngleMeasure { return Degree(this.degree() * factor) } operator fun div(factor: Float): AngleMeasure { return Degree(this.degree() / factor) } companion object { private const val eps = 0.00001f } } class Radian(private val angle: Float) : AngleMeasure { override fun degree(): Float = angle * 180.0f / PI.toFloat() override fun radian(): Float = angle } class Degree(private val angle: Float) : AngleMeasure { override fun degree(): Float = angle override fun radian(): Float = angle * PI.toFloat() / 180.0f }
0
Kotlin
0
0
9dfbebf977e96fe990c7b5300a28b48c1df11152
2,028
AutomatedSoccerRecordingWithAndroid
MIT License
src/Day02.kt
kmakma
574,238,598
false
null
fun main() { fun myScore(strategy: String): Int { return when { strategy.contains('X') -> 1 strategy.contains('Y') -> 2 strategy.contains('Z') -> 3 else -> throw IllegalArgumentException() } } fun part1(input: List<String>): Int { val wins = listOf("A Y", "B Z", "C X") val draws = listOf("A X", "B Y", "C Z") var score = 0 input.forEach { score += myScore(it) when { wins.contains(it) -> score += 6 draws.contains(it) -> score += 3 } } return score } fun lose(theirs: Char): Int { return when (theirs) { 'A' -> myScore("Z") 'B' -> myScore("X") 'C' -> myScore("Y") else -> throw IllegalArgumentException() } } fun draw(theirs: Char): Int { return 3 + when (theirs) { 'A' -> myScore("X") 'B' -> myScore("Y") 'C' -> myScore("Z") else -> throw IllegalArgumentException() } } fun win(theirs: Char): Int { return 6 + when (theirs) { 'A' -> myScore("Y") 'B' -> myScore("Z") 'C' -> myScore("X") else -> throw IllegalArgumentException() } } fun part2(input: List<String>): Int { var score = 0 input.forEach { when (it[2]) { 'X' -> { score += lose(it[0]) } 'Y' -> { score += draw(it[0]) } 'Z' -> { score += win(it[0]) } } } return score } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
1,860
advent-of-kotlin-2022
Apache License 2.0