path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/net/colors_wind/particleswarmoptimization/Particles.kt
ColorsWind
351,369,022
false
null
package net.colors_wind.particleswarmoptimization import net.colors_wind.particleswarmoptimization.Vector.Companion.times import kotlin.random.Random class Particles(val question: Question) { var iterations: Int = 0 val particles: Array<Particle> = Array(question.N){ Particle(this, it) } /** attribute **/ var gBest = ParticleValue(particles.maxByOrNull { it.fitness }!!) fun iterate() { particles.sortedBy { it.fitness }.forEachIndexed{index,particle -> particle.rank = index + 1} particles.forEach { particle -> particle.update() } iterations++ } operator fun get(index: Int) = particles[(index + question.N) % question.N] } data class Particle(private val particles: Particles, private val index: Int) { /** attribute **/ var velocity = Vector(DoubleArray(particles.question.dimension){ val bound = particles.question.bounds[it] Random.nextDouble(bound.lowerBound * 0.12, bound.upperBound * 0.12) }, particles.question.bounds) var location = Vector(particles.question.bounds) var fitness: Double = particles.question.fit(location) /** pBest **/ private var pBest = ParticleValue(this) /** rank **/ var rank = 0 fun update() { velocity = (particles.question.omega * velocity + particles.question.c1 * Random.nextDouble() * (pBest.location - location) + particles.question.c2 * Random.nextDouble() * (particles.gBest.location - location)) //print("$location ${location + velocity}") location = location + velocity //println(" $location") fitness = particles.question.fit(location) if (fitness < pBest.fitness) { pBest = ParticleValue(this) } if (pBest.fitness < particles.gBest.fitness) { particles.gBest = pBest } //if (Random.nextDouble() < (1-particles.iterations / particles.question.Gmax) * 0.01) pBest = particles[Random.nextInt(particles.question.N)].pBest } } data class ParticleValue(val location: Vector, val velocity: Vector, val fitness: Double) { constructor(particle: Particle) : this(particle.location.copy(), particle.velocity.copy(), particle.fitness) {} }
0
Kotlin
0
0
54f289a61436be27758a21a5581dd478c1d9f840
2,274
ParticleSwarmOptimization
MIT License
src/main/kotlin/kt/kotlinalgs/app/sorting/CountingSort.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.sorting println("test") /* array: (2, 6, 4) 0 1 2 3 4 5 6 7 8 9 10 counts bei max 10: (0,0,1,0,1,0,1,0,0,0,0 ) accumulated: (0,0,1,1,2,2,3,3,3,3,3 ) adj.: (0,0,0,1,2,2,3,3,3,3,3 ) output, for value array[0] = 2: index = counts[2] - 1 = 1 - 1 = 0 output[index] = value -> output[0] = 2 counts[value]-= 1 -> counts[2]-- = 0 */ val array1 = intArrayOf(2, 6, 4) val array2 = intArrayOf(15, 13, 1, 10, 17, 0, 2, 2, 7) val array3 = array1.clone() val array4 = array2.clone() val array5 = intArrayOf(-2, 0, 2) CountingSort().sort(array1, 10) CountingSort().sort(array2, 20) CountingSort().sortWithFlexMinMax(array3) CountingSort().sortWithFlexMinMax(array4) CountingSort().sortWithFlexMinMax(array5) // runtime: O(N + K), for finite ranges where N = array size & K = value range (max - min + 1) // space: O(N + K), aux arrays counts (K) + output (N) // stable when 3rd pass backwards println(array1.map { it }) println(array2.map { it }) println(array3.map { it }) println(array4.map { it }) println(array5.map { it }) // https://www.geeksforgeeks.org/counting-sort/ class CountingSort { fun sort(array: IntArray, maxValue: Int) { if (array.size <= 1) return // 1. pass: Calculate counts val counts = IntArray(maxValue + 1) array.forEach { counts[it] += 1 } // 2. pass: Cumulate counts for (index in 1 until counts.size) { counts[index] += counts[index - 1] } // 3. pass: put back in original array (count = index!) // stable, if we iterate backwards (because we are decreasing indices): // https://stackoverflow.com/questions/2572195/how-is-counting-sort-a-stable-sort val output = IntArray(array.size) for (index in array.size - 1 downTo 0) { val value = array[index] val finalPos = counts[value] - 1 output[finalPos] = value counts[value]-- } output.forEachIndexed { index, value -> array[index] = value } } fun sortWithFlexMinMax(array: IntArray) { if (array.size <= 1) return val min = array.min() ?: return //minOrNull() ?: return val max = array.max() ?: return //maxOrNull() ?: return val range = max - min + 1 // 1. pass: Calculate counts val counts = IntArray(range) array.forEach { counts[it - min] += 1 } // 2. pass: Cumulate counts for (index in 1 until counts.size) { counts[index] += counts[index - 1] } // 3. pass: put back in original array (count = index!) // stable, if we iterate backwards (because we are decreasing indices): // https://stackoverflow.com/questions/2572195/how-is-counting-sort-a-stable-sort val output = IntArray(array.size) for (index in array.size - 1 downTo 0) { val value = array[index] val finalPos = counts[value - min] - 1 output[finalPos] = value counts[value - min]-- } output.forEachIndexed { index, value -> array[index] = value } } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,382
KotlinAlgs
MIT License
src/Day10.kt
marosseleng
573,498,695
false
{"Kotlin": 32754}
fun main() { fun part1(input: List<String>): Int { return countSignals(input, draw = false) } fun part2(input: List<String>): Int { return countSignals(input, draw = true) } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) // check(part2(testInput) == 13140) val input = readInput("Day10") println(part1(input)) println(part2(input)) } fun countSignals(instructions: List<String>, draw: Boolean): Int { var cycleCount = 0 var registerXValue = 1 val remainingInstructions = instructions.toMutableList() val desiredCycles = listOf(20, 60, 100, 140, 180, 220) var sum = 0 val drawingResult = mutableListOf<Char>() var currentInstruction: String? = null var currentInstructionStartCycle: Int = 0 fun cycleStart(): Boolean { if (currentInstruction != null) { println("--START->performing other instruction.") return true } val instruction = remainingInstructions.removeFirstOrNull() ?: return false currentInstruction = instruction currentInstructionStartCycle = cycleCount println("--START->Starting [$instruction] @ $cycleCount.") return true } fun draw() { val drawingPosition = cycleCount - 1 // 0-239 val normalizedPosition = drawingPosition % 40 val character = if (normalizedPosition in ((registerXValue - 1)..(registerXValue + 1))) {// val character = if (drawingPosition in ((registerXValue - 1)..(registerXValue + 1))) { '#' } else { '.' } println("Adding '$character' to drawing result[$drawingPosition].") drawingResult.add(drawingPosition, character) } fun cycleEnd() { val instruction = currentInstruction ?: return var shouldResetInstruction = false when { instruction == "noop" -> { println("--END->Ending [$instruction].") shouldResetInstruction = true } instruction.startsWith("addx") -> { if (cycleCount - currentInstructionStartCycle == 1) { registerXValue += instruction.split(" ")[1].toInt() println("--END->Ending [$instruction]->registerXValue=$registerXValue.") shouldResetInstruction = true } else { println("--END->Processing [$instruction].") shouldResetInstruction = false } } } if (shouldResetInstruction) { println("--END->Resetting instruction.") currentInstruction = null currentInstructionStartCycle = 0 } } while (true) { cycleCount++ println("*** TICK: $cycleCount ***") if (!cycleStart()) { println("!!! NO INSTRUCTION.") break } if (draw) { draw() } if (cycleCount in desiredCycles) { sum += cycleCount * registerXValue println("!!! Updating sum = $sum.") } cycleEnd() } return sum.also { println("====$it====") if (draw) { println( drawingResult.chunked(40) .joinToString(separator = "\n") { it.joinToString(separator = "") } ) } } }
0
Kotlin
0
0
f13773d349b65ae2305029017490405ed5111814
3,476
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/frankandrobot/rapier/parse/getMatchedFillers.kt
frankandrobot
62,833,944
false
null
/* * Copyright 2016 <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 com.frankandrobot.rapier.parse import com.frankandrobot.rapier.meta.Example import com.frankandrobot.rapier.meta.Examples import com.frankandrobot.rapier.meta.SlotFiller import com.frankandrobot.rapier.nlp.Token import com.frankandrobot.rapier.rule.IRule import org.funktionale.memoization.memoize import java.util.* data class FillerMatchResults(val positives : List<SlotFiller>, val negatives : List<SlotFiller>) /** * Matches the rule against the example. If a filler occurs in the Example * enabledSlotFiller, then it is a positive match. Otherwise, it is a negative match. */ private val _getMatchedFillers = { rule: IRule, example: Example -> val slot = example[rule.slotName] if (slot.enabled) { val doc = example.document() val matchResults = rule.exactMatch(doc).distinctBy { it.fillerMatch.index } val fillerMatchResults = matchResults .map { it.fillerMatch } .filter { it().isDefined() } // put the match results in a SlotFiller val slotFillers = fillerMatchResults .map { it().get().map(Token::dropTagAndSemanticProperties) } .map { SlotFiller(tokens = it as ArrayList) } val positives = slotFillers.filter { slot.slotFillers.contains(it) } val negatives = slotFillers.filter { !slot.slotFillers.contains(it) } FillerMatchResults(positives = positives, negatives = negatives) } else { FillerMatchResults(positives = emptyList(), negatives = emptyList()) } }.memoize() internal fun getMatchedFillers(rule : IRule, example : Example) : FillerMatchResults = _getMatchedFillers(rule, example) private val _ruleGetMatchedFillers = { rule : IRule, examples : Examples -> examples() .map{ example -> getMatchedFillers(rule, example) } .fold(FillerMatchResults(emptyList(), emptyList())) { total, cur -> FillerMatchResults( positives = total.positives + cur.positives, negatives = total.negatives + cur.negatives ) } }.memoize() /** * Matches the rule against the examples. If a filler occurs in an Example * enabledSlotFiller, then it is a positive match. Otherwise, it is a negative match. * * Note that the results may contain duplicates. This corresponds to the (valid) case * where the rule matches the same filler in two or more examples. */ fun IRule.getMatchedFillers(examples : Examples) : FillerMatchResults = _ruleGetMatchedFillers(this, examples)
1
Kotlin
1
1
ddbc0dab60ca595e63a701e2f8cd6694ff009adc
3,092
rapier
Apache License 2.0
src/main/kotlin/org/hildan/ipm/helper/galaxy/money/Money.kt
joffrey-bion
226,177,839
false
null
package org.hildan.ipm.helper.galaxy.money import org.hildan.ipm.helper.utils.formatWithSuffix import kotlin.time.Duration import kotlin.time.seconds fun min(p1: Price, p2: Price) = if (p1 < p2) p1 else p2 fun List<Price>.sum() = fold(Price.ZERO) { p1, p2 -> p1 + p2} fun List<ValueRate>.sumRates() = fold(ValueRate.ZERO) { vr1, vr2 -> vr1 + vr2} operator fun Int.div(rate: Rate): Duration = (this / rate.timesPerSecond).seconds inline class Rate(val timesPerSecond: Double): Comparable<Rate> { operator fun plus(other: Rate): Rate = Rate(timesPerSecond + other.timesPerSecond) operator fun minus(other: Rate): Rate = Rate(timesPerSecond - other.timesPerSecond) operator fun times(factor: Double): Rate = Rate(timesPerSecond * factor) operator fun div(factor: Double): Rate = Rate(timesPerSecond / factor) override fun compareTo(other: Rate): Int = timesPerSecond.compareTo(other.timesPerSecond) override fun toString(): String = String.format("%.2f/s", timesPerSecond) } inline class ValueRate(val amountPerSec: Double) : Comparable<ValueRate> { operator fun plus(other: ValueRate) = ValueRate(amountPerSec + other.amountPerSec) operator fun minus(other: ValueRate) = ValueRate(amountPerSec - other.amountPerSec) override fun compareTo(other: ValueRate): Int = amountPerSec.compareTo(other.amountPerSec) fun formatPerMinute(): String = String.format("\$%s/min", (amountPerSec * 60).formatWithSuffix()) override fun toString(): String = String.format("\$%.2f/s", amountPerSec) companion object { val ZERO = ValueRate(0.0) } } inline class Price(private val amount: Double) : Comparable<Price> { constructor(amount: Int) : this(amount.toDouble()) constructor(amount: Long) : this(amount.toDouble()) operator fun plus(other: Price): Price = Price(amount + other.amount) operator fun minus(other: Price): Price = Price(amount - other.amount) operator fun div(other: Price): Double = amount / other.amount operator fun div(time: Duration): ValueRate = ValueRate(amount / time.inSeconds) operator fun div(rate: ValueRate): Duration = (amount / rate.amountPerSec).seconds operator fun times(factor: Double): Price = Price(amount * factor) operator fun times(factor: Int): Price = Price(amount * factor) operator fun times(rate: Rate): ValueRate = ValueRate(amount * rate.timesPerSecond) override fun compareTo(other: Price): Int = amount.compareTo(other.amount) override fun toString(): String = "\$${amount.formatWithSuffix()}" companion object { val ZERO = Price(0.0) } }
0
Kotlin
0
1
0458e397d5ccdc48015628c79c69fde47e2d4f22
2,626
idle-planet-miner-helper
MIT License
src/main/kotlin/com/github/shmvanhouten/adventofcode/day3/ValidTriangleCounter.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day3 class ValidTriangleCounter(private val validTriangleChecker: ValidTriangleChecker = ValidTriangleChecker()) { fun countValidTriangles(inputTrianglesString: String): Int { val trianglesList = formatInputStringToList(inputTrianglesString) return trianglesList.filter { validTriangleChecker.isTriangleValid(formatToTriangleWithDescendingValues(it)) }.size } fun countValidTrianglesFromVerticalInput(inputTrianglesString: String): Int { val inputLines = formatInputStringToList(inputTrianglesString) var validTriangleCount = 0 val tempTriangles = listOf<MutableList<Int>>(mutableListOf(), mutableListOf(), mutableListOf()) for (inputLine in inputLines) { inputLine.trimStart().split(" ").mapIndexed { index, side -> tempTriangles[index].add(side.toInt()) } if (tempTriangles[2].size == 3) { validTriangleCount += tempTriangles.filter { validTriangleChecker.isTriangleValid(it.sortedDescending()) }.size tempTriangles.map { it.clear() } } } return validTriangleCount } private fun formatInputStringToList(triangles: String): List<String> = triangles.replace(" ", " ").replace(" ", " ").split("\n") private fun formatToTriangleWithDescendingValues(triangleString: String) = triangleString.trimStart().split(" ").map { it.toInt() }.sortedDescending() }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
1,496
adventOfCode2016
MIT License
src/main/kotlin/utilities/TaxBracketGenerator.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70755}
package utilities import dataModel.base.Money.Companion.dollars import dataModel.base.Percent import dataModel.base.Percent.Companion.percent import dataModel.base.TaxBracket import kotlin.random.Random private val maxPercentBps = 100.percent.amountBps object TaxBracketGenerator { /** * The current data model can support a maximum of 10,000 brackets due to the following reasons: * * 1. In a progressive income tax system, the tax rate must be strictly increasing as you advance to the next * bracket. This results in an ordered list of brackets starting with the lowest tax rate and ending in the * highest tax rate. * * 2. Consecutive brackets cannot have the same tax rate otherwise they would be part of a single larger tax * bracket. * * 3. All brackets need a different tax rate in order to fulfill the previous 2 requirements so the maximum number * of brackets is limited by the maximum number of unique tax rates. * * 4. All regions in the world limit tax bracket percentages to at most 2 decimal places so using basis points is * the granularity limit. * * 5. Each percent is split into 100bps so there are up to 100% X 100bps = 10,000 unique tax rates possible. */ val maxNumTaxBrackets = maxPercentBps.toInt() fun generateTaxBrackets( numBrackets: Int, lowerBoundDollarsOfHighestBracket: Int = numBrackets * 100, random: Random = Random, ): List<TaxBracket> { require(numBrackets > 0) { "The number of tax brackets must be positive" } require(numBrackets <= maxNumTaxBrackets) { "Cannot create more than $maxNumTaxBrackets tax brackets" } if (numBrackets == 1) { require(lowerBoundDollarsOfHighestBracket == 0) { "The lower bound of the highest bracket must be 0 when creating a single bracket" } } require(lowerBoundDollarsOfHighestBracket + 1 >= numBrackets) { "Cannot create $numBrackets brackets if the highest bracket starts at $lowerBoundDollarsOfHighestBracket" } // Divide the range into numBrackets distinct lower-bound values including 0 val lowerBounds = hashSetOf(0.dollars) lowerBounds += lowerBoundDollarsOfHighestBracket.dollars while (lowerBounds.size < numBrackets) { lowerBounds += random.nextInt(until = lowerBoundDollarsOfHighestBracket).dollars } // generate a unique percentage for each bracket up to 100.00% (exclusive) val percentages = hashSetOf<Percent>() while (percentages.size < numBrackets) { percentages += Percent.ofBasisPoints(random.nextLong(until = maxPercentBps)) } val sortedPercentages = percentages.sortedBy { it.amountBps } val sortedLowerBounds = lowerBounds.sortedBy { it.cents } val result = ArrayList<TaxBracket>(numBrackets) for (i in 0..<numBrackets) { result += TaxBracket( taxRate = sortedPercentages[i], from = sortedLowerBounds[i], to = sortedLowerBounds.getOrNull(i + 1) ) } return result } }
0
Kotlin
0
1
166d8bc05c355929ffc5b216755702a77bb05c54
3,211
tax-calculator
MIT License
src/main/kotlin/solutions/CHK/CheckoutSolution.kt
DPNT-Sourcecode
749,456,768
false
{"Kotlin": 13106, "Shell": 2184}
package solutions.CHK //+------+-------+------------------------+ //| Item | Price | Special offers | //+------+-------+------------------------+ //| H | 10 | 5H for 45, 10H for 80 | //| K | 80 | 2K for 150 | //| N | 40 | 3N get one M free | //| P | 50 | 5P for 200 | //| Q | 30 | 3Q for 80 | //| R | 50 | 3R get one Q free | //| U | 40 | 3U get one U free | //| V | 50 | 2V for 90, 3V for 130 | //+------+-------+------------------------+ object CheckoutSolution { private val valid = listOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') fun checkout(skus: String): Int { if (skus.count { it !in valid } != 0) return -1 return Skus(totalSoFar = 0, skus = skus.toMutableList()) // SKUs without a deal involved .consumeSimpleItems() .consumeE() .consumeA() .consumeB() .consumeF() .totalSoFar } } data class Skus(var totalSoFar: Int, val skus: MutableList<Char>) { val simpleSkusToPrice = mapOf( 'C' to 20, 'D' to 15, 'G' to 20, 'I' to 35, 'J' to 60, 'L' to 90, 'M' to 15, 'O' to 10, 'S' to 30, 'T' to 20, 'W' to 20, 'X' to 90, 'Y' to 10, 'Z' to 50 ) fun consumeA(): Skus { val aCount = countSku('A') val firstDealCount = aCount / 5 val secondDealCount = (aCount - (firstDealCount * 5)) / 3 val leftOver = (aCount - (firstDealCount * 5) - secondDealCount * 3) skus.removeIf { it == 'A' } totalSoFar += (firstDealCount * 200) + (secondDealCount * 130) + (leftOver * 50) return this } fun consumeB(): Skus { val value = specialDeal(2, 45, 30, countSku('B')) skus.removeIf { it == 'B' } totalSoFar += value return this } fun consumeE(): Skus { val eCost = countSku('E') * 40 totalSoFar += eCost val freeBs = countSku('E') / 2 skus.removeIf { it == 'E' } for (i in 0 until freeBs ) { skus.remove('B') } return this } fun consumeF(): Skus { totalSoFar += freeSelfDeal('F', 3, 10) skus.removeIf { it == 'F' } return this } fun consumeSimpleItems(): Skus { simpleSkusToPrice.forEach { (sku, price) -> val count = skus.count { it == sku } totalSoFar += count * price skus.removeIf { it == sku } } return this } private fun countSku(char: Char) = this.skus.count { it == char } private fun freeSelfDeal(sku: Char, countForFree: Int, usualPrice: Int): Int { val count = countSku(sku) val free = count / countForFree return (count - free) * usualPrice } private fun specialDeal(dealCount: Int, forMoney: Int, usualPrice: Int, itemCount: Int): Int { var total = 0 var items = itemCount while (items >= dealCount) { total += forMoney items -= dealCount } total += items * usualPrice return total } }
0
Kotlin
0
0
cb056a981f511e8c887ce03317b94c28e62d4318
3,328
CHK-gply01
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindGoodStrings.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD /** * 1397. Find All Good Strings * @see <a href="https://leetcode.com/problems/find-all-good-strings/">Source</a> */ fun interface FindGoodStrings { operator fun invoke(n: Int, s1: String, s2: String, evil: String): Int } class FindGoodStringsDFS : FindGoodStrings { data class DfsParams( val i: Int, val evilMatched: Int, val leftBound: Boolean, val rightBound: Boolean, val n: Int, val s1: CharArray, val s2: CharArray, val evil: CharArray, val lps: IntArray, val dp: IntArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DfsParams if (i != other.i) return false if (evilMatched != other.evilMatched) return false if (leftBound != other.leftBound) return false if (rightBound != other.rightBound) return false if (n != other.n) return false if (!s1.contentEquals(other.s1)) return false if (!s2.contentEquals(other.s2)) return false if (!evil.contentEquals(other.evil)) return false if (!lps.contentEquals(other.lps)) return false if (!dp.contentEquals(other.dp)) return false return true } override fun hashCode(): Int { var result = i result = 31 * result + evilMatched result = 31 * result + leftBound.hashCode() result = 31 * result + rightBound.hashCode() result = 31 * result + n result = 31 * result + s1.contentHashCode() result = 31 * result + s2.contentHashCode() result = 31 * result + evil.contentHashCode() result = 31 * result + lps.contentHashCode() result = 31 * result + dp.contentHashCode() return result } } override operator fun invoke(n: Int, s1: String, s2: String, evil: String): Int { val dp = IntArray(1 shl BITS) return dfs( DfsParams( 0, 0, true, true, n, s1.toCharArray(), s2.toCharArray(), evil.toCharArray(), computeLPS(evil.toCharArray()), dp, ), ) } private fun dfs(params: DfsParams): Int { with(params) { if (evilMatched == evil.size) return 0 if (i == n) return 1 val key = getKey(i, evilMatched, leftBound, rightBound) if (dp[key] != 0) return dp[key] val from = if (leftBound) s1[i] else 'a' val to = if (rightBound) s2[i] else 'z' var res = 0 var c = from while (c <= to) { val nextMatch = computeNextMatch(evil, c, lps, evilMatched) res += dfs( DfsParams( i + 1, nextMatch, leftBound && c == from, rightBound && c == to, n, s1, s2, evil, lps, dp, ), ) res %= MOD c++ } return res.also { dp[key] = it } } } private fun computeNextMatch(evil: CharArray, c: Char, lps: IntArray, evilMatched: Int): Int { var j = evilMatched while (j > 0 && evil[j] != c) { j = lps[j - 1] } return if (c == evil[j]) j + 1 else 0 } private fun getKey(n: Int, m: Int, b1: Boolean, b2: Boolean): Int { return n shl 8 or (m shl 2) or ((if (b1) 1 else 0) shl 1) or if (b2) 1 else 0 } private fun computeLPS(str: CharArray): IntArray { val n = str.size val lps = IntArray(n) var i = 1 var j = 0 while (i < n) { j = updateJ(str, i, j, lps) i++ } return lps } private fun updateJ(str: CharArray, i: Int, j: Int, lps: IntArray): Int { var updatedJ = j while (updatedJ > 0 && str[i] != str[updatedJ]) { updatedJ = lps[updatedJ - 1] } if (str[i] == str[updatedJ]) { lps[i] = ++updatedJ } return updatedJ } companion object { private const val BITS = 17 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,265
kotlab
Apache License 2.0
src/main/kotlin/org/gnit/cpsd/GeoCalculation.kt
nehemiaharchives
325,581,086
false
null
package org.gnit.cpsd import kotlin.math.* /** * [Reference](https://stackoverflow.com/questions/3694380/calculating-distance-between-two-points-using-latitude-longitude) * * Calculate distance between two points in latitude and longitude taking * into account height difference. If you are not interested in height * difference pass 0.0. Uses Haversine method as its base. * * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters * el2 End altitude in meters * @returns Distance in Meters */ fun distanceOf( lat1: Double, lat2: Double, lng1: Double, lng2: Double, el1: Double, el2: Double ): Double { val R = 6371 // Radius of the earth val latDistance = Math.toRadians(lat2 - lat1) val lonDistance = Math.toRadians(lng2 - lng1) val a = (sin(latDistance / 2) * sin(latDistance / 2) + (cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(lonDistance / 2) * sin(lonDistance / 2))) val c = 2 * atan2(sqrt(a), sqrt(1 - a)) var distance = R * c * 1000 // convert to meters val height = el1 - el2 distance = distance.pow(2.0) + height.pow(2.0) return sqrt(distance) } /** * [Reference](https://gis.stackexchange.com/questions/15545/calculating-coordinates-of-square-x-miles-from-center-point) * @param lat latitude of center coordinate for square polygon * @param lng longitude of center coordinate for square polygon * @param side length of the side of square in meters * @return array of 5 coordinates to draw square polygon with GeoJson, order of corner is SW->SE->NE->NW->SW */ fun squareOf(lat: Double, lng: Double, side: Double): Array<Array<Double>> { val dLat = side / (111 * 1000) // Latitudinal or north-south distance in degrees val dLng = dLat / cos(Math.toRadians(lat)) // Longitudinal or east-west distance in degrees val nLat = dLat / 2 val nLng = dLng / 2 val lat1 = lat - nLat val lng1 = lng - nLng val lat2 = lat - nLat val lng2 = lng + nLng val lat3 = lat + nLat val lng3 = lng + nLng val lat4 = lat + nLat val lng4 = lng - nLng return arrayOf( arrayOf(lng1, lat1), arrayOf(lng2, lat2), arrayOf(lng3, lat3), arrayOf(lng4, lat4), arrayOf(lng1, lat1) ) } /** * @param latNE latitude of first geo polygon coordinate which is north-east corner * @param lngNE longitude of first geo polygon coordinate which is north-east corner * @param latSW latitude of third geo polygon coordinate which is south-west corner * @param lngSW longitude of third geo polygon coordinate which is south-west corner * @return array of Double representing (latitude, longitude) of center of the square */ fun centerOf(latNE: Double, lngNE: Double, latSW: Double, lngSW: Double): Array<Double> = arrayOf( (latNE + latSW) * 0.5, (lngNE + lngSW) * 0.5 )
0
Kotlin
0
0
055a7baf597e25ae48b6f4b5421cf249a1fb3dbe
2,868
cpsd
MIT License
src/main/java/com/booknara/problem/string/LongestPalindromicSubstringKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.string /** * 5. Longest Palindromic Substring (Medium) * https://leetcode.com/problems/longest-palindromic-substring/ */ class LongestPalindromicSubstringKt { // T:O(n^2), S:O(1) fun longestPalindrome(s: String): String { // input check, s.length >= 1 if (s.length == 1) return s var res: String = "" var max = 0 // "cbbd" for (i in s.indices) { // odd (e.g. aba) var l = i - 1 var r = i + 1 while (l >= 0 && r < s.length) { if (s[l] != s[r]) break l-- r++ } // l ~ r : Palindrome if (max < r - l - 1) { max = r - l - 1 res = s.substring(l + 1, r) // inclusive ~ exclusive } // even (e.g. aabbaa) l = i - 1 r = i while (l >= 0 && r < s.length) { if (s[l] != s[r]) break l-- r++ } // l ~ r : Palindrome if (max < r - l - 1) { max = r - l - 1 res = s.substring(l + 1, r) // inclusive ~ exclusive } } return res } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,065
playground
MIT License
src/Day01.kt
Sagolbah
573,032,320
false
{"Kotlin": 14528}
import kotlin.math.max fun main() { fun part1(input: List<String>): Long { var ans: Long = -1 var curr: Long = 0 for (line in input) { if (line.isEmpty()) { ans = max(ans, curr) curr = 0 } else { curr += line.toLong() } } ans = max(ans, curr) return ans } fun part2(input: List<String>): Long { val elves = mutableListOf<Long>() var curr: Long = 0 // assume all input is > 0 for (line in input) { if (line.isEmpty()) { elves.add(curr) curr = 0 } else { curr += line.toLong() } } if (curr != 0L) { elves.add(curr) } return elves.sortedDescending().take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
893c1797f3995c14e094b3baca66e23014e37d92
956
advent-of-code-kt
Apache License 2.0
kotlin/src/main/kotlin/com/ximedes/aoc/day04/PassportProcessing.kt
rolfchess
314,041,772
false
null
package com.ximedes.aoc.day04 import com.javamonitor.tools.Stopwatch import com.ximedes.aoc.util.assertTrue import com.ximedes.aoc.util.getClasspathFile // :warning: *Day 4: Toboggan Trajectory* solution thread - here be spoilers! :warning: fun main() { val sw = Stopwatch("Day 4", "load input") val file = getClasspathFile("/input-4.txt") sw.aboutTo("solve part 1") val passports = file.readText().getPassports().filter { it.containsRequiredFields() } println("Day 04 part 1 solution: ${passports.count()}") assertTrue(passports.count() == 192) sw.aboutTo("solve part 2") val validPassports = passports.filter { it.isValidPassport() } println("Day 04 part 2 solution: ${validPassports.size}") assertTrue(validPassports.count() == 101) println(sw.stop().getMessage()) } fun String.getPassports() = split("\n\n").map { it.toPassport() } data class Passport(val fields: Map<String, String>) { fun containsRequiredFields() = fields.keys.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")) fun isValidPassport() = // Fastest assert first fields["byr"]!!.toInt() in 1920..2002 && fields["iyr"]!!.toInt() in 2010..2020 && fields["eyr"]!!.toInt() in 2020..2030 && fields["hcl"]!!.matches("""#[0-9a-f]{6}""".toRegex()) && fields["ecl"]!!.matches("""amb|blu|brn|gry|grn|hzl|oth""".toRegex()) && fields["pid"]!!.matches("""[0-9]{9}""".toRegex()) && validHeight() fun validHeight(): Boolean { val matches = """(\d+)(cm|in)""".toRegex().matchEntire(fields["hgt"]!!) return matches != null && matches.groupValues.isNotEmpty() && when (matches.groupValues[2]) { "cm" -> matches.groupValues[1].toInt() in 150..193 "in" -> matches.groupValues[1].toInt() in 59..96 else -> error("Do not know how to handle ${fields["hgt"]}") } } } fun String.toPassport() = Passport( split("""[\n| ]""".toRegex()) .map { val keyvalue = it.split(":") Pair(keyvalue.first(), keyvalue.last()) }.toMap() )
0
Kotlin
0
0
e666ef0358980656e1c52a3ec08482dd7f86e8a3
2,252
aoc-2020
The Unlicense
src/main/kotlin/g2401_2500/s2407_longest_increasing_subsequence_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2407_longest_increasing_subsequence_ii // #Hard #Array #Dynamic_Programming #Divide_and_Conquer #Queue #Segment_Tree #Binary_Indexed_Tree // #Monotonic_Queue #2023_07_03_Time_518_ms_(100.00%)_Space_56.7_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private class SegTree(private val n: Int) { private val arr: IntArray = IntArray(2 * n) fun query(l: Int, r: Int): Int { var l = l var r = r l += n r += n var ans = 0 while (l < r) { if (l and 1 == 1) { ans = ans.coerceAtLeast(arr[l]) l += 1 } if (r and 1 == 1) { r -= 1 ans = ans.coerceAtLeast(arr[r]) } l = l shr 1 r = r shr 1 } return ans } fun update(i: Int, `val`: Int) { var i = i i += n arr[i] = `val` while (i > 0) { i = i shr 1 arr[i] = arr[2 * i].coerceAtLeast(arr[2 * i + 1]) } } } fun lengthOfLIS(nums: IntArray, k: Int): Int { var max = 0 for (n in nums) { max = max.coerceAtLeast(n) } val seg = SegTree(max) var ans = 0 var i = 0 while (i < nums.size) { var n = nums[i] n -= 1 val temp = seg.query(0.coerceAtLeast(n - k), n) + 1 ans = ans.coerceAtLeast(temp) seg.update(n, temp) i++ } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,676
LeetCode-in-Kotlin
MIT License
src/shmp/simulation/culture/group/centers/RelationCenter.kt
ShMPMat
212,499,539
false
null
package shmp.simulation.culture.group.centers import shmp.utils.getTruncated import shmp.simulation.culture.group.GroupConglomerate import shmp.simulation.culture.group.GroupError import shmp.simulation.culture.group.intergroup.Relation import shmp.simulation.space.tile.Tile import shmp.simulation.space.tile.getDistance import java.util.* import kotlin.math.max class RelationCenter(internal val hostilityCalculator: (Relation) -> Double) { private val relationsMap: MutableMap<Group, Relation> = HashMap() private val evaluationFactor = 10_000 val relatedGroups: Set<Group> get() = relationsMap.keys val relations: Collection<Relation> get() = relationsMap.values fun getConglomerateGroups(conglomerate: GroupConglomerate) = relations.filter { it.other.parentGroup == conglomerate } fun getAvgConglomerateRelation(conglomerate: GroupConglomerate): Double { val result = max( getConglomerateGroups(conglomerate).map { it.normalized }.average(), 0.0000001 ) return if (result.isNaN()) 1.0 else result } fun getMinConglomerateRelation(conglomerate: GroupConglomerate) = getConglomerateGroups(conglomerate).map { it.normalized }.min() ?: 1.0 fun getMaxConglomerateRelation(conglomerate: GroupConglomerate) = getConglomerateGroups(conglomerate).map { it.normalized }.max() ?: 1.0 fun getNormalizedRelation(group: Group) = relationsMap[group]?.normalized ?: 0.5 fun getRelation(group: Group) = relationsMap[group] fun evaluateTile(tile: Tile) = relations.map { (it.positive * evaluationFactor / getDistance(tile, it.other.territoryCenter.center)).toInt() }.fold(0, Int::plus) internal fun updateRelations(groups: Collection<Group>, owner: Group) { updateNewConnections(groups, owner) updateRelations() } private fun updateNewConnections(groups: Collection<Group>, owner: Group) { if (relations.map { it.owner }.any { it != owner }) throw GroupError("Incoherent owner for relations") for (group in groups) if (!relationsMap.containsKey(group)) { val relation = Relation(owner, group) relation.pair = group.relationCenter.addMirrorRelation(relation) relationsMap[relation.other] = relation } } private fun updateRelations() { val dead: MutableList<Group> = ArrayList() for (relation in relationsMap.values) { if (relation.other.state == Group.State.Dead) dead.add(relation.other) else relation.positive = hostilityCalculator(relation) } dead.forEach { relationsMap.remove(it) } } private fun addMirrorRelation(relation: Relation): Relation { val newRelation = Relation(relation.other, relation.owner) newRelation.pair = relation relationsMap[relation.owner] = newRelation return newRelation } override fun toString() = relations .map { it.other.parentGroup } .distinct() .joinToString("\n") { "${it.name} average - ${getTruncated(getAvgConglomerateRelation(it), 4)}, " + "min - ${getTruncated(getMinConglomerateRelation(it), 4)}, " + "max - ${getTruncated(getMaxConglomerateRelation(it), 4)}\n" } }
0
Kotlin
0
0
9fc6faafa1dbd9737dac71dc8a77960accdae81f
3,472
CulturesSim
MIT License
src/codility/NumberOfDiscIntersections.kt
faniabdullah
382,893,751
false
null
package codility /* We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J]. We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders). The figure below shows discs drawn for N = 6 and A as follows: A[0] = 1 A[1] = 5 A[2] = 2 A[3] = 1 A[4] = 4 A[5] = 0 There are eleven (unordered) pairs of discs that intersect, namely: discs 1 and 4 intersect, and both intersect with all the other discs; disc 2 also intersects with discs 0 and 3. Write a function: class Solution { public int solution(int[] A); } that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000. Given array A shown above, the function should return 11, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [0..2,147,483,647]. */ import kotlin.math.abs class NumberOfDiscIntersections { fun solution(A: IntArray): Int { val n = A.size val starts = IntArray(n + 1) val ends = IntArray(n + 1) for (i in 0 until n) { val discRadius = abs(A[i]) val indexOfBeginning = i.toLong() - discRadius.toLong() starts[(if (indexOfBeginning < 0) 0 else indexOfBeginning).toInt()]++ val indexOfEnd: Long = i.toLong() + discRadius.toLong() val result = if (indexOfEnd > n) n else indexOfEnd ends[result.toString().toInt()]++ } var numberOfIntersections = 0 var numberOfActiveCircles = 0 for (i in 0 until n + 1) { val numberOfNewCircles = starts[i] if (numberOfNewCircles > 0) { numberOfIntersections += (numberOfActiveCircles * numberOfNewCircles + (numberOfNewCircles - 1) * numberOfNewCircles / 2) numberOfActiveCircles += numberOfNewCircles if (numberOfIntersections > 10000000) { return -1 } } if (ends[i] > 0) { numberOfActiveCircles -= ends[i] } } return numberOfIntersections } }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,570
dsa-kotlin
MIT License
LR6/src/main/kotlin/Task2V1.kt
Kirchberg
602,987,232
false
null
// Списки (стеки, очереди) I(1..n) и U(1..n) содержат результаты n измерений тока и напряжения на неизвестном // сопротивлении R. Найти приближенное число R методом наименьших квадратов. import kotlin.math.pow // Create a class LeastSquaresR that takes two lists of measurements, currents, and voltages class LeastSquaresR(private val currents: List<Double>, private val voltages: List<Double>) { // Check if the input lists have the same size init { require(currents.size == voltages.size) { "Currents and voltages lists must have the same size" } } // Implement a method that calculates the least squares approximation of R based on the input data fun calculateR(): Double { // Calculate the sum of the product of each current and voltage measurement val sumIU = currents.zip(voltages) { i, u -> i * u }.sum() // Calculate the sum of the square of each current measurement val sumISquared = currents.map { it.pow(2) }.sum() // Calculate the number of measurements val n = currents.size // Calculate the approximate value of the unknown resistance R using the least squares method val r = sumIU / sumISquared return r } } fun task2V1() { // Provide sample data: two lists of current and voltage measurements val currents = listOf(0.5, 1.0, 1.5, 2.0, 2.5) val voltages = listOf(1.0, 2.1, 3.1, 4.1, 5.0) // Create a LeastSquaresR object with the sample data val leastSquaresR = LeastSquaresR(currents, voltages) // Calculate the approximate value of the unknown resistance R val r = leastSquaresR.calculateR() // Print the result println("The approximate value of the unknown resistance R is: $r Ω") }
0
Kotlin
0
0
b6a459a30ef20b0f38c4869d0949e22f4239183e
1,888
BigDataPL
MIT License
src/main/kotlin/com/colinodell/advent2023/Day06.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day06(private val input: List<String>) { private fun countWaysToWin(time: Long, recordDistance: Long) = 0.rangeTo(time) .takeWhile { holdTime -> ((time - holdTime) * holdTime) <= recordDistance } .count() .let { time - (it * 2) + 1 } fun solvePart1() = run { val times = input.first().split(":").last().trim().split(Regex("""\s+""")).map { it.toLong() } val recordDistances = input.last().split(":").last().trim().split(Regex("""\s+""")).map { it.toLong() } times .zip(recordDistances) .productOf { countWaysToWin(it.first, it.second) } } fun solvePart2() = run { val time = input.first().replace(" ", "").split(":").last().toLong() val recordDistance = input.last().replace(" ", "").split(":").last().toLong() countWaysToWin(time, recordDistance) } }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
913
advent-2023
MIT License
app/src/test/java/com/terencepeh/leetcodepractice/IntersectionArrays.kt
tieren1
560,012,707
false
{"Kotlin": 26346}
package com.terencepeh.leetcodepractice fun intersection(nums1: IntArray, nums2: IntArray): IntArray { return nums1.intersect(nums2.toHashSet()).toIntArray() } fun intersection2(nums1: IntArray, nums2: IntArray): IntArray { val set1 = nums1.toHashSet() val set2 = nums2.toHashSet() return if (set1.size > set2.size) { setIntersection(set1, set2) } else { setIntersection(set2, set1) } } fun setIntersection(set1: HashSet<Int>, set2: HashSet<Int>): IntArray { val output = mutableListOf<Int>() set2.forEach { s -> if (set1.contains(s)) { output.add(s) } } return output.toIntArray() } fun main() { val nums1 = intArrayOf(4, 9, 5, 1) val nums2 = intArrayOf(9, 4, 9, 8, 4) println("intersection: ${intersection(nums1, nums2).contentToString()}") println("intersection: ${intersection2(nums1, nums2).contentToString()}") }
0
Kotlin
0
0
427fa2855c01fbc1e85a840d0be381cbb4eec858
927
LeetCodePractice
MIT License
src/day13/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
package day13 import java.io.File import kotlin.math.abs fun main() { val input = File("src/day13/input.txt").readText() val coords = Regex("([0-9]*),([0-9]*)").findAll(input) .map { Pair(it.groupValues[1].toInt(), it.groupValues[2].toInt()) } .toSet() val folds = Regex("fold along ([xy])=([0-9]*)").findAll(input) .map { Pair(it.groupValues[1], it.groupValues[2].toInt()) } .toList() println(coords.map { p -> p.fold(folds[0]) }.toSet().size) folds.fold(coords) { c, f -> c.map { p -> p.fold(f) }.toSet() }.output() } fun Pair<Int, Int>.fold(fold: Pair<String, Int>) = Pair( if (fold.first == "x") fold.second - abs(first - fold.second) else first, if (fold.first == "y") fold.second - abs(second - fold.second) else second ) fun Set<Pair<Int, Int>>.output() { (0..maxOf { it.second }).forEach { y -> (0..maxOf { it.first }).forEach { x -> print(if (contains(Pair(x, y))) "#" else ".") } println() } println() }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
1,027
advent-of-code-2021
MIT License
src/main/kotlin/algorithms/sorting/quick_sort/QuickSort.kt
AANikolaev
273,465,105
false
{"Java": 179737, "Kotlin": 13961}
package algorithms.sorting.quick_sort import algorithms.sorting.InplaceSort class QuickSort : InplaceSort { override fun sort(values: IntArray) { quickSort(values) } private fun quickSort(ar: IntArray?) { if (ar == null) return quickSort(ar, 0, ar.size - 1) } // Sort interval [lo, hi] inplace recursively private fun quickSort(ar: IntArray, lo: Int, hi: Int) { if (lo < hi) { val splitPoint: Int = partition(ar, lo, hi) quickSort(ar, lo, splitPoint) quickSort(ar, splitPoint + 1, hi) } } // Performs Hoare partition algorithm for quicksort private fun partition(ar: IntArray, lo: Int, hi: Int): Int { val pivot = ar[lo] var i = lo - 1 var j = hi + 1 while (true) { do { i++ } while (ar[i] < pivot) do { j-- } while (ar[j] > pivot) if (i < j) swap(ar, i, j) else return j } } // Swap two elements private fun swap(ar: IntArray, i: Int, j: Int) { val tmp = ar[i] ar[i] = ar[j] ar[j] = tmp } }
0
Java
0
0
f9f0a14a5c450bd9efb712b28c95df9a0d7d589b
1,182
Algorithms
MIT License
src/main/kotlin/aoc05/Solution05.kt
rainer-gepardec
573,386,353
false
{"Kotlin": 13070}
package aoc05 import java.nio.file.Paths /* [D] [N] [C] [Z] [M] [P] 1 2 3 [J] [Z] [G] [Z] [T] [S] [P] [R] [R] [Q] [V] [B] [G] [J] [W] [W] [N] [L] [V] [W] [C] [F] [Q] [T] [G] [C] [T] [T] [W] [H] [D] [W] [W] [H] [T] [R] [M] [B] [T] [G] [T] [R] [B] [P] [B] [G] [G] [S] [S] [B] [D] [F] [L] [Z] [N] [L] 1 2 3 4 5 6 7 8 9 */ fun createStorage(): Map<Int, ArrayDeque<String>> { val storage = mutableMapOf<Int, ArrayDeque<String>>() storage[1] = ArrayDeque(listOf("S", "T","H","F","W","R")) storage[2] = ArrayDeque(listOf("S", "G", "D","Q","W")) storage[3] = ArrayDeque(listOf("B","T","W")) storage[4] = ArrayDeque(listOf("D","R","W","T","N","Q","Z","J")) storage[5] = ArrayDeque(listOf("F","B","H","G","L","V","T","Z")) storage[6] = ArrayDeque(listOf("L","P","T","C","V","B","S","G")) storage[7] = ArrayDeque(listOf("Z","B","R","T","W","G","P")) storage[8] = ArrayDeque(listOf("N","G","M","T","C","J","R")) storage[9] = ArrayDeque(listOf("L","G","B","W")) return storage } fun main() { val lines = Paths.get("src/main/resources/aoc_05.txt").toFile().useLines { it.toList() } val operations = lines.map { it.split(" ") } .map { tokens -> tokens.map { token -> token.toIntOrNull() }.mapNotNull { it } } .map { Triple(it[0], it[1], it[2]) } println(solution1(createStorage(), operations)) println(solution2(createStorage(), operations)) } fun solution1(storage: Map<Int, ArrayDeque<String>>, operations: List<Triple<Int, Int, Int>>): String { operations.forEach { for (i in 0 until it.first) storage[it.third]!!.addLast(storage[it.second]!!.removeLast()) } return storage.map {it.value.removeLast() }.joinToString(separator = "") } fun solution2(storage: Map<Int, ArrayDeque<String>>, operations: List<Triple<Int, Int, Int>>): String { operations.forEach { movement -> val tmpDeque = ArrayDeque<String>(); for (i in 0 until movement.first) { tmpDeque.addFirst(storage[movement.second]!!.removeLast()); } tmpDeque.forEach { storage[movement.third]!!.addLast(it) } } return storage.map {it.value.removeLast() }.joinToString(separator = "") }
0
Kotlin
0
0
c920692d23e8c414a996e8c1f5faeee07d0f18f2
2,324
aoc2022
Apache License 2.0
Generics/Generic functions/src/Task.kt
margalis
393,934,017
false
null
import java.util.* public fun <T, C : MutableCollection<in T>> Collection<T>.partitionTo(col1: C, col2: C, predicate: (T)-> Boolean): Pair<C,C> { //T-n itemi tesak, C-n` Collectioni mejini //greladzevy` toCollectioni pes for( item in this){ if(predicate(item)){ col1.add(item) } else{ col2.add(item) } } return Pair(col1,col2) // qanzi partition()-y sl-um pair er veradardznum } fun partitionWordsAndLines() { val (words, lines) = listOf("a", "a b", "c", "d e") .partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } check(words == listOf("a", "c")) check(lines == listOf("a b", "d e")) } fun partitionLettersAndOtherSymbols() { val (letters, other) = setOf('a', '%', 'r', '}') .partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' } check(letters == setOf('a', 'r')) check(other == setOf('%', '}')) }
0
Kotlin
0
0
faf2034dcc4e0c90cd39b6c059de7aae4faade73
957
Kotlin_Koans_mg
MIT License
kotlin/2020/round-1b/expogo/src/main/kotlin/bfs/Solution.kt
ShreckYe
345,946,821
false
null
package bfs fun main() { val T = readLine()!!.toInt() repeat(T) { t -> val (X, Y) = readLine()!!.splitToSequence(' ').map(String::toInt).toList() val zero = Point(0, 0) val goal = Point(X, Y) val bfsPoints = bfsPointsWithin(sequenceOf(zero to emptySequence()), 0, 9) val jumps = bfsPoints.firstOrNull { it.first == goal && it.second.any() }?.run { second.joinToString("") } println("Case #${t + 1}: ${jumps ?: "IMPOSSIBLE"}") } } data class Point(val x: Int, val y: Int) typealias History = Sequence<Char> typealias PointWithHis = Pair<Point, History> fun bfsPointsWithin(from: Sequence<PointWithHis>, i: Int, nSteps: Int): Sequence<PointWithHis> = if (nSteps == 0) from else bfsPointsWithin(from + from.flatMap { nextPointsFrom( it.first, i, it.second ) }, i + 1, nSteps - 1) // i means i + 1 here fun nextPointsFrom(from: Point, i: Int, history: Sequence<Char>): Sequence<PointWithHis> { val (x, y) = from val jump = 1 shl i return directions.map { when (it) { 'N' -> Point(x, y + jump) 'S' -> Point(x, y - jump) 'E' -> Point(x + jump, y) 'W' -> Point(x - jump, y) else -> throw AssertionError() } to history + it } } val directions = sequenceOf('N', 'S', 'E', 'W')
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
1,389
google-code-jam
MIT License
src/main/kotlin/wtf/log/xmas2021/day/day05/Day05.kt
damianw
434,043,459
false
{"Kotlin": 62890}
package wtf.log.xmas2021.day.day05 import com.google.common.collect.HashMultiset import com.google.common.collect.Multiset import wtf.log.xmas2021.Day import wtf.log.xmas2021.util.math.Line import wtf.log.xmas2021.util.math.Point import wtf.log.xmas2021.util.math.points import java.io.BufferedReader object Day05 : Day<List<Line>, Int, Int> { private val REGEX = Regex("""(\d+),(\d+) -> (\d+),(\d+)""") override fun parseInput(reader: BufferedReader): List<Line> = reader .lineSequence() .map { line -> val (x1, y1, x2, y2) = requireNotNull(REGEX.matchEntire(line)).destructured Line( start = Point(x1.toInt(), y1.toInt()), end = Point(x2.toInt(), y2.toInt()), ) } .toList() override fun part1(input: List<Line>): Int { return solve(input) { it.isVertical || it.isHorizontal } } override fun part2(input: List<Line>): Int { return solve(input) { true } } private inline fun solve(input: List<Line>, predicate: (Line) -> Boolean): Int { val pointCounts: Multiset<Point> = HashMultiset.create() for (line in input) { if (predicate(line)) { pointCounts.addAll(line.points.asIterable()) } } val dangerousPoints = pointCounts .entrySet() .filter { it.count >= 2 } .map { it.element } return dangerousPoints.size } }
0
Kotlin
0
0
1c4c12546ea3de0e7298c2771dc93e578f11a9c6
1,483
AdventOfKotlin2021
BSD Source Code Attribution
leetcode/src/array/Q73.kt
zhangweizhe
387,808,774
false
null
package array fun main() { // 73. 矩阵置零 // https://leetcode-cn.com/problems/set-matrix-zeroes/ val mat = Array<IntArray>(3) { when(it) { // 0 -> intArrayOf(0,1,2,0) // 1 -> intArrayOf(3,4,5,2) // 2 -> intArrayOf(1,3,1,5) // else -> intArrayOf() 0 -> intArrayOf(0) 1 -> intArrayOf(0) 2 -> intArrayOf(1) else -> intArrayOf() } } setZeroes1(mat) for (m in mat) { println(m.contentToString()) } } fun setZeroes(matrix: Array<IntArray>): Unit { val xy = ArrayList<Pair<Int, Int>>() for (row in matrix.indices) { for (col in matrix[row].indices) { if (matrix[row][col] == 0) { xy.add(Pair(row, col)) } } } val rCount = matrix.size val cCount = matrix[0].size for (pair in xy) { for (x in 1..rCount) { matrix[x-1][pair.second] = 0 } for (y in 1..cCount) { matrix[pair.first][y-1] = 0 } } } /** * 用第一行和第一列作为标记数组 */ fun setZeroes1(matrix: Array<IntArray>): Unit { var col0Flag = false var row0Flag = false val rCount = matrix.size //3 val cCount = matrix[0].size //4 for (x in 0 until rCount) { if (matrix[x][0] == 0) { col0Flag = true break } } for (y in 0 until cCount) { if (matrix[0][y] == 0) { row0Flag = true break } } for (x in 0 until rCount) { for (y in 0 until cCount) { if (matrix[x][y] == 0) { matrix[x][0] = 0 matrix[0][y] = 0 } } } for (x in 1 until rCount) { for (y in 1 until cCount) { if (matrix[0][y] == 0) { matrix[x][y] = 0 } if (matrix[x][0] == 0) { matrix[x][y] = 0 } } } if (row0Flag) { for (y in 0 until cCount) { matrix[0][y] = 0 } } if (col0Flag) { for (x in 0 until rCount) { matrix[x][0] = 0 } } }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
2,220
kotlin-study
MIT License
grokking-algorithms/06 - Breadth-first Search/01_BFS_Person.kt
arturschaefer
427,090,600
false
{"C": 48055, "Kotlin": 24446, "C++": 16696, "Dart": 3630, "QMake": 168}
import java.util.Deque import java.util.LinkedList import kotlin.collections.last fun main() { val valuesList = listOf( Person("you") to listOf(Person("alice"), Person("bob"), Person("claire")), Person("bob") to listOf(Person("anuj"), Person("peggy")), Person("alice") to listOf(Person("peggy")), Person("claire") to listOf(Person("thom", true), Person("jonny")), Person("anuj") to emptyList(), Person("peggy") to emptyList(), Person("thom", true) to emptyList(), Person("jonny") to emptyList(), ) val graph = Graph<Person>(valuesList) val result = graph.breadthFirstSearch(Person("you"), Person::isMangoSeller) result?.let { println("${it.last().name} is a Mango Seller") println("Searched graph -> ${result.toString()}") } ?: println("There is no Mango seller") } data class Person(val name: String, val isMangoSeller: Boolean = false) { override fun equals(other: Any?): Boolean = if (other is Person) other.name == name else false } class Graph<V>(val values: List<Pair<V, List<V>>>){ // O(V+E) (V for number of vertices, E for number of edges) fun breadthFirstSearch(key: V, searchFunction: (V) -> Boolean): List<V>?{ val graph = hashMapOf<V, List<V>>() graph.putAll(values) var searchQueue: Deque<V> = LinkedList() graph[key]?.let { searchQueue += it } val searched = LinkedHashSet<V>() while (searchQueue.isNotEmpty()){ val current = searchQueue.pop() if (!searched.contains(current)){ if (searchFunction(current)){ searched.add(current) return searched.toList() } else { graph[current]?.let { searchQueue += it } searched.add(current) } } } return null } }
0
C
0
0
04c34298739cab13b5cd755b4c6786fc1fe236cd
1,999
computer-science-studies
Apache License 2.0
src/main/kotlin/me/grison/aoc/Extensions.kt
agrison
315,292,447
false
{"Kotlin": 267552}
/** * This file contains useful Kotlin extensions to deal with * various problems that we need to solve during Advent Of Code * * Including String, Ints, Longs, Iterable & Collections, Ranges, Pairs, Complex, ... * * These extensions are used in all the different years solutions. */ package me.grison.aoc import space.kscience.kmath.complex.Complex import util.CYAN import util.RESET import java.lang.Integer.max import java.lang.Integer.min import java.math.BigInteger import kotlin.math.abs import kotlin.math.absoluteValue import kotlin.math.ceil // core types // Strings /* 219 398 -> {(0,0)=2, (0,1)=1, (0,2)=9 (1,0)=3, (1,1)=9, (1,2)=8} */ typealias Grid<T> = MutableMap<Position, T> fun List<String>.intGrid(default: Int, size: Int): Grid<Int> { val grid = HashMap<Position, Int>(size).withDefault { default } var height = 0 forEach { line -> var width = 0 line.normalSplit("").ints().forEach { n -> grid[p(height, width++)] = n } height++ } return grid } fun List<String>.intGrid(default: Int): Grid<Int> { val grid = mutableMapOf<Position, Int>().withDefault { default } var height = 0 forEach { line -> var width = 0 line.normalSplit("").ints().forEach { n -> grid[p(height, width++)] = n } height++ } return grid } fun List<String>.stringGrid(default: String): Grid<String> { val grid = mutableMapOf<Position, String>().withDefault { default } var height = 0 forEach { line -> var width = 0 line.normalSplit("").forEach { n -> grid[p(height, width++)] = n } height++ } return grid } fun <T> MutableList<T>.append(t: T): MutableList<T> { this.add(t) return this } // Integers & Long /** Returns whether this is divisible by `other`. */ fun Int.divisible(other: Int) = this % other == 0 /** Returns whether this is in the given range. */ fun Int.`in`(i: IntRange) = (i.first..(i.last + 1)).contains(this) /** Returns whether this is divisible by `other`. */ fun Long.divisible(other: Long) = this % other == 0L fun Int.odd() = this % 2 == 1 fun Int.even() = this % 2 == 0 fun Int.zero() = this == 0 fun Int.pos() = this >= 0 fun Int.neg() = this < 0 // Complex /** Returns the manhattan distance of this Complex. */ fun Complex.manhattan() = (abs(this.re) + abs(this.im)).toInt() val Double.j: Complex get() = Complex(0, this) val Int.j: Complex get() = Complex(0, this) val Double.r: Complex get() = Complex(this, 0) val Int.r: Complex get() = Complex(this, 0) operator fun Complex.times(c: Complex) = Complex(this.re * c.re - this.im * c.im, this.re * c.im + this.im * c.re) operator fun Complex.plus(c: Complex) = Complex(this.re + c.re, this.im + c.im) // Booleans /** Returns `1` if `true`, `0` otherwise. */ fun Boolean.toInt() = if (this) 1 else 0 /** Returns `1` if `true`, `0` otherwise. */ fun Boolean.toLong() = if (this) 1L else 0L fun Int.sign() = kotlin.math.sign(this.toDouble()).toInt() // Characters /** `+` operator for characters. */ operator fun Char.plus(c: Char) = toString() + c /** Returns whether this equals `c`. */ fun Char.eq(c: Char) = this == c //Ranges /** Returns whether this range includes all the given `ints`. */ fun IntRange.includes(vararg ints: Int) = ints.all(this::contains) // Sequence fun <T : Any> cycle(vararg xs: T): Sequence<T> { var i = 0 return generateSequence { xs[i++ % xs.size] } } fun <T : Any> cycle(xs: List<T>): Sequence<T> { var i = 0 return generateSequence { xs[i++ % xs.size] } } // Pairs /** Difference between an ordered Pair. */ fun Pair<Int, Int>.difference() = second - first /** Whether the difference between an ordered Pair is `i`. */ fun Pair<Int, Int>.differenceIs(i: Int) = difference() == i /** Difference between an ordered Pair. */ fun Pair<Long, Long>.difference() = (second - first).absoluteValue /** Whether the difference between an ordered Pair is `i`. */ fun Pair<Long, Long>.differenceIs(i: Long) = difference() == i /** Returns the sum of the elements in this Pair. */ fun Pair<Int, Int>.sum() = first + second /** Returns the product of the elements in this Pair. */ fun Pair<Int, Int>.multiply() = first * second /** Returns the product of the elements in this Pair. */ fun Pair<Int, Int>.product() = first * second /** `+` operator for Pairs. */ operator fun Pair<Int, Int>.plus(p: Pair<Int, Int>): Pair<Int, Int> = Pair(first + p.first, second + p.second) //operator fun Pair<Long, Long>.plus(p: Pair<Long, Long>): Pair<Long, Long> = Pair(first + p.first, second + p.second) fun Pair<Int, Int>.plus(a: Int, b: Int): Pair<Int, Int> = Pair(first + a, second + b) /** `-` operator for Pairs. */ operator fun Pair<Int, Int>.minus(p: Pair<Int, Int>): Pair<Int, Int> = Pair(first - p.first, second - p.second) /** `*` operator for Pairs. */ operator fun Pair<Int, Int>.times(p: Pair<Int, Int>): Pair<Int, Int> = Pair(first * p.first, second * p.second)/** `*` operator for Pairs. */ //operator fun Pair<Long, Long>.times(p: Pair<Long, Long>): Pair<Long, Long> = Pair(first * p.first, second * p.second) fun bools() = mutableListOf<Boolean>() fun ints() = mutableListOf<Int>() fun directions() = listOf(p(-1, 0), p(1, 0), p(0, -1), p(0, 1)) fun Pair<Int, Int>.above() = this.plus(p(0, -1)) fun Pair<Int, Int>.below() = this.plus(p(0, 1)) fun Pair<Int, Int>.left() = this.plus(p(-1, 0)) fun Pair<Int, Int>.right() = this.plus(p(1, 0)) fun Pair<Int, Int>.up(i: Int) = this.plus(p(0, -i)) fun Pair<Int, Int>.down(i: Int) = this.plus(p(0, i)) fun Pair<Int, Int>.forward(i: Int) = this.plus(p(i, 0)) fun Pair<Int, Int>.forward(i: Int, aim: Int) = this.plus(p(i, aim)) fun Pair<Int, Int>.backward(i: Int) = this.plus(p(-i, 0)) fun Pair<Int, Int>.within(minx: Int, miny: Int, maxx: Int, maxy: Int) = first in minx..maxx && second in miny..maxy fun Pair<Int, Int>.directions() = listOf(above(), below(), left(), right()) fun Pair<Int, Int>.neighbors(self: Boolean = false): List<Position> { val neighbors = listOf( plus(-1, -1), plus(-1, 0), plus(-1, 1), plus(0, -1), this, plus(0, 1), plus(1, -1), plus(1, 0), plus(1, 1) ) return if (self) neighbors else neighbors.reject { it == this } } fun Pair<Int, Int>.abs() = p(abs(first), abs(second)) fun Pair<Int, Int>.max() = kotlin.math.max(first, second) fun Pair<Int, Int>.min() = kotlin.math.min(first, second) fun <T, U> Pair<T, U>.first(t: T) = p(t, second) fun <T, U> Pair<T, U>.second(u: U) = p(first, u) fun movements() = mapOf("R" to p(0, 1), "L" to p(0, -1), "D" to p(1, 0), "U" to p(-1, 0)) // return an increasing range fun Pair<Int, Int>.range() = min(first, second)..max(first, second) // compute the slope of a pair representing two X or two Y (derivative) fun Pair<Int, Int>.slope() = when { first == second -> 0 first > second -> -1 else -> 1 } fun Pair<Int, Int>.pivotSecond(loc: Int) = if (second < loc) this else p(first, loc - (second - loc)) fun Pair<Int, Int>.pivotFirst(loc: Int) = if (first < loc) this else p(loc - (first - loc), second) fun Pair<Long, Long>.pivotSecond(loc: Long) = if (second < loc) this else Pair(first, loc - (second - loc)) fun Pair<Long, Long>.pivotFirst(loc: Long) = if (first < loc) this else Pair(loc - (first - loc), second) fun Triple<Int, Int, Int>.sum() = first + second + third fun Triple<Long, Long, Long>.sum() = first + second + third // works with MutableMap.withDefault() fun <T> MutableMap<T, Int>.increase(key: T, amount: Int = 1): MutableMap<T, Int> { this[key] = this.getOrDefault(key, 0) + amount return this } fun <T> MutableMap<T, Long>.increase(key: T, amount: Long = 1L): MutableMap<T, Long> { this[key] = this.getOrDefault(key, 0L) + amount return this } fun <T> MutableMap<T, BigInteger>.increase(key: T, amount: BigInteger = BigInteger.ONE): MutableMap<T, BigInteger> { this[key] = this.getOrDefault(key, BigInteger.ZERO).add(amount) return this } fun <T> List<T>.copy() = this.toMutableList() fun <T> List<T>.update(i: Int, value: T): List<T> { val copy = this.toMutableList() copy[i] = value return copy } fun <T> List<T>.combinations(k: Int) = io.vavr.collection.Vector.ofAll(this) .combinations(k).map { it.toJavaList() as List<T> }.toJavaList() as List<List<T>> fun <T> List<T>.uniqueCombinations(k: Int) = this.combinations(k).toSet() fun combinations2(lo: Int, hi: Int) = sequence { for (i in lo..hi) for (j in lo..hi) yield(Pair(i, j)) } fun combinations3(lo: Int, hi: Int) = sequence { for (i in lo..hi) for (j in lo..hi) for (k in lo..hi) yield(Triple(i, j, k)) } /** Returns the sum of the elements in this Pair. */ fun Pair<Long, Long>.sum() = first + second /** Returns the product of the elements in this Pair. */ fun Pair<Long, Long>.multiply() = first * second /** Shortcut for creating a Pair. */ fun <T, U> p(t: T, u: U): Pair<T, U> = Pair(t, u) fun pd(t: Double, u: Double): Pair<Double, Double> = Pair(t, u) /** Returns the manhattan distance for this Pair. */ fun Pair<Int, Int>.manhattan() = first.absoluteValue + second.absoluteValue /** Swap a Pair. */ fun <T, U> Pair<T, U>.swap() = p(second, first) fun Pair<Double, Double>.distance() = ceil(abs(first) + kotlin.math.max(0.0, abs(second) - abs(first) / 2)) // ArrowKt fun arrow.core.Tuple2<Int, Int>.sum(): Int = a + b fun arrow.core.Tuple2<Int, Int>.mul(): Int = a * b fun arrow.core.Tuple3<Int, Int, Int>.sum(): Int = a + b + c fun arrow.core.Tuple3<Int, Int, Int>.mul(): Int = a * b * c class Memoize1<in T, out R>(val f: (T) -> R) : (T) -> R { private val values = mutableMapOf<T, R>() override fun invoke(x: T): R { return values.getOrPut(x, { f(x) }) } } fun <T, R> ((T) -> R).memoize(): (T) -> R = Memoize1(this) fun <T> List<List<T>>.swapRowCols() = flatMap { it.withIndex() } .groupBy({ (i, _) -> i }, { (_, v) -> v }) .map { (_, v) -> v.reversed() } fun List<List<List<Boolean>>>.flattenGrid() = flatMap { it.mapIndexed { i, list -> IndexedValue(i, list) } } .groupBy({ (i, _) -> i }, { (_, v) -> v }) .map { (_, v) -> v.reduce { acc, list -> acc + list } } fun intSeq() = generateSequence(1) { it + 1 } fun intSeq(x: Int) = generateSequence(x) { it + 1 } typealias HashBag<T> = MutableMap<T, Int> fun <T> hashBag() = mutableMapOf<T, Int>().withDefault { 0 } typealias LongHashBag<T> = MutableMap<T, Int> fun <T> longHashBag() = mutableMapOf<T, Long>().withDefault { 0L } fun <T> bigIntHashBag() = mutableMapOf<T, BigInteger>().withDefault { BigInteger.ZERO } typealias Position = Pair<Int, Int> typealias LPosition = Pair<Long, Long> fun Position.manhattan(other: Position) = abs(first - other.first) + abs(second - other.second) fun LPosition.manhattan(other: LPosition) = abs(first - other.first) + abs(second - other.second) fun <T> makeList(size: Int, t: T): MutableList<T> { val list = mutableListOf<T>() for (i in 0.until(size)) { list.add(t) } return list } fun Iterable<Int>.sumLong(): Long = this.fold(0L, Long::plus) fun Array<Long>.increase(i: Int, amount: Long = 1): Array<Long> { this[i] += amount return this } fun gridPositions(dimensions: Pair<Int, Int>) = gridPositions(dimensions.first, dimensions.second) fun gridPositions(height: Int, width: Int) = (0.until(height)).flatMap { y -> (0.until(width)).map { x -> p(y, x) } } fun Iterable<Position>.pointsDisplay(empty: String = " "): String { val (maxX, maxY) = p(maxOf { it.first }, maxOf { it.second }) val display = arrayListOf<List<String>>() for (y in 0..maxY) { display.add((0..maxX).map { x -> if (p(x, y) in this) "$CYAN#$RESET" else empty }) } return display.joinToString("\n") { it.joinToString("") } } //fun Iterable<Pair<Long, Long>>.pointsDisplay(empty: String = " "): String { // val (maxX, maxY) = p(maxOf { it.first }, maxOf { it.second }) // val display = arrayListOf<List<String>>() // for (y in 0..maxY) { // display.add((0..maxX).map { x -> if (p(x, y) in this) "$CYAN#$RESET" else empty }) // } // return display.joinToString("\n") { it.joinToString("") } //} fun Collection<Int>.toRange() = IntRange(this.first(), this.last()) fun Collection<Long>.toRange() = LongRange(this.first(), this.last()) fun Pair<Int, Int>.toRange() = IntRange(this.first, this.second) fun Pair<Long, Long>.toRange() = LongRange(this.first, this.second) operator fun IntRange.contains(range: IntRange) = this.first <= range.first && this.last >= range.last fun IntRange.overlap(range: IntRange) = range.first in this || this.first in range fun Collection<Int>.range() = maxOrNull()!! - minOrNull()!! fun Collection<Long>.range() = maxOrNull()!! - minOrNull()!! fun Collection<BigInteger>.range() = maxOrNull()!!.minus(minOrNull()!!) fun <T> Map<T, Long>.frequency() = longHashBag<T>().let { hash -> this.forEach { (k, v) -> hash.increase(k, v) } hash } fun <T, U> Map<T, Long>.frequency(selector: (T) -> U) = longHashBag<U>().let { hash -> this.forEach { (k, v) -> hash.increase(selector(k), v) } hash } fun <T> Collection<T>.frequency() = bigIntHashBag<T>().let { hash -> this.forEach { c -> hash.increase(c) } hash } fun Int.toBinary(length: Int? = null): String { return if (length == null) this.toString(2) else Integer.toBinaryString((1 shl length) or this).substring(1) } fun Int.padLeft(length: Int, value: Char): String { return this.toString().padStart(length, value) } fun Char.int() = this.toString().toInt() fun <T,U,V> t(t: T, u: U, v: V) = Triple(t, u, v) fun Position.sign() = p(first.sign(), second.sign()) fun Position.x() = first fun Position.y() = second fun List<Int>.min() = minByOrNull { it }!! fun Iterable<Position>.minX() = map {it.first}.min() fun Iterable<Position>.minY() = map {it.second}.min() fun List<Int>.max() = maxByOrNull { it }!! fun Iterable<Position>.maxX() = map {it.first}.max() fun Iterable<Position>.maxY() = map {it.second}.max() fun List<Long>.max() = maxByOrNull { it }!! fun <T> List<T>.peek(index: Int, sideEffect: (T) -> Unit) : List<T> { sideEffect.invoke(this[index]) return this; }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
14,264
advent-of-code
Creative Commons Zero v1.0 Universal
app/src/y2021/day24/Day24.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day24 import common.* import common.annotations.AoCPuzzle import y2021.day24.Variable.* import java.io.File import javax.xml.stream.events.Characters import kotlin.math.roundToInt import kotlin.time.Duration import kotlin.time.ExperimentalTime import kotlin.time.milliseconds fun main(args: Array<String>) { Day24().solveThem(ignoreSamples = true) } @AoCPuzzle(2021, 24) class Day24 : AocSolution { override val answers = Answers(samplePart1 = -1, samplePart2 = -1) // val lower = 11_111_111_111_111 // val upper = 99_999_999_999_999 val lower = 44_444_444_444_444 val upper = 55360782312113 // 44444444444444 is too low // 55393888877939 is too high // 55555555555555 is too high @OptIn(ExperimentalTime::class) override fun solvePart1(input: List<String>): Any { val start = System.currentTimeMillis() var percent = 0.0 File("monad_in_order.csv").appendText("candidate,result\n") for (candidate in (lower..upper).reversed()) { // for (candidate in (lower..upper).step(10000)) { val result = monad(candidate) // if(result != -1) { // println("$candidate;$result") // File("monad_in_order.csv").appendText("$candidate,$result\n") // } if (result == 0) { println("Valid monad found: $candidate") return candidate } val newPercent = ((upper.toDouble() - candidate) / (upper - lower) * 100 * 1000).roundToInt() / 1000.0 if (newPercent != percent) { val passed = Duration.milliseconds(System.currentTimeMillis() - start) println("$newPercent % / time passed: $passed / currently at $candidate") percent = newPercent } } return -100 } override fun solvePart2(input: List<String>): Any { TODO() } } class ALU() { var w: Int = 0 private set var x: Int = 0 private set var y: Int = 0 private set var z: Int = 0 private set // inp a - Read an input value and write it to variable a. fun inp(a: Variable, value: Int) { when (a) { W -> w = value X -> x = value Y -> y = value Z -> z = value } } // add a b - Add the value of a to the value of b, then store the result in variable a. fun add(a: Variable, value: Int) { when (a) { W -> w += value X -> x += value Y -> y += value Z -> z += value } } fun add(a: Variable, b: Variable) { when (b) { W -> add(a, w) X -> add(a, x) Y -> add(a, y) Z -> add(a, z) } } // mul a b - Multiply the value of a by the value of b, then store the result in variable a. fun mul(a: Variable, value: Int) { when (a) { W -> w *= value X -> x *= value Y -> y *= value Z -> z *= value } } fun mul(a: Variable, b: Variable) { when (b) { W -> mul(a, w) X -> mul(a, x) Y -> mul(a, y) Z -> mul(a, z) } } // div a b - Divide the value of a by the value of b, truncate the result to an integer, then store the result in variable a. (Here, "truncate" means to round the value toward zero.) fun div(a: Variable, value: Int) { when (a) { W -> w /= value X -> x /= value Y -> y /= value Z -> z /= value } } fun div(a: Variable, b: Variable) { when (b) { W -> div(a, w) X -> div(a, x) Y -> div(a, y) Z -> div(a, z) } } // mod a b - Divide the value of a by the value of b, then store the remainder in variable a. (This is also called the modulo operation.) fun mod(a: Variable, value: Int) { when (a) { W -> w %= value X -> x %= value Y -> y %= value Z -> z %= value } } fun mod(a: Variable, b: Variable) { when (b) { W -> mod(a, w) X -> mod(a, x) Y -> mod(a, y) Z -> mod(a, z) } } // eql a b - If the value of a and b are equal, then store the value 1 in variable a. Otherwise, store the value 0 in variable a. fun eql(a: Variable, value: Int) { when (a) { W -> w = if (w == value) 1 else 0 X -> x = if (x == value) 1 else 0 Y -> y = if (y == value) 1 else 0 Z -> z = if (z == value) 1 else 0 } } fun eql(a: Variable, b: Variable) { when (b) { W -> eql(a, w) X -> eql(a, x) Y -> eql(a, y) Z -> eql(a, z) } } } enum class Variable { X, Y, Z, W } fun monad(input: Long): Int { val alu = ALU() val digits = input.toString().map(Character::getNumericValue).toMutableList() if (digits.contains(0)) return -1 alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 10) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 15) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 12) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 8) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 15) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 2) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -9) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 6) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 15) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 13) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 10) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 4) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 14) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 1) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -5) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 9) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 1) alu.add(X, 14) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 5) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -7) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 13) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -12) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 9) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -10) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 6) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -1) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 2) alu.mul(Y, X) alu.add(Z, Y) alu.inp(W, digits.removeFirst()) alu.mul(X, 0) alu.add(X, Z) alu.mod(X, 26) alu.div(Z, 26) alu.add(X, -11) alu.eql(X, W) alu.eql(X, 0) alu.mul(Y, 0) alu.add(Y, 25) alu.mul(Y, X) alu.add(Y, 1) alu.mul(Z, Y) alu.mul(Y, 0) alu.add(Y, W) alu.add(Y, 2) alu.mul(Y, X) alu.add(Z, Y) return alu.z }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
10,027
advent-of-code-2021
Apache License 2.0
src/Day02.kt
greeshmaramya
514,310,903
false
{"Kotlin": 8307}
data class Day2( val password: String, val l: Int, val r: Int, val c: Char ) fun main() { fun String.modifyInput(): Day2 { val s = split(':') val s1 = s.first().split(' ') val s2 = s1.first().split('-') return Day2(password = <PASSWORD>(), l = s2.first().toInt(), r = s2[1].toInt(), c = s1.last().last()) } fun part1(data: List<Day2>):Int { var count = 0 data.forEach { db -> val num = db.password.count { it == db.c } if (db.l <= num && num <= db.r) { count++ } } return count } fun part2(data: List<Day2>):Int { var count = 0 data.forEach { if( (it.password[it.l] == it.c) xor (it.password[it.r] == it.c)) count++ } return count } val testInput = readInput("Day02Test").map { it.modifyInput() } val input = readInput("Day02").map { it.modifyInput() } println(part1(testInput)) println(part1(input)) println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
9e1128ee084145f5a70fe3ad4e71b05944260d6e
1,079
aoc2020
Apache License 2.0
src/kotlin2022/Day02.kt
egnbjork
571,981,366
false
{"Kotlin": 18156}
package kotlin2022 import readInput //rock A X //paper B Y //scissors C Z val winningPairs = mapOf( "A" to "Y", "B" to "Z", "C" to "X" ) val loosingPairs = mapOf( "A" to "Z", "B" to "X", "C" to "Y" ) val drawPairs = mapOf( "A" to "X", "B" to "Y", "C" to "Z" ) fun main() { val gameInput = readInput("Day02_test") println(gameInput.sumOf { getRoundScore(it) }) } fun getRoundScore(round: String): Int { val roundPair = Pair(round.split(" ")[0], round.split(" ")[1]) return when (roundPair.second) { "Y" -> drawPairs[roundPair.first]?.let { getItemScore(it) + 3 } "Z" -> winningPairs[roundPair.first]?.let{ getItemScore(it) + 6} else -> loosingPairs[roundPair.first]?.let{ getItemScore(it) } } ?: 0 } fun getItemScore(item: String): Int { return when(item) { "X" -> 1 "Y" -> 2 else -> 3 } }
0
Kotlin
0
0
1294afde171a64b1a2dfad2d30ff495d52f227f5
909
advent-of-code-kotlin
Apache License 2.0
src/test/kotlin/com/igorwojda/string/reverse/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.string.reverse // Kotlin idiomatic way private object Solution1 { private fun reverse(str: String): String { return str.reversed() } } // Iterative approach private object Solution2 { private fun reverse(str: String): String { var reversed = "" str.forEach { reversed = it + reversed } return reversed } } // Recursive approach private object Solution3 { private fun reverse(str: String): String { if (str.isEmpty()) { return str } return reverse(str.drop(1)) + str.first() } } // Kotlin fold private object Solution4 { private fun reverse(str: String): String { return str.foldRight("") { char, reversed -> reversed + char } } } // Time complexity: O(n) // Space complexity: O(1) // Reverse in place private object Solution5 { private fun reverse(str: String): String { val chars = str.toMutableList() var leftIndex = 0 var rightIndex = chars.lastIndex while (leftIndex <= rightIndex) { val temp = chars[leftIndex] chars[leftIndex] = chars[rightIndex] chars[rightIndex] = temp leftIndex++ rightIndex-- } return chars.joinToString(transform = { it.toString() }, separator = "") } }
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
1,358
kotlin-coding-challenges
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day15.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.* import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.api.ndarray import org.jetbrains.kotlinx.multik.ndarray.data.D2Array import org.jetbrains.kotlinx.multik.ndarray.data.get open class Part15A : PartSolution() { lateinit var cave: D2Array<Int> lateinit var end: Vector2i lateinit var limits: Pair<Vector2i, Vector2i> private val moves = moves() override fun parseInput(text: String) { cave = mk.ndarray(text.split("\n").map { it.map { c -> c.digitToInt() } }) limits = Vector2i() to Vector2i(cave.shape[0] - 1, cave.shape[1] - 1) end = limits.second } open fun getRisk(pos: Vector2i) = cave[pos] override fun compute(): Int { val traversal = AStar(this::nextEdges, this::heuristic) traversal.startFrom(Vector2i()).goTo(end) return traversal.distance } private fun nextEdges(pos: Vector2i, traversal: AStar<Vector2i>): Sequence<Pair<Vector2i, Int>> { return sequence { for (neighbor in pos.neighbors(moves, limits)) { yield(neighbor to getRisk(neighbor)) } } } private fun heuristic(pos: Vector2i) = (end - pos).norm(Order.L1) override fun getExampleAnswer() = 40 } class Part15B : Part15A() { override fun config() { limits = Vector2i() to Vector2i(cave.shape[0] * 5 - 1, cave.shape[1] * 5 - 1) end = limits.second } override fun getRisk(pos: Vector2i): Int { val blockX = pos.x / cave.shape[0] val x = pos.x % cave.shape[0] val blockY = pos.y / cave.shape[1] val y = pos.y % cave.shape[1] return (cave[x, y] + blockX + blockY - 1) % 9 + 1 } override fun getExampleAnswer() = 315 } fun main() { Day(2021, 15, Part15A(), Part15B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
1,880
advent-of-code-kotlin
MIT License
src/Day10.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
import java.lang.StringBuilder fun main() { class Cpu(val input: List<String>) { var cycle = 0 var instructionPointer = 0 var instruction: String? = null var register = 1 var cyclesToExecute = 0 fun beforeCycle(): Boolean { cycle++ if (instruction == null) { if (instructionPointer in input.indices) { instruction = input[instructionPointer++] cyclesToExecute = if (instruction!!.startsWith("addx")) { 2 } else { 1 } } else { return false } } return true } fun afterCycle() { if (--cyclesToExecute == 0) { if (instruction!!.startsWith("addx")) { register += instruction!!.substringAfter(" ").toInt() } instruction = null } } } fun part1(input: List<String>): Int { val cpu = Cpu(input) var sum = 0 while (cpu.beforeCycle()) { if (cpu.cycle % 40 == 20) { sum += cpu.cycle * cpu.register } cpu.afterCycle() } return sum } fun part2(input: List<String>): Int { val cpu = Cpu(input) val image = StringBuilder() var x = 0 while (cpu.beforeCycle()) { if (x++ in cpu.register - 1..cpu.register + 1) { image.append("#") } else { image.append(".") } if (x >= 40) { image.appendLine() x = 0 } cpu.afterCycle() } print(image) return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == 0) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
2,136
AdventOfCode2022
Apache License 2.0
src/main/kotlin/Day10.kt
alex859
573,174,372
false
{"Kotlin": 80552}
fun main() { val testInput = readInput("Day10_test.txt") check(testInput.day10Part1() == 13140) check(testInput.day10Part2() == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent()) val input = readInput("Day10.txt") println(input.day10Part1()) println(input.day10Part2()) } internal fun String.day10Part1(): Int { val cycles = cycles() return cycles.signalStrength(20) + cycles.signalStrength(60) + cycles.signalStrength(100) + cycles.signalStrength(140) + cycles.signalStrength(180) + cycles.signalStrength(220) } internal fun String.day10Part2() = cycles().draw() internal fun Int.pixel(index: Int): String { val sprite = listOf(this - 1, this, this + 1) return if (sprite.contains(index)) "#" else "." } internal fun List<Int>.draw(): String { return chunked(40).joinToString("\n") { it.drawLine() } } private fun List<Int>.drawLine() = mapIndexed { i, register -> register.pixel(i) }.joinToString(separator = "") internal fun List<Int>.signalStrength(cycle: Int): Int { return this[cycle - 1] * cycle } internal fun String.cycles(): List<Int> { var register = 1 return lines() .map { it.toCpuInstruction() } .flatMap { instruction -> when (instruction) { is NoOp -> listOf(register) is Add -> listOf(register, register).also { register += instruction.addend } } } } private fun String.toCpuInstruction() = when (this) { "noop" -> NoOp else -> split(" ").let { (_, addend) -> Add(addend.toInt()) } } private sealed interface CpuInstruction object NoOp : CpuInstruction data class Add(val addend: Int) : CpuInstruction
0
Kotlin
0
0
fbbd1543b5c5d57885e620ede296b9103477f61d
2,008
advent-of-code-kotlin-2022
Apache License 2.0
src/Day06.kt
brigittb
572,958,287
false
{"Kotlin": 46744}
fun main() { fun indexOfMarker(input: String, length: Int): Int { val unique = input .windowed(length) .map { it.toSet() } .first { it.size == length } .joinToString("") return input.indexOf(unique) + length } fun part1(input: List<String>): Int = indexOfMarker(input = input.first(), length = 4) fun part2(input: List<String>): Int = indexOfMarker(input = input.first(), length = 14) // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 11) check(part2(testInput) == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
470f026f2632d1a5147919c25dbd4eb4c08091d6
760
aoc-2022
Apache License 2.0
app/src/main/kotlin/com/bloidonia/advent2020/Day_09.kt
timyates
317,965,519
false
null
package com.bloidonia.advent2020 import com.bloidonia.longsFromResource class Day_09 { // Given a list of T, return a sequence of every combination of pairs fun <T> combinationPairs(input: List<T>): Sequence<Pair<T, T>> = sequence { for (i in 0 until input.size - 1) for (j in i + 1 until input.size) yield(input[i] to input[j]) } fun part1(input: List<Long>, preamble: Int): Long { for (start in 0 until input.size - preamble) { input.drop(start).take(preamble + 1).let { chunk -> if (combinationPairs(chunk.take(preamble)).none { it.first + it.second == chunk.last() }) { return chunk.last() } } } return -1 } fun part2(input: List<Long>, invalidNumber: Long): Long { for (idx in input.indices) { for (span in idx + 1 until input.size) { val block = input.drop(idx).take(span - idx) val sum = block.sum() if (sum == invalidNumber) { return block.maxOrNull()!! + block.minOrNull()!! } else if (sum > invalidNumber) { break } } } return -1 } } fun main() { val day09 = Day_09() val input = longsFromResource("/9.txt") val invalidNumber = day09.part1(input, 25) println(invalidNumber) println(day09.part2(input, invalidNumber)) }
0
Kotlin
0
0
cab3c65ac33ac61aab63a1081c31a16ac54e4fcd
1,489
advent-of-code-2020-kotlin
Apache License 2.0
03/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : List<String> { return File("input.txt") .readLines() } fun getRates(report : List<String>) : Pair<Int, Int> { var lineFreq = Array(report[0].length) { Array(2) {0} } for (line in report) { for ((idx, char) in line.withIndex()) { lineFreq[idx][char - '0']++; } } return calcRatesFrom(lineFreq) } fun calcRatesFrom(lineFreq : Array<Array<Int>>) : Pair<Int, Int> { var gammaRate = 0 var epsRate = 0 for (column in lineFreq.indices) { gammaRate *= 2 epsRate *= 2 if (lineFreq[column][1] > lineFreq[column][0]) { gammaRate++ } else { epsRate++ } } return Pair(gammaRate, epsRate) } fun solve(gammaRate : Int, epsRate : Int) : Int { return gammaRate * epsRate; } fun main() { val report = readInput() val (gammaRate, epsRate) = getRates(report) val ans = solve(gammaRate, epsRate) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
999
advent-of-code-2021
MIT License
Problems/Algorithms/1856. Maximum Subarray Min-Product/MaxMinProduct.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun maxSumMinProduct(nums: IntArray): Int { val n = nums.size val stack = Stack<Int>() val nextSmaller = IntArray(n) { n } val prevSmaller = IntArray(n) { -1 } for (i in 0..n-1) { while (!stack.isEmpty() && nums[i] < nums[stack.peek()]) { nextSmaller[stack.peek()] = i stack.pop() } stack.push(i) } while (!stack.isEmpty()) { stack.pop() } for (i in n-1 downTo 0) { while (!stack.isEmpty() && nums[i] < nums[stack.peek()]) { prevSmaller[stack.peek()] = i stack.pop() } stack.push(i) } var prefix: Long = 0 val prefixes = LongArray(n+1) { 0 } for (i in 1..n) { prefix += nums[i-1] prefixes[i] = prefix } var ans: Long = 0 for (i in 0..n-1) { val right = nextSmaller[i] val left = prevSmaller[i] val sum: Long = prefixes[right] - prefixes[left+1] ans = maxOf(ans, sum * nums[i]) } return (ans % 1000000007).toInt() } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,267
leet-code
MIT License
kotlin/1254-number-of-closed-islands.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun closedIsland(grid: Array<IntArray>): Int { val rows = grid.size val cols = grid[0].size val visited = Array(rows){BooleanArray(cols)} fun isValid(r: Int, c: Int) = r in (0 until rows) && c in (0 until cols) fun dfs(r: Int, c: Int): Int { if(!isValid(r, c)) return 0 if(grid[r][c] == 1 || visited[r][c] == true) return 1 visited[r][c] = true return minOf( minOf( dfs(r + 1, c), dfs(r - 1, c) ), minOf( dfs(r, c + 1), dfs(r, c - 1) ) ) } var islands = 0 for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == 0 && visited[r][c] == false) { if (dfs(r, c) != 0) islands++ } } } return islands } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,071
leetcode
MIT License
src/test/kotlin/Day7Test.kt
FredrikFolkesson
320,692,155
false
null
import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day7Test { @Test fun test_demo_input() { assertEquals( 4, numberOfBagColorsThatCanContainGoldBag( ("light red bags contain 1 bright white bag, 2 muted yellow bags.\n" + "dark orange bags contain 3 bright white bags, 4 muted yellow bags.\n" + "bright white bags contain 1 shiny gold bag.\n" + "muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\n" + "shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\n" + "dark olive bags contain 3 faded blue bags, 4 dotted black bags.\n" + "vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\n" + "faded blue bags contain no other bags.\n" + "dotted black bags contain no other bags.").lines() ) ) } @Test fun `test real input`() { println(numberOfBagColorsThatCanContainGoldBag(readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day7.txt"))) } @Test fun `test real input part 2`() { println(numberOfBagsInsideGoldBag(readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day7.txt"))) } @Test fun `test_demo_input part 2`() { assertEquals( 126, numberOfBagsInsideGoldBag( ("shiny gold bags contain 2 dark red bags.\n" + "dark red bags contain 2 dark orange bags.\n" + "dark orange bags contain 2 dark yellow bags.\n" + "dark yellow bags contain 2 dark green bags.\n" + "dark green bags contain 2 dark blue bags.\n" + "dark blue bags contain 2 dark violet bags.\n" + "dark violet bags contain no other bags.").lines() ) ) } private fun numberOfBagsInsideGoldBag(bagRulesList: List<String>): Int { val bagRules = bagRulesList.map { getBagRuleWithNumberOfBagsDirectlyInside(it) }.toMap() return getNumberOfBagsInside("shiny gold", bagRules) } @Test fun `test getBagRuleWithNumberOfBagsDirectlyInside`() { assertEquals( Pair("faded blue", listOf<Pair<Int, String>>()), getBagRuleWithNumberOfBagsDirectlyInside("faded blue bags contain no other bags.") ) assertEquals( Pair("bright white", listOf<Pair<Int, String>>(Pair(1, "shiny gold"))), getBagRuleWithNumberOfBagsDirectlyInside("bright white bags contain 1 shiny gold bag.") ) assertEquals( Pair("muted yellow", listOf<Pair<Int, String>>(Pair(2, "shiny gold"), Pair(9, "faded blue"))), getBagRuleWithNumberOfBagsDirectlyInside("muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.") ) } private fun getBagRuleWithNumberOfBagsDirectlyInside(bagRuleString: String): Pair<String, List<Pair<Int, String>>> { return bagRuleString.split(" bags contain ").let { val containedBags = if (it[1].equals("no other bags.")) listOf() else it[1].split(", ") .map { it.split(" ")[0].toInt() to it.split(" ")[1] + " " + it.split(" ")[2] } Pair(it[0], containedBags) } } private fun getBagRule(bagRuleString: String): Pair<String, List<String>> { return bagRuleString.split(" bags contain ").let { val containedBags = if (it[1].equals("no other bags.")) listOf() else it[1].split(", ") .map { it.split(" ")[1] + " " + it.split(" ")[2] } Pair(it[0], containedBags) } } @Test fun `test_demo_input part 3`() { assertEquals( 32, numberOfBagsInsideGoldBag( ("flight red bags contain 1 bright white bag, 2 muted yellow bags.\n" + "dark orange bags contain 3 bright white bags, 4 muted yellow bags.\n" + "bright white bags contain 1 shiny gold bag.\n" + "muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\n" + "shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\n" + "dark olive bags contain 3 faded blue bags, 4 dotted black bags.\n" + "vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\n" + "faded blue bags contain no other bags.\n" + "dotted black bags contain no other bags.").lines() ) ) } private fun getNumberOfBagsInside(bagType: String, bagRules: Map<String, List<Pair<Int, String>>>): Int { val containedBags = bagRules.getOrElse(bagType) { throw IllegalArgumentException("No bag of type $bagType found in map") } // val get:List<Pair<Int, String>> = bagRules[bagType] ?: listOf() return if (containedBags.isEmpty()) 0 else containedBags.sumOf { it.first + (it.first * getNumberOfBagsInside( it.second, bagRules )) } } private fun numberOfBagColorsThatCanContainGoldBag(bagRulesList: List<String>): Int { val bagRules = bagRulesList.map { getBagRule(it) }.toMap() return bagRules.keys.count { containsGoldBag(it, bagRules) } } @Test fun `test get bag rule`() { assertEquals( Pair("light red", listOf("bright white", "muted yellow")), getBagRule("light red bags contain 1 bright white bag, 2 muted yellow bags.") ) assertEquals(Pair("faded blue", listOf()), getBagRule("faded blue bags contain no other bags.")) assertEquals( Pair("bright white", listOf("shiny gold")), getBagRule("bright white bags contain 1 shiny gold bag.") ) } @Test fun `test containsGoldBag`() { assertEquals( true, containsGoldBag( "light red", mapOf( Pair("light red", listOf<String>("bright white", "muted yellow")), Pair("bright white", listOf<String>("shiny gold")), Pair("muted yellow", listOf<String>("shiny gold", "faded blue")) ) ) ) assertEquals( true, containsGoldBag( "dark orange", mapOf( Pair("dark orange", listOf<String>("bright white", "muted yellow")), Pair("light red", listOf<String>("bright white", "muted yellow")), Pair("bright white", listOf<String>("shiny gold")), Pair("muted yellow", listOf<String>("shiny gold", "faded blue")) ) ) ) assertEquals(true, containsGoldBag("bright white", mapOf(Pair("bright white", listOf<String>("shiny gold"))))) assertEquals( true, containsGoldBag("muted yellow", mapOf(Pair("muted yellow", listOf<String>("shiny gold", "faded blue")))) ) assertEquals( false, containsGoldBag( "shiny gold", mapOf( Pair("shiny gold", listOf<String>("dark olive", "vibrant plum")), Pair("dark olive", listOf<String>("faded blue", "dotted black")), Pair("vibrant plum", listOf<String>("faded blue", "dotted black")), Pair("muted yellow", listOf<String>("shiny gold", "faded blue")), Pair("dotted black", listOf<String>()), Pair("faded blue", listOf<String>()) ) ) ) assertEquals( false, containsGoldBag( "dark olive", mapOf( Pair("dark olive", listOf<String>("faded blue", "dotted black")), Pair("dotted black", listOf<String>()), Pair("faded blue", listOf<String>()) ) ) ) assertEquals( false, containsGoldBag( "vibrant plum", mapOf( Pair("vibrant plum", listOf<String>("faded blue", "dotted black")), Pair("dotted black", listOf<String>()), Pair("faded blue", listOf<String>()) ) ) ) assertEquals(false, containsGoldBag("dotted black", mapOf(Pair("dotted black", listOf<String>())))) assertEquals(false, containsGoldBag("faded blue", mapOf(Pair("faded blue", listOf<String>())))) } private fun containsGoldBag(bagType: String, bagRules: Map<String, List<String>>): Boolean { val containedBagTypes = bagRules.getOrElse(bagType) { throw IllegalArgumentException("No bag of type $bagType found in map") } return when { containedBagTypes.contains("shiny gold") -> true containedBagTypes.isEmpty() -> false else -> containedBagTypes.any { containsGoldBag(it, bagRules) } } } private fun numberOfBagsInsideGoldBag2(bagRulesList: List<String>): Int { val bagRules = bagRulesList.map { getBagRuleWithNumberOfBagsDirectlyInside(it) }.toMap() return getNumberOfBagsInside2("shiny gold", bagRules) } private fun getNumberOfBagsInside2(bagType: String, bagRules: Map<String, List<Pair<Int, String>>>): Int { val containedBags = bagRules.getOrElse(bagType) { throw IllegalArgumentException("No bag of type $bagType found in map") } return if (containedBags.isEmpty()) 0 else containedBags.sumOf { it.first + (it.first * getNumberOfBagsInside2( it.second, bagRules )) } } }
0
Kotlin
0
0
79a67f88e1fcf950e77459a4f3343353cfc1d48a
9,951
advent-of-code
MIT License
src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0939_minimum_area_rectangle // #Medium #Array #Hash_Table #Math #Sorting #Geometry // #2023_04_29_Time_461_ms_(100.00%)_Space_74.8_MB_(20.00%) import java.util.Arrays import kotlin.math.abs class Solution { fun minAreaRect(points: Array<IntArray>): Int { if (points.size < 4) { return 0 } val map: MutableMap<Int, MutableSet<Int>> = HashMap() for (p in points) { map.putIfAbsent(p[0], HashSet()) map.getValue(p[0]).add(p[1]) } Arrays.sort( points ) { a: IntArray, b: IntArray -> if (a[0] == b[0]) Integer.compare( a[1], b[1] ) else Integer.compare(a[0], b[0]) } var min = Int.MAX_VALUE for (i in 0 until points.size - 2) { for (j in i + 1 until points.size - 1) { val p1 = points[i] val p2 = points[j] val area = abs((p1[0] - p2[0]) * (p1[1] - p2[1])) if (area >= min || area == 0) { continue } if (map.getValue(p1[0]).contains(p2[1]) && map.getValue(p2[0]).contains(p1[1])) { min = area } } } return if (min == Int.MAX_VALUE) 0 else min } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,349
LeetCode-in-Kotlin
MIT License
src/main/kotlin/cloud/dqn/leetcode/self/IslandFinder.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode.self /** * Nov 12, 2017 * Self generated problem * * Find the islands in a (0,1) * * Island is defined as a 1 surrounded by 0's * - ?? Are pairs found on edges considered Islands (Peninsula) * Planned improvements: * Handle easily convertable resutl * Handle non NxN array * Handle island of not a single 1 case * Handle islands made up of 0's or 1's */ /* Algo 0: val map = CoordinateMap() fun isIsland(x: Int, y: Int, map: CoordinateMap): Boolean map.forEach { if (isIsland(x, y) { Add to result } } */ class IslandFinder: Iterable<Pair<Int, Int>> { var map: Array<IntArray> var countPeninsulas: Boolean var islandValueIsValid: (Int) -> Boolean constructor( map: Array<IntArray>, islandValueIsValid: (Int) -> Boolean = { true }, countPeninsulas: Boolean = false) { this.map = map this.countPeninsulas = countPeninsulas this.islandValueIsValid = islandValueIsValid } fun mapToString(): String { val s = StringBuilder(map.size * map.size) map.forEach { it.forEach { s.append(it) } s.append("\n") } return s.toString() } fun findAllIslands(): Answer { val answer = Answer() this.forEach { (rowIndex, colIndex) -> val pointValue = PointValue(rowIndex, colIndex, map[rowIndex][colIndex]) if (isIsland(pointValue) && islandValueIsValid(pointValue.value)) { answer.pairs.add(pointValue) } } return answer } override fun iterator(): Iterator<Pair<Int, Int>> { return IslandFinderIterator(this) } class IslandFinderIterator: Iterator<Pair<Int, Int>> { private val islandFinder: IslandFinder private var rowIndex: Int private var colIndex: Int constructor(islandFinder: IslandFinder) { this.islandFinder = islandFinder this.rowIndex = 0 this.colIndex = 0 } override fun hasNext(): Boolean { return islandFinder.onMap(rowIndex, colIndex) } override fun next(): Pair<Int, Int> { val pair = Pair(rowIndex, colIndex) val row = islandFinder.map[rowIndex] colIndex++ if (colIndex >= row.size) { rowIndex++ colIndex = 0 } return pair } } private fun isIsland(p: PointValue): Boolean { if (!countPeninsulas && isOnBoarder(p)) { return false } var itsAnIsland = true iterateAroundPoint(p, body = { pointValue -> itsAnIsland = itsAnIsland && (p.value != pointValue.value) } ) return itsAnIsland } inline private fun iterateAroundPoint(p: PointValue, body: (PointValue) -> Unit) { p.getBoarderPoints().forEach { point -> pointValueFactory(point)?.let { body(it) } } } private fun pointValueFactory(row: Int, col: Int): PointValue? { return getValue(row, col)?.let { PointValue(row, col, it) } } private fun pointValueFactory(p: Point): PointValue? { return pointValueFactory(p.row, p.col) } private fun getValue(p: Point): Int? { return getValue(p.row, p.col) } private fun getValue(row: Int, col: Int): Int? { if (onMap(row, col)) { return map[row][col] } return null } private fun onMap(row: Int, col: Int): Boolean { if (row >= 0 && row < map.size) { val r = map[row] if (col >= 0 && col < r.size) { return true } } return false } private fun isOnBoarder(p: PointValue): Boolean { if (onMap(p.row, p.col)) { val row = map[p.row] return p.row == 0 || p.row == map.size - 1 || p.col == 0 || p.col == row.size - 1 } return false } /************************************************* * Sub Classes (Usually to be devided into it's own file) **************************************************/ /* Class for storing an answer to get all answers Used to convert answer to that required by program */ class Answer { val pairs = HashSet<PointValue>() fun toFormat() { TODO("finish") } } data class Point ( val row: Int, val col: Int ) { fun toPair(): Pair<Int, Int> = Pair(row, col) } class PointValue { val row: Int val col: Int var value: Int constructor(row: Int, col: Int, value: Int) { this.row = row this.col = col this.value = value } private constructor(p: Point, value: Int) { this.row = p.row this.col = p.col this.value = value } override fun equals(other: Any?): Boolean { return other is PointValue && other.row == row && other.col == col && other.value == value } override fun hashCode(): Int { return "r${row}c$col{$}v${value}".hashCode() } // topLeft, topCenter, topRight private fun topLeft(): Point = Point(row - 1, col - 1) private fun topCenter(): Point = Point( row -1, col) private fun topRight(): Point = Point( row -1, col + 1) // middleLeft, middleRight private fun middleLeft(): Point = Point(row, col - 1) private fun middleRight(): Point = Point(row, col + 1) // bottomLeft, bottomCenter, bottomRight private fun bottomLeft(): Point = Point(row + 1, col - 1) private fun bottomMiddle(): Point = Point(row + 1, col) private fun bottomRight(): Point = Point(row + 1, col + 1) fun getBoarderPoints(): Array<Point> { return arrayOf( topLeft(), topCenter(), topRight(), middleLeft(), middleRight(), bottomLeft(), bottomMiddle(), bottomRight() ) } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
6,375
cloud-dqn-leetcode
No Limit Public License
jvm/word-finder/src/test/kotlin/net/maelbrancke/filip/service/SolverDataTest.kt
filipmaelbrancke
597,192,385
false
{"Rust": 268793, "Kotlin": 38872, "Shell": 17239, "Dockerfile": 478, "PLpgSQL": 238}
package net.maelbrancke.filip.service import net.maelbrancke.filip.KotestProject import io.kotest.assertions.arrow.core.shouldBeLeft import io.kotest.assertions.arrow.core.shouldBeRight import io.kotest.core.spec.style.FunSpec import io.kotest.datatest.WithDataTestName import io.kotest.datatest.withData import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import net.maelbrancke.filip.WordCombination class SolverDataTest : FunSpec({ suspend fun solverService(): SolverService = KotestProject.dependencies.get().solver context("test inputs that should have valid combinations") { withData( TestCombination( input = TestInput("foobar", "foob", "ar"), solutions = TestSolutions(WordCombination(output = "foobar", inputWords = listOf("foob", "ar"))) ), TestCombination( input = TestInput("narrow", "narro", "w"), solutions = TestSolutions(WordCombination(output = "narrow", inputWords = listOf("narro", "w"))) ), TestCombination( input = TestInput("eens", "qu", "w", "qu", "queens"), solutions = TestSolutions(WordCombination(output = "queens", inputWords = listOf("qu", "eens"))) ), TestCombination( input = TestInput("s", "ignal", "shabby", "habby", "signal"), solutions = TestSolutions( WordCombination(output = "shabby", inputWords = listOf("s", "habby")), WordCombination(output = "signal", inputWords = listOf("s", "ignal")) ) ), TestCombination( input = TestInput("s", "skiing", "hower", "qu", "eens", "shower", "w", "teamy", "iver", "kiing", "quiver"), solutions = TestSolutions( WordCombination(output = "skiing", inputWords = listOf("s", "kiing")), WordCombination(output = "shower", inputWords = listOf("s", "hower")), WordCombination(output = "quiver", inputWords = listOf("qu", "iver")) ) ) ) { val result = solverService().findSolutions(CreateSolution(it.input.words)) result.shouldBeRight().shouldContainExactlyInAnyOrder(it.solutions.wordCombinations) } } context("test inputs that should have no solution") { withData( TestInput("foo", "bar"), TestInput("osine", "them", "narro", "es", "awler", "plex", "qu", "rrow", "iny") ) { val result = solverService().findSolutions(CreateSolution(it.words)) result.shouldBeLeft() } } }) data class TestInput(val words: List<String>) : WithDataTestName { companion object { operator fun invoke(vararg inputWords: String): TestInput { return TestInput(inputWords.asList()) } } override fun dataTestName() = "testing $words" } data class TestSolutions(val wordCombinations: List<WordCombination>) { companion object { operator fun invoke(vararg solutions: WordCombination): TestSolutions { return TestSolutions(solutions.asList()) } } } data class TestCombination(val input: TestInput, val solutions: TestSolutions) : WithDataTestName { override fun dataTestName() = "solving for ${solutions.wordCombinations.joinToString { it.output } }" }
0
Rust
0
0
ce407259666c3908f2f2c3a79659f0a16c68efd0
3,472
playground
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RepeatedSubstringPattern.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 459. Repeated Substring Pattern * @see <a href="https://leetcode.com/problems/repeated-substring-pattern/">Source</a> */ fun interface RepeatedSubstringPattern { operator fun invoke(s: String): Boolean } /** * Approach 1: Using Divisors */ class RepeatedSubstringPatternDivisors : RepeatedSubstringPattern { override operator fun invoke(s: String): Boolean { val n: Int = s.length for (i in 1..n / 2) { if (n % i == 0) { val pattern = StringBuilder() for (j in 0 until n / i) { pattern.append(s.substring(0, i)) } if (s == pattern.toString()) { return true } } } return false } } /** * Approach 2: String Concatenation */ class RepeatedSubstringPatternConcat : RepeatedSubstringPattern { override operator fun invoke(s: String): Boolean { val combined = s.plus(s) return combined.substring(1, combined.length - 1).contains(s) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,699
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindBall.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 /** * 1706. Where Will the Ball Fall * @see <a href="https://leetcode.com/problems/where-will-the-ball-fall/">Source</a> */ fun interface FindBall { operator fun invoke(grid: Array<IntArray>): IntArray } /** * Approach 1: Depth First Search (DFS) */ class FindBallDFS : FindBall { override operator fun invoke(grid: Array<IntArray>): IntArray { if (grid.isEmpty()) return intArrayOf() if (grid.first().isEmpty()) return intArrayOf() val result = IntArray(grid.first().size) for (i in 0 until grid.first().size) { result[i] = findBallDropColumn(0, i, grid) } return result } private fun findBallDropColumn(row: Int, col: Int, grid: Array<IntArray>): Int { // base case; ball reached the last row if (row == grid.size) return col val nextColumn = col + grid[row][col] return if (nextColumn < 0 || nextColumn > grid[0].size - 1 || grid[row][col] != grid[row][nextColumn] ) { -1 } else { findBallDropColumn(row + 1, nextColumn, grid) } } } /** * Approach 2: Dynamic Programming Approach */ class FindBallDP : FindBall { override operator fun invoke(grid: Array<IntArray>): IntArray { if (grid.isEmpty()) return intArrayOf() if (grid.first().isEmpty()) return intArrayOf() val result = IntArray(grid[0].size) val memo = Array<Array<Int>>(grid.size + 1) { Array(grid[0].size) { 0 } } for (row in grid.size downTo 0) { for (col in 0 until grid[0].size) { if (row == grid.size) { memo[row][col] = col continue } val nextColumn = col + grid[row][col] if (nextColumn < 0 || nextColumn > grid[0].size - 1 || grid[row][col] != grid[row][nextColumn]) { memo[row][col] = -1 } else { memo[row][col] = memo[row + 1][nextColumn] } if (row == 0) { result[col] = memo[row][col] } } } return result } } /** * Approach 3: Iterative Approach, Simulation */ class FindBallIterative : FindBall { override operator fun invoke(grid: Array<IntArray>): IntArray { if (grid.isEmpty()) return intArrayOf() if (grid.first().isEmpty()) return intArrayOf() val result = IntArray(grid[0].size) for (col in 0 until grid[0].size) { var currentCol = col for (row in grid.indices) { val nextColumn = currentCol + grid[row][currentCol] if (nextColumn < 0 || nextColumn > grid[0].size - 1 || grid[row][currentCol] != grid[row][nextColumn]) { result[col] = -1 break } result[col] = nextColumn currentCol = nextColumn } } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,663
kotlab
Apache License 2.0
src/main/kotlin/Grid2D.kt
MatteoMartinelli97
403,882,570
false
{"Kotlin": 39512}
import kotlin.random.Random /** * 2D grid container as a graph * * This class builds a graph from a 2D grid of squares, where each square is a node, and the length of each edge * is 1.0. * 2 adjacent squares are considered also adjacent nodes. * Since [Graph] works with node IDs, also [Grid2D] does, but provides to the user a simplified interface, * with rows and cols indices, as one would expect on a grid. * * IDs are assigned from left to right, top to bottom increasingly. * Same applies for rows and cols. (0, 0) is the top-left square, ([nSquares]-1, [nSquares]-1) is the bottom-right one. * * Some nodes may be considered as blocks, meaning there cannot be any edge with them. This is meant to apply * some difficulties in the finding of the shortest path. * * It is also possible to create a grid where blocks are randomly positioned, with the [Boolean] flag [randomBlocks]. * If true, each node has 10% of probability of becoming a block. This is compatible also with giving deterministic * blocks. * * Class properties are: * - [nSquares]: Number of squares per side in the grid. (Sets the dimension of the grid) * - [blocks]: List of the position * - [randomBlocks]: Boolean for creating a random grid. * * - [graph]: The [Graph] representing the grid * - [freeV]: The nodes that are not blocks * * @see Graph */ class Grid2D( val nSquares: Int, val blocks: MutableList<Pair<Int, Int>> = mutableListOf(), val randomBlocks: Boolean = false ) { private val V = (0 until nSquares * nSquares).toMutableList() val graph = Graph(V, directed = false) val freeV: MutableList<Pair<Int, Int>> = mutableListOf() private val rand = Random.Default /** * Initialization of graph. Edges between nodes are built, considering if there are blocks or not. * If [randomBlocks] is true a random generators decides whether each square may become a block */ init { if (randomBlocks) { for (i in 0 until nSquares * nSquares) { if (rand.nextFloat() < 0.1) { val row = i / nSquares val col = i % nSquares addBlock(row, col) } } } for (i in 0 until nSquares * nSquares) { val row = i / nSquares val col = i % nSquares //If block, no neighbour if (Pair(row, col) in blocks) continue if (row != nSquares - 1) { //If not in last (bottom) row --> add the neighbour under it //if not a block if (Pair(row + 1, col) !in blocks) graph.addEdge(i, i + nSquares, 1f) } if (col != nSquares - 1) { //If not in last (right) col --> add the neighbour to the right //if not a block if (Pair(row, col + 1) !in blocks) graph.addEdge(i, i + 1, 1f) } freeV.add(Pair(row, col)) } } /** * Adds a block in position ([row], [col]). Each edge with this node as an end is removed, the node is * added to [blocks] and it is removed from [freeV] */ fun addBlock(row: Int, col: Int) { blocks.add(Pair(row, col)) val id = nSquares * row + col graph.removeVertex(id) freeV.remove(Pair(row, col)) } /** * Returns the ID value of the square, given the coordinates as (row, col) */ fun getId(row: Int, col: Int): Int { return nSquares * row + col } /** * Returns the ID value of the square, given the coordinates as Pair(row, col) */ fun getId(coor: Pair<Int, Int>): Int { return nSquares * coor.first + coor.second } /** * Returns the coordinates value as a [Pair] = (row, col), given the ID value of the square. */ fun getCoordinates(id: Int): Pair<Int, Int> { val row = id / nSquares val col = id % nSquares return Pair(row, col) } }
0
Kotlin
0
0
f14d4ba7058be629b407e06eebe09fae63aa35c1
3,999
Dijkstra-and-AStar
Apache License 2.0
Rare_numbers/Kotlin/src/RareNumbers.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
import java.time.Duration import java.time.LocalDateTime import kotlin.math.sqrt class Term(var coeff: Long, var ix1: Byte, var ix2: Byte) const val maxDigits = 16 fun toLong(digits: List<Byte>, reverse: Boolean): Long { var sum: Long = 0 if (reverse) { var i = digits.size - 1 while (i >= 0) { sum = sum * 10 + digits[i] i-- } } else { var i = 0 while (i < digits.size) { sum = sum * 10 + digits[i] i++ } } return sum } fun isSquare(n: Long): Boolean { val root = sqrt(n.toDouble()).toLong() return root * root == n } fun seq(from: Byte, to: Byte, step: Byte): List<Byte> { val res = mutableListOf<Byte>() var i = from while (i <= to) { res.add(i) i = (i + step).toByte() } return res } fun commatize(n: Long): String { var s = n.toString() val le = s.length var i = le - 3 while (i >= 1) { s = s.slice(0 until i) + "," + s.substring(i) i -= 3 } return s } fun main() { val startTime = LocalDateTime.now() var pow = 1L println("Aggregate timings to process all numbers up to:") // terms of (n-r) expression for number of digits from 2 to maxDigits val allTerms = mutableListOf<MutableList<Term>>() for (i in 0 until maxDigits - 1) { allTerms.add(mutableListOf()) } for (r in 2..maxDigits) { val terms = mutableListOf<Term>() pow *= 10 var pow1 = pow var pow2 = 1L var i1: Byte = 0 var i2 = (r - 1).toByte() while (i1 < i2) { terms.add(Term(pow1 - pow2, i1, i2)) pow1 /= 10 pow2 *= 10 i1++ i2-- } allTerms[r - 2] = terms } // map of first minus last digits for 'n' to pairs giving this value val fml = mapOf( 0.toByte() to listOf(listOf<Byte>(2, 2), listOf<Byte>(8, 8)), 1.toByte() to listOf(listOf<Byte>(6, 5), listOf<Byte>(8, 7)), 4.toByte() to listOf(listOf<Byte>(4, 0)), 6.toByte() to listOf(listOf<Byte>(6, 0), listOf<Byte>(8, 2)) ) // map of other digit differences for 'n' to pairs giving this value val dmd = mutableMapOf<Byte, MutableList<List<Byte>>>() for (i in 0 until 100) { val a = listOf((i / 10).toByte(), (i % 10).toByte()) val d = a[0] - a[1] dmd.getOrPut(d.toByte(), { mutableListOf() }).add(a) } val fl = listOf<Byte>(0, 1, 4, 6) val dl = seq(-9, 9, 1) // all differences val zl = listOf<Byte>(0) // zero differences only val el = seq(-8, 8, 2) // even differences only val ol = seq(-9, 9, 2) // odd differences only val il = seq(0, 9, 1) val rares = mutableListOf<Long>() val lists = mutableListOf<MutableList<List<Byte>>>() for (i in 0 until 4) { lists.add(mutableListOf()) } for (i_f in fl.withIndex()) { lists[i_f.index] = mutableListOf(listOf(i_f.value)) } var digits = mutableListOf<Byte>() var count = 0 // Recursive closure to generate (n+r) candidates from (n-r) candidates // and hence find Rare numbers with a given number of digits. fun fnpr( cand: List<Byte>, di: MutableList<Byte>, dis: List<List<Byte>>, indicies: List<List<Byte>>, nmr: Long, nd: Int, level: Int ) { if (level == dis.size) { digits[indicies[0][0].toInt()] = fml[cand[0]]?.get(di[0].toInt())?.get(0)!! digits[indicies[0][1].toInt()] = fml[cand[0]]?.get(di[0].toInt())?.get(1)!! var le = di.size if (nd % 2 == 1) { le-- digits[nd / 2] = di[le] } for (i_d in di.slice(1 until le).withIndex()) { digits[indicies[i_d.index + 1][0].toInt()] = dmd[cand[i_d.index + 1]]?.get(i_d.value.toInt())?.get(0)!! digits[indicies[i_d.index + 1][1].toInt()] = dmd[cand[i_d.index + 1]]?.get(i_d.value.toInt())?.get(1)!! } val r = toLong(digits, true) val npr = nmr + 2 * r if (!isSquare(npr)) { return } count++ print(" R/N %2d:".format(count)) val checkPoint = LocalDateTime.now() val elapsed = Duration.between(startTime, checkPoint).toMillis() print(" %9sms".format(elapsed)) val n = toLong(digits, false) println(" (${commatize(n)})") rares.add(n) } else { for (num in dis[level]) { di[level] = num fnpr(cand, di, dis, indicies, nmr, nd, level + 1) } } } // Recursive closure to generate (n-r) candidates with a given number of digits. fun fnmr(cand: MutableList<Byte>, list: List<List<Byte>>, indicies: List<List<Byte>>, nd: Int, level: Int) { if (level == list.size) { var nmr = 0L var nmr2 = 0L for (i_t in allTerms[nd - 2].withIndex()) { if (cand[i_t.index] >= 0) { nmr += i_t.value.coeff * cand[i_t.index] } else { nmr2 += i_t.value.coeff * -cand[i_t.index] if (nmr >= nmr2) { nmr -= nmr2 nmr2 = 0 } else { nmr2 -= nmr nmr = 0 } } } if (nmr2 >= nmr) { return } nmr -= nmr2 if (!isSquare(nmr)) { return } val dis = mutableListOf<List<Byte>>() dis.add(seq(0, ((fml[cand[0]] ?: error("oops")).size - 1).toByte(), 1)) for (i in 1 until cand.size) { dis.add(seq(0, (dmd[cand[i]]!!.size - 1).toByte(), 1)) } if (nd % 2 == 1) { dis.add(il) } val di = mutableListOf<Byte>() for (i in 0 until dis.size) { di.add(0) } fnpr(cand, di, dis, indicies, nmr, nd, 0) } else { for (num in list[level]) { cand[level] = num fnmr(cand, list, indicies, nd, level + 1) } } } for (nd in 2..maxDigits) { digits = mutableListOf() for (i in 0 until nd) { digits.add(0) } if (nd == 4) { lists[0].add(zl) lists[1].add(ol) lists[2].add(el) lists[3].add(ol) } else if (allTerms[nd - 2].size > lists[0].size) { for (i in 0 until 4) { lists[i].add(dl) } } val indicies = mutableListOf<List<Byte>>() for (t in allTerms[nd - 2]) { indicies.add(listOf(t.ix1, t.ix2)) } for (list in lists) { val cand = mutableListOf<Byte>() for (i in 0 until list.size) { cand.add(0) } fnmr(cand, list, indicies, nd, 0) } val checkPoint = LocalDateTime.now() val elapsed = Duration.between(startTime, checkPoint).toMillis() println(" %2d digits: %9sms".format(nd, elapsed)) } rares.sort() println("\nThe rare numbers with up to $maxDigits digits are:") for (i_rare in rares.withIndex()) { println(" %2d: %25s".format(i_rare.index + 1, commatize(i_rare.value))) } }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
7,606
rosetta
MIT License
android/app/src/main/java/com/thepyprogrammer/ktlib/signalProcessing/SignalProcessing.kt
terminalai
312,471,067
false
null
package com.thepyprogrammer.ktlib.signalProcessing import div import normalise import slice import sum import timesConj import toComplex import transpose import kotlin.math.pow import kotlin.math.roundToInt const val SR = 64.0 const val stepSize = 1 const val windowLength = 256 private val f_nr_LBs: Int = (0.5 * windowLength / SR).roundToInt() private val f_nr_LBe: Int = (3 * windowLength / SR).roundToInt() private val f_nr_FBs: Int = (3 * windowLength / SR).roundToInt() private val f_nr_FBe: Int = (8 * windowLength / SR).roundToInt() val powerTH = 2.0.pow(11.5) /** * Do numerical integration of x */ fun numIntegration(x: Array<Double>): Double { val term1: Double = x.slice(1, x.size).sum() val term2: Double = x.slice(0, -1).sum() return (term1 + term2) / (SR * 2) } /** * Moore's Algorithm * Compute the Freeze Index for a certain axis */ fun freeze(data: Array<Double>): Array<Double> { var jPos: Int val iMax: Int = (data.size / stepSize) val freezeIndex = mutableListOf<Double>() for (i in 0..iMax) { // Time (sample nr) of this window val jStart = i * stepSize jPos = jStart + windowLength // compute com.thepyprogrammer.gaitanalyzer.model.signalProcessing.FFT (Fast Fourier Transform) val y = FFT.fft( // get the signal in the window data.slice(jStart, jPos) // make signal zero-mean (mean normalization) .normalise() .toComplex() ) val pyy: Array<Double> = y.timesConj() / windowLength //--- calculate sumLocoFreeze and com.thepyprogrammer.gaitanalyzer.model.signalProcessing.freezeIndex --- val areaLocoBand = numIntegration(pyy.slice(f_nr_LBs, f_nr_LBe, 1)) val areaFreezeBand = numIntegration(pyy.slice(f_nr_FBs, f_nr_FBe, 1)) // Extension of Baechlin to handle low-energy situations (e.g. standing) freezeIndex.add( if (areaFreezeBand + areaLocoBand >= powerTH) areaFreezeBand / areaLocoBand else 0.0 ) } return freezeIndex.toTypedArray() } /** * Computes the Freeze Index for all 3 axes */ fun freezeIndex(data: Array<Array<Double>>): Array<Array<Double>> { val fis = mutableListOf<Array<Double>>() val dat = data.transpose() for (axis in 1..5) { fis.add(freeze(dat[axis])) } return fis.toTypedArray() }
1
Jupyter Notebook
4
10
2064375ddc36bf38f3ff65f09e776328b8b4612a
2,430
GaitMonitoringForParkinsonsDiseasePatients
MIT License
src/commonMain/kotlin/model/model.kt
chausknecht
544,439,666
false
null
package model import dev.fritz2.core.Lenses import kotlin.random.Random data class Coordinate(val x: Int, val y: Int) { companion object { fun of(index: Int) = Coordinate(index % World.MAX_X, index / World.MAX_X) } val index: Int = y * World.MAX_X + x operator fun plus(move: Move) = Coordinate(x + move.x, y + move.y) } /** * ``` * 01234567 * 1........ * 2....x... * 3........ * 4........ * ``` */ enum class Move(val x: Int, val y: Int) { Stay(0, 0), Up(0, -1), UpRight(1, -1), UpLeft(-1, -1), Down(0, 1), DownRight(1, 1), DownLeft(-1, 1), Right(1, 0), Left(-1, 0); fun reverse(): Move = when (this) { Stay -> Stay Up -> Down Down -> Up Left -> Right Right -> Left else -> Stay } fun orthogonal(): List<Move> = when (this) { Up, Down -> listOf(Right, Left) Right, Left -> listOf(Up, Down) else -> listOf(Stay) } } val neighbours: List<Move> = Move.values().filterNot { it == Move.Stay }.toList() val neighboursFour: List<Move> = listOf(Move.Up, Move.Down, Move.Right, Move.Left) enum class Tile( val symbol: String, ) { Empty(""), Grass("."), StompedGrass("."), Stone("^"), Tree("*"), Orc("O"), Troll("T"), Goblin("G") } interface Movement { fun next(world: World, current: Coordinate): Coordinate } class Bouncing(private var last: Move) : Movement { private val priorities: Map<Move, List<List<Move>>> = mapOf( Move.Up to ( listOf( listOf(Move.Up, Move.Right, Move.Left, Move.Down), listOf(Move.Up, Move.Left, Move.Right, Move.Down) )), Move.Down to ( listOf( listOf(Move.Down, Move.Right, Move.Left, Move.Up), listOf(Move.Down, Move.Left, Move.Right, Move.Up) )), Move.Right to ( listOf( listOf(Move.Right, Move.Up, Move.Down, Move.Left), listOf(Move.Right, Move.Down, Move.Up, Move.Left) )), Move.Left to ( listOf( listOf(Move.Left, Move.Up, Move.Down, Move.Right), listOf(Move.Left, Move.Down, Move.Up, Move.Right) )), Move.Stay to ( listOf( listOf(Move.Up, Move.Down, Move.Right, Move.Left) )), ) override fun next(world: World, current: Coordinate): Coordinate = priorities[last]!!.random().fold(false to last) { (possible, result), move -> if (possible) { true to result } else { if (world.isPassable(current + move)) true to move else possible to result } }.let { (possible, move) -> if (possible) move else Move.Stay } .also { last = it } .let { current + it } } class KeepOn(private var last: Move) : Movement { private val priorities = mapOf( Move.Up to buildList { add(listOf(Move.Up, Move.UpLeft, Move.UpRight)) add(listOf(Move.Left, Move.Right)) add(listOf(Move.Down, Move.DownLeft, Move.DownRight)) }, Move.Down to buildList { add(listOf(Move.Down, Move.DownLeft, Move.DownRight)) add(listOf(Move.Left, Move.Right)) add(listOf(Move.Up, Move.UpLeft, Move.UpRight)) }, Move.Right to buildList { add(listOf(Move.Right, Move.UpRight, Move.DownRight)) add(listOf(Move.Up, Move.Down)) add(listOf(Move.Left, Move.UpLeft, Move.DownLeft)) }, Move.Left to buildList { add(listOf(Move.Left, Move.UpLeft, Move.DownLeft)) add(listOf(Move.Up, Move.Down)) add(listOf(Move.Right, Move.UpRight, Move.DownRight)) }, Move.UpRight to buildList { add(listOf(Move.Up, Move.UpRight, Move.Right)) add(listOf(Move.UpLeft, Move.DownRight)) add(listOf(Move.Down, Move.DownLeft, Move.Left)) }, Move.DownLeft to buildList { add(listOf(Move.Down, Move.DownLeft, Move.Left)) add(listOf(Move.UpLeft, Move.DownRight)) add(listOf(Move.Up, Move.UpRight, Move.Right)) }, Move.UpLeft to buildList { add(listOf(Move.Up, Move.UpLeft, Move.Left)) add(listOf(Move.UpRight, Move.DownLeft)) add(listOf(Move.Down, Move.DownRight, Move.Right)) }, Move.DownRight to buildList { add(listOf(Move.Down, Move.DownRight, Move.Right)) add(listOf(Move.UpRight, Move.DownLeft)) add(listOf(Move.Up, Move.UpLeft, Move.Left)) }, Move.Stay to listOf(Move.values().filter { it != Move.Stay }) ) private fun prioritiesFor(move: Move) = priorities[move]!!.flatMap { it.shuffled() } override fun next(world: World, current: Coordinate): Coordinate = prioritiesFor(last).fold(false to last) { (possible, result), move -> if (possible) { true to result } else { if (world.isPassable(current + move)) true to move else possible to result } }.let { (possible, move) -> if (possible) move else Move.Stay } .also { last = it } .let { current + it } } class SurroundObject(private var lastMove: Move, private var lastWallDirection: Move) : Movement { private val initialMovement: Movement = Bouncing(lastMove) private enum class State { Searching, Surrounding } private var state = State.Searching override fun next(world: World, current: Coordinate): Coordinate = if (state == State.Searching) { val nextPosition = initialMovement.next(world, current) if (current + lastMove == nextPosition) nextPosition else { lastWallDirection = lastMove lastMove = lastWallDirection.orthogonal().shuffled().first() state = State.Surrounding nextBySurrounding(world, current) } } else { nextBySurrounding(world, current) } private fun nextBySurrounding(world: World, current: Coordinate): Coordinate = if (world.isPassable(current + lastMove) && !world.isPassable(current + lastWallDirection)) { current + lastMove } else if (world.isPassable(current + lastWallDirection)) { lastWallDirection = lastMove.reverse() lastMove = lastWallDirection current + lastWallDirection } else if (!world.isPassable(current + lastMove) && world.isPassable(current + lastWallDirection.reverse())) { lastWallDirection = lastMove lastMove = lastWallDirection.reverse() current + lastWallDirection.reverse() } else { lastMove = lastMove.reverse() lastWallDirection = lastWallDirection.reverse() current + lastMove.reverse() } } data class ActingState( val ticks: Int, val current: Int = 1 ) { val canAct: Boolean = ticks == current fun tick() = ActingState(ticks, if (current < ticks) current + 1 else 1) } data class Entity( val id: String, val tile: Tile, val coordinate: Coordinate, val state: ActingState, val movement: Movement ) data class Field( val ground: Tile, val base: Tile, ) { companion object { fun of(tile: Tile) = Field(ground = tile, base = Tile.Empty) fun ofSymbols(symbols: String): List<Field> = symbols.map { of( when (it) { '.' -> Tile.Grass '#' -> Tile.Stone '*' -> Tile.Tree else -> Tile.Empty } ) } } } @Lenses data class World( val fields: List<Field> ) { companion object { const val MAX_X: Int = 40 const val MAX_Y: Int = 25 const val size: Int = MAX_X * MAX_Y } fun getStartCoordinate(): Coordinate = Coordinate.of(fields.withIndex().filter { (_, field) -> field.base == Tile.Empty && field.ground.ordinal < 3 } .shuffled().first().index) fun inBounds(coordinate: Coordinate) = coordinate.x >= 0 && coordinate.x < MAX_X && coordinate.y >= 0 && coordinate.y < MAX_Y fun isPassable(coordinate: Coordinate) = if (inBounds(coordinate)) { fields[coordinate.index].let { it.base == Tile.Empty && (it.ground == Tile.Empty || it.ground == Tile.Grass || it.ground == Tile.StompedGrass) //it.base == Tile.Empty && (it.ground == Tile.Empty || it.ground == Tile.Grass) } } else false fun update(old: Entity, new: Entity): World = World(fields.mapIndexed { index, field -> if (new.coordinate.index == index) field.copy(base = new.tile) else if (old.coordinate.index == index) field.copy( ground = if (field.ground == Tile.Grass) Tile.StompedGrass else field.ground, base = Tile.Empty ) else field }) fun clearEntities() = World(fields.map { it.copy(if (it.ground == Tile.StompedGrass) Tile.Grass else it.ground, Tile.Empty) }) } @Lenses data class GameState( val world: World, val entities: List<Entity>, ) { companion object } fun generateWorld(): World { val fields = generateSequence { when (Random.nextInt(0, 32)) { 5, 6, 7, 8 -> Tile.Tree 14 -> Tile.Stone else -> Tile.Grass } }.take(World.MAX_Y * World.MAX_X).map { Field.of(it) }.toList() return World(fields) } fun generateGrassWorld(): World = World(generateSequence { Tile.Grass }.take(World.MAX_Y * World.MAX_X).map { Field.of(it) }.toList()) fun neighboursOf(index: Int): List<Int> = with(Coordinate.of(index)) { neighbours .map { this + it } .filter { it.x >= 0 && it.x < World.MAX_X && it.y >= 0 && it.y < World.MAX_Y } .map { it.index } } fun neighboursFourOf(index: Int): List<Int> = with(Coordinate.of(index)) { neighboursFour .map { this + it } .filter { it.x >= 0 && it.x < World.MAX_X && it.y >= 0 && it.y < World.MAX_Y } .map { it.index } } fun blockedNeighboursOf(index: Int, fields: List<Field>): Int = neighboursOf(index).let { (neighbours.size - it.size) + it .map { fields[it] } .filter { it.ground != Tile.Grass } .size } fun applyCellularAutomata(world: World): World = world.copy(fields = world.fields.mapIndexed { index, _ -> Field.of(if (blockedNeighboursOf(index, world.fields) > 4) Tile.Stone else Tile.Grass) }) fun generateInitialWorld(): World { val indexOfStones = (0 until World.size).shuffled().take((World.size * 0.55).toInt()).toHashSet() return generateGrassWorld().let { it.copy(fields = it.fields.withIndex().map { (index, field) -> if (indexOfStones.contains(index)) Field.of(Tile.Stone) else field }) } } fun generateCellularWorld(times: Int): World { val initial = generateInitialWorld() return (0 until times).fold(initial) { world, _ -> applyCellularAutomata(world) } } fun erosion(world: World): World { return world.copy(fields = world.fields.withIndex().map { (index, field) -> if(field.ground != Tile.Grass && neighboursOf(index).any { world.fields[it].ground == Tile.Grass }) Field.of(Tile.Grass) else field }) } fun dilattation(world: World): World { return world.copy(fields = world.fields.withIndex().map { (index, field) -> if(field.ground == Tile.Grass && neighboursOf(index).any { world.fields[it].ground != Tile.Grass }) Field.of(Tile.Stone) else field }) } fun removeGnubbels(world: World): World { return world.copy(fields = world.fields.withIndex().map { (index, field) -> if(field.ground != Tile.Grass && neighboursFourOf(index).filter { world.fields[it].ground == Tile.Grass }.count() > 2) Field.of(Tile.Grass) else field }) } // 16 x 16 fun getDemoWorld() = World( buildList { addAll(Field.ofSymbols(".....##.........")) addAll(Field.ofSymbols(".....#......####")) addAll(Field.ofSymbols(".....#..........")) addAll(Field.ofSymbols("................")) addAll(Field.ofSymbols(".......###......")) addAll(Field.ofSymbols("*.....#####.....")) addAll(Field.ofSymbols("......####......")) addAll(Field.ofSymbols("................")) addAll(Field.ofSymbols(".......**.......")) addAll(Field.ofSymbols("......*****.....")) addAll(Field.ofSymbols("....***...****..")) addAll(Field.ofSymbols(".....**..***....")) addAll(Field.ofSymbols("..........****..")) addAll(Field.ofSymbols(".......#........")) addAll(Field.ofSymbols(".......###......")) addAll(Field.ofSymbols(".......#.###....")) } )
0
Kotlin
0
1
6850193ca4902c55b4d4bcaea71f8c63bffa89fe
13,101
wimmel-fritz
MIT License
src/main/kotlin/wk269/Problem3.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package wk269 import kotlin.math.min fun main() { val result = Problem3().minimumDeletions(intArrayOf(1, 2)) println(result) } class Problem3 { fun minimumDeletions(nums: IntArray): Int { // Find indices of min and max elements var minIndex = 0 var maxIndex = 0 for ((index, num) in nums.withIndex()) { if (num > nums[maxIndex]) maxIndex = index if (num < nums[minIndex]) minIndex = index } // Find in what order min and max elements appear in the array val first = if (minIndex < maxIndex) minIndex else maxIndex val second = if (minIndex > maxIndex) minIndex else maxIndex // There are 3 cases when we can remove 2 elements: // 1. Remove all elements from the first appeared element to the right. // It will include both elements in any case: // _ _ // 2,1,3,6,5 // |_______ val removeLessToTheLeft = first + 1 // 2. Remove all elements from the second appeared element to the left. // It will include both elements in any case: // _ _ // 2,1,3,6,5 // _______| val removeLessToTheRight = nums.size - first // 3. Remove all elements from the first to the left // and from the second to the right // _ _ // 2,1,3,6,5 // ___| |___ val removeBiggerToTheLeft = second + 1 val removeBiggerToTheRight = nums.size - second // Then just find the minimum between all 3 cases: return min( removeLessToTheLeft + removeBiggerToTheRight, min(removeLessToTheRight, removeBiggerToTheLeft) ) } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
1,714
leetcode-kotlin
MIT License
src/main/kotlin/g2601_2700/s2654_minimum_number_of_operations_to_make_all_array_elements_equal_to_1/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2654_minimum_number_of_operations_to_make_all_array_elements_equal_to_1 // #Medium #Array #Math #Number_Theory #2023_07_20_Time_172_ms_(100.00%)_Space_35.3_MB_(100.00%) class Solution { fun minOperations(nums: IntArray): Int { var g = nums[0] var list = mutableListOf<Int>() var padding = 0 var result = nums.size for (i in 0 until nums.size) { val n = nums[i] if (n == 1) { result-- } g = gcd(g, n) if (i == nums.size - 1) continue val m = nums[i + 1] list.add(gcd(m, n)) } if (g > 1) return -1 while (!list.any { it == 1 }) { padding++ val nlist = mutableListOf<Int>() for (i in 0 until list.size - 1) { val n = list[i] val m = list[i + 1] nlist.add(gcd(m, n)) } list = nlist } return result + padding } private fun gcd(a: Int, b: Int): Int = if (b != 0) gcd(b, a % b) else a }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,103
LeetCode-in-Kotlin
MIT License
src/Day22.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import utils.Coord2DInt import kotlin.math.max class Day22 { enum class Direction(val movement: Coord2DInt, val value: Int) { RIGHT(Coord2DInt(0, 1), 0), DOWN(Coord2DInt(1, 0), 1), LEFT(Coord2DInt(0, -1), 2), UP(Coord2DInt(-1, 0), 3) } companion object { val part1 = Part1() val part2 = Part2() private fun rotate(direction: Direction, rotate: Int): Direction { return Direction.values()[(direction.value + rotate + Direction.values().size) % Direction.values().size] } } class Part1 { data class Stage2D( val rowRange: List<Pair<Int, Int>>, val colRange: List<Pair<Int, Int>>, val grid: List<String> ) fun buildStage2D(grid: List<String>): Stage2D { val rowRange = grid.map { row -> row.indexOfFirst { it == '.' || it == '#' } to row.indexOfLast { it == '.' || it == '#' } }.toList() val colRange = mutableListOf<Pair<Int, Int>>() for (i in 0 until grid.maxOf { it.length }) { val col = grid.map { if (i >= it.length) ' ' else it[i] } colRange += col.indexOfFirst { it == '.' || it == '#' } to col.indexOfLast { it == '.' || it == '#' } } return Stage2D(rowRange, colRange, grid) } fun traverse2D(stage: Stage2D, steps: List<Int>, rotations: List<Int>): Pair<Coord2DInt, Direction> { var position = Coord2DInt(0, stage.rowRange[0].first) var direction = Direction.RIGHT var i = 0 while (i < max(steps.size, rotations.size)) { if (i < steps.size) { val step = steps[i] for (j in 0 until step) { val newPos = move2D(position, direction, stage) if (newPos != position) { position = newPos } } } if (i < rotations.size) { direction = rotate(direction, rotations[i]) } i++ } return position to direction } private fun move2D(position: Coord2DInt, direction: Direction, stage: Stage2D): Coord2DInt { val newPos = position + direction.movement if (direction == Direction.UP || direction == Direction.DOWN) { if (newPos.x < stage.colRange[newPos.y].first) newPos.x = stage.colRange[newPos.y].second // loop from top to bottom if (newPos.x > stage.colRange[newPos.y].second) newPos.x = stage.colRange[newPos.y].first // loop from bottom to top } if (direction == Direction.LEFT || direction == Direction.RIGHT) { if (newPos.y < stage.rowRange[newPos.x].first) newPos.y = stage.rowRange[newPos.x].second // loop from left to right if (newPos.y > stage.rowRange[newPos.x].second) newPos.y = stage.rowRange[newPos.x].first // loop from right to left } return if (stage.grid[newPos.x][newPos.y] == '#') position else newPos // can't move if there's a wall } } class Part2 { data class Stage3D(val faces: Map<Char, Array<CharArray>>) data class Position3D(val face: Char, val coord: Coord2DInt, val direction: Direction) fun buildStage3D(grid: List<String>, net: List<String>, size: Int): Stage3D { val result = mutableMapOf<Char, Array<CharArray>>() for(i in net.indices) { for (j in net[i].indices) { if (net[i][j] == ' ') continue val face = Array(size) { CharArray(size) } for (x in 0 until size) { for (y in 0 until size) { face[x][y] = grid[i * size + x][j * size + y] } } result += net[i][j] to face } } return Stage3D(result) } fun traverse3D(stage: Stage3D, size: Int, steps: List<Int>, rotations: List<Int>): Position3D { var position = Position3D( 'U', Coord2DInt(0, 0), Direction.RIGHT ) var i = 0 while (i < max(steps.size, rotations.size)) { if (i < steps.size) { val step = steps[i] for (j in 0 until step) { val newPos = move3D(position, size, stage) if (newPos != position) { position = newPos } } } if (i < rotations.size) { position = Position3D( position.face, position.coord, rotate(position.direction, rotations[i]) ) } i++ } return position } private fun move3D(position: Position3D, size: Int, stage3D: Stage3D): Position3D { val newPos = position.coord + position.direction.movement if (newPos.x in 0 until size && newPos.y in 0 until size) { // not moving to adjacent face return Position3D( position.face, if (stage3D.faces[position.face]!![newPos.x][newPos.y] == '#') position.coord else newPos, position.direction ) } return faceTransition(position, size - 1, stage3D) } // Only works private fun faceTransition(position: Position3D, lastIndex: Int, stage3D: Stage3D): Position3D { val newFace = when (position.direction) { Direction.UP -> when(position.face) { 'B' -> 'L' in listOf('L', 'D') -> 'F' 'F' -> 'U' in listOf('U', 'R') -> 'B' else -> throw IllegalArgumentException("Cannot parse ${position.face} next face") } Direction.DOWN -> when(position.face){ 'B' -> 'R' in listOf('L', 'D') -> 'B' 'F' -> 'D' in listOf('U', 'R') -> 'F' else -> throw IllegalArgumentException("Cannot parse ${position.face} next face") } Direction.LEFT -> when(position.face) { in listOf('U', 'F', 'D') -> 'L' in listOf('L', 'B', 'R') -> 'U' else -> throw IllegalArgumentException("Cannot parse ${position.face} next face") } Direction.RIGHT -> when(position.face) { in listOf('U', 'F', 'D') -> 'R' in listOf('L', 'B', 'R') -> 'D' else -> throw IllegalArgumentException("Cannot parse ${position.face} next face") } } val faceRotation = faceRotation(position.face, newFace) val newPos = when(position.direction) { Direction.UP -> when(faceRotation) { 0 -> Coord2DInt( lastIndex, position.coord.y ) 1 -> Coord2DInt( position.coord.y, 0 ) else -> throw IllegalArgumentException("Cannot parse ${position.face} going ${position.direction}") } Direction.DOWN -> when (faceRotation) { 0 -> Coord2DInt( 0, position.coord.y ) 1 -> Coord2DInt( lastIndex - position.coord.y, lastIndex ) else -> throw IllegalArgumentException("Cannot parse ${position.face} going ${position.direction}") } Direction.LEFT -> when (faceRotation) { 0 -> Coord2DInt( position.coord.x, lastIndex ) -1 -> Coord2DInt( 0, position.coord.x ) 2 -> Coord2DInt( lastIndex - position.coord.x, 0 ) else -> throw IllegalArgumentException("Cannot parse ${position.face} going ${position.direction}") } Direction.RIGHT -> when (faceRotation) { 0 -> Coord2DInt( position.coord.x, 0 ) -1 -> Coord2DInt( lastIndex, position.coord.x ) 2 -> Coord2DInt( lastIndex - position.coord.x, lastIndex ) else -> throw IllegalArgumentException("Cannot parse ${position.face}") } } return if (stage3D.faces[newFace]!![newPos.x][newPos.y] == '#') position else Position3D( newFace, newPos, rotate(position.direction, faceRotation) ) } private fun faceRotation(from: Char, to: Char): Int { val map = mapOf( ('U' to 'L') to 2, ('D' to 'R') to 2, ('L' to 'U') to 2, ('R' to 'D') to 2, ('U' to 'B') to 1, ('D' to 'B') to 1, ('L' to 'F') to 1, ('R' to 'F') to 1, ('B' to 'U') to -1, ('B' to 'D') to -1, ('F' to 'L') to -1, ('F' to 'R') to -1 ) return map[from to to] ?: 0 } } } fun main() { fun part1(input: List<String>): Int { val grid = input.filter { it.contains(Regex("[.#]")) } val path = input.first { it.contains(Regex("[\\d\\w]")) } val (coord, direction) = Day22.part1.traverse2D( Day22.part1.buildStage2D(grid), Regex("\\d+").findAll(path).map { it.value.toInt() }.toList(), Regex("[LR]").findAll(path).map { if (it.value == "L") -1 else 1 }.toList() ) println("$direction, (${coord.x + 1}, ${coord.y + 1}") return 1000 * (coord.x + 1) + 4 * (coord.y + 1) + direction.value } fun part2(input: List<String>, net: List<String>, size: Int): Int { val grid = input.filter { it.contains(Regex("[.#]")) } val path = input.first { it.contains(Regex("[\\d\\w]")) } val stage = Day22.part2.buildStage3D(grid, net, size) val (face, position, direction) = Day22.part2.traverse3D( stage, size, Regex("\\d+").findAll(path).map { it.value.toInt() }.toList(), Regex("[LR]").findAll(path).map { if (it.value == "L") -1 else 1 }.toList() ) for (i in net.indices) { for (j in net[i].indices) { if (net[i][j] == face) { val row = i * size + position.x + 1 val col = j * size + position.y + 1 println("$direction ($row, $col)") return row * 1000 + col * 4 + direction.value } } } return 0 } val test = readInput("Day22_test") println("=== Part 1 (test) ===") println(part1(test)) val testNet = readInput("Day22_test_net") println("=== Part 2 (test) ===") println(part2(test, testNet, 4)) val input = readInput("Day22") val net = readInput("Day22_net") println("=== Part 1 (puzzle) ===") println(part1(input)) println("=== Part 2 (puzzle) ===") println(part2(input, net, 50)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
12,274
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountGoodNumbers.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD /** * 1922. Count Good Numbers * @see <a href="https://leetcode.com/problems/count-good-numbers">Source</a> */ fun interface CountGoodNumbers { operator fun invoke(n: Long): Int } class CountGoodNumbersImpl : CountGoodNumbers { override fun invoke(n: Long): Int { return powerMod(5, n.plus(1).div(2), MOD).times( powerMod(4, n / 2, MOD), ).mod(MOD) } private fun powerMod(a: Int, b: Long, mod: Int): Long { if (b == 0L) { return 1 } val x = powerMod(a, b / 2, mod) return if (b % 2 == 0L) { x.times(x).mod(mod).toLong() } else { a.times(x).mod(mod).times(x).mod(mod).toLong() } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,397
kotlab
Apache License 2.0
src/Day09.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
import kotlin.math.abs import kotlin.math.max import kotlin.math.sign fun main() { data class Coords( val column: Int, val row: Int, ) { fun distance(other: Coords): Int { return max(abs(column - other.column), abs(row - other.row)) } } fun part1(input: List<String>): Int { data class Visits( val head: Int = 0, val tail: Int = 0, ) operator fun Visits?.plus(other: Visits): Visits { return this?.let { it.copy(it.head + other.head, it.tail + other.tail) } ?: other } val startpath = mutableMapOf<Coords, Visits>() var coords = Coords(0, 0) var tailCoords = Coords(0, 0) startpath[coords] = Visits(1, 1) for (line in input) { val line = line.split(" ") val command = line[0] val amount = line[1].toInt() when (command) { "U" -> { var target = coords.copy(column = coords.column + amount) for (i in 1..amount) { coords = coords.copy(column = coords.column + 1) startpath[coords] = startpath[coords] + Visits(head = 1) if (coords.distance(tailCoords) >= 2) { if (tailCoords.row == coords.row) { tailCoords = tailCoords.copy(column = tailCoords.column + 1) } else { tailCoords = tailCoords.copy(column = tailCoords.column + 1, row = coords.row) } startpath[tailCoords] = startpath[tailCoords] + Visits(tail = 1) } } } "L" -> { var target = coords.copy(row = coords.row - amount) for (i in 1..amount) { coords = coords.copy(row = coords.row - 1) startpath[coords] = startpath[coords] + Visits(head = 1) if (coords.distance(tailCoords) >= 2) { if (tailCoords.column == coords.column) { tailCoords = tailCoords.copy(row = tailCoords.row - 1) } else { tailCoords = tailCoords.copy(column = coords.column, row = tailCoords.row - 1) } startpath[tailCoords] = startpath[tailCoords] + Visits(tail = 1) } } } "R" -> { var target = coords.copy(row = coords.row + amount) for (i in 1..amount) { coords = coords.copy(row = coords.row + 1) startpath[coords] = startpath[coords] + Visits(head = 1) if (coords.distance(tailCoords) >= 2) { if (tailCoords.column == coords.column) { tailCoords = tailCoords.copy(row = tailCoords.row + 1) } else { tailCoords = tailCoords.copy(column = coords.column, row = tailCoords.row + 1) } startpath[tailCoords] = startpath[tailCoords] + Visits(tail = 1) } } } "D" -> { var target = coords.copy(column = coords.column - amount) for (i in 1..amount) { coords = coords.copy(column = coords.column - 1) startpath[coords] = startpath[coords] + Visits(head = 1) if (coords.distance(tailCoords) >= 2) { if (tailCoords.row == coords.row) { tailCoords = tailCoords.copy(column = tailCoords.column - 1) } else { tailCoords = tailCoords.copy(column = tailCoords.column - 1, row = coords.row) } startpath[tailCoords] = startpath[tailCoords] + Visits(tail = 1) } } } } } return startpath.values.filter { it.tail > 0 }.count() } fun moveTail(coords: MutableList<Coords>, tail: Int) { val previousKnot = coords[tail - 1] val current = coords[tail] val difference = Coords(column = previousKnot.column - current.column, row = previousKnot.row - current.row) coords[tail] = coords[tail].copy( column = current.column + difference.column.sign, row = current.row + difference.row.sign ) } fun part2(input: List<String>): Int { data class Visits( val head: Int = 0, val tail: Int = 0, ) operator fun Visits?.plus(other: Visits): Visits { return this?.let { it.copy(it.head + other.head, it.tail + other.tail) } ?: other } val startpath = mutableMapOf<Coords, Visits>() var coords = (1..10).map { Coords(0, 0) }.toMutableList() startpath[coords[9]] = Visits(1, 1) for (line in input) { val line = line.split(" ") val command = line[0] val amount = line[1].toInt() when (command) { "U" -> { for (i in 1..amount) { coords[0] = coords[0].copy(column = coords[0].column + 1) for (tail in 1..9) { if (coords[tail - 1].distance(coords[tail]) >= 2) { moveTail(coords, tail) } } startpath[coords[9]] = startpath[coords[9]] + Visits(tail = 1) } } "L" -> { for (i in 1..amount) { coords[0] = coords[0].copy(row = coords[0].row - 1) for (tail in 1..9) { if (coords[tail - 1].distance(coords[tail]) >= 2) { moveTail(coords, tail) } } startpath[coords[9]] = startpath[coords[9]] + Visits(tail = 1) } } "R" -> { for (i in 1..amount) { coords[0] = coords[0].copy(row = coords[0].row + 1) for (tail in 1..9) { if (coords[tail - 1].distance(coords[tail]) >= 2) { moveTail(coords, tail) } } startpath[coords[9]] = startpath[coords[9]] + Visits(tail = 1) } } "D" -> { for (i in 1..amount) { coords[0] = coords[0].copy(column = coords[0].column - 1) for (tail in 1..9) { if (coords[tail - 1].distance(coords[tail]) >= 2) { moveTail(coords, tail) } } startpath[coords[9]] = startpath[coords[9]] + Visits(tail = 1) } } } println(startpath) } return startpath.values.filter { it.tail > 0 }.count().also { println(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d7ab334f38a9e260c72725d3f583228acb6aa0e
8,067
advent-2022
Apache License 2.0
src/main/kotlin/Day-7.kt
joebutler2
577,057,170
false
{"Kotlin": 5432}
import java.util.Stack interface IOObject { fun getBaseName(): String fun calculateSize(): Int } // Composite class Dir : IOObject { private var children: MutableList<IOObject> = mutableListOf() var name: String constructor(name: String) { this.name = name } override fun getBaseName(): String = name override fun calculateSize(): Int = children.sumOf { it.calculateSize() } fun addChild(child: IOObject) = children.add(child) fun findChild(dirName: String): Dir = children.filterIsInstance<Dir>().first { it.name == dirName } fun allDirsUnder(size: Int): List<Dir> = allDirsUnder(mutableListOf(), size) fun allDirsUnder(matches: MutableList<Dir>, size: Int): List<Dir> { children.forEach { if (it is Dir) { if(it.calculateSize() < 100000) { matches.add(it) } it.allDirsUnder(matches, size) } } return matches } } // Leaf class File : IOObject { var size: Int = 0 var name: String constructor(name: String) { this.name = name } override fun getBaseName(): String = name override fun calculateSize(): Int = size } val root = Dir("root") val pathToWorkingDirectory: Stack<Dir> = Stack() fun main() { val input = object {}.javaClass.getResourceAsStream("day-7.txt")?.bufferedReader()?.readLines()!!.iterator() input.next() // skip first line since we already start at the root pathToWorkingDirectory.push(root) while (input.hasNext()) { val line = input.next() println("Processing line: $line") val segments = line.split(" ") if (line.startsWith("$")) { if (line.contains("cd")) { changeDirectory(segments[2]) } } else { parseListedDirectory(line) } } val matchingDirs = root.allDirsUnder(100000) val totalSize = matchingDirs.sumOf { it.calculateSize() } println("And the total is... ${totalSize}") } fun parseListedDirectory(line: String) { println("Processing listed dir: $line") val (label, name: String) = line.split(" ") if (label.startsWith("d")) { val dir = Dir(name) pathToWorkingDirectory.peek().addChild(dir) } else if (label[0].isDigit()) { val file = File(name) file.size = label.toInt() pathToWorkingDirectory.peek().addChild(file) } } private fun changeDirectory(path: String) { if (path == "..") { pathToWorkingDirectory.pop() } else { val newDir = pathToWorkingDirectory.peek().findChild(path) pathToWorkingDirectory.push(newDir) } }
0
Kotlin
0
0
7abdecbc4a4397f917c84bd8d8b9f05fb7079c75
2,714
advent-of-code-kotlin
MIT License
src/Day08.kt
an4
575,331,225
false
{"Kotlin": 117105}
fun main() { fun part1(input: List<String>): Int { val matrix = Array(input.size) { IntArray(input[0].length) } for (row in input.indices) { val charArr = input[row].toCharArray() for (column in charArr.indices) { matrix[row][column] = charArr[column].digitToInt() } } val seen = Array(input.size) { BooleanArray(input[0].length) } // N for (c in matrix[0].indices) { var maxHeight = -1 for (r in matrix.indices) { if (matrix[r][c] > maxHeight) { seen[r][c] = true maxHeight = matrix[r][c] } } } // W for (r in matrix.indices) { var maxHeight = -1 for (c in matrix[r].indices) { if (matrix[r][c] > maxHeight) { seen[r][c] = true maxHeight = matrix[r][c] } } } // S for (c in matrix[0].indices) { var maxHeight = -1 for (r in matrix.indices.reversed()) { if (matrix[r][c] > maxHeight) { seen[r][c] = true maxHeight = matrix[r][c] } } } // E for (r in matrix.indices) { var maxHeight = -1 for (c in matrix[r].indices.reversed()) { if (matrix[r][c] > maxHeight) { seen[r][c] = true maxHeight = matrix[r][c] } } } var seenCount = 0 for(r in seen.indices) { for (c in seen[r].indices) { if (seen[r][c]) { seenCount++ } } } // for (r in matrix.indices) { // for (c in matrix[r].indices) { // print(matrix[r][c]) // } // println() // } // println() // // for (r in seen.indices) { // for (c in seen[r].indices) { // print(if (seen[r][c]) 1 else 0) // } // println() // } return seenCount } fun computeViewingDistance(r: Int, c: Int, matrix: Array<IntArray>): Int { val height = matrix[r][c] // N var northViewingDistance = 0 var i = r-1 while (i >= 0 && matrix[i][c] < height) { northViewingDistance++ i-- } if (i != -1) { northViewingDistance++ } // W var westViewingDistance = 0 i = c-1 while (i >= 0 && matrix[r][i] < height) { westViewingDistance++ i-- } if (i != -1) { westViewingDistance++ } // S var southViewingDistance = 0 i = r+1 while (i <= matrix.size-1 && matrix[i][c] < height) { southViewingDistance++ i++ } if (i != matrix.size) { southViewingDistance++ } // E var eastViewingDistance = 0 i = c+1 while (i <= matrix[r].size-1 && matrix[r][i] < height) { eastViewingDistance++ i++ } if (i != matrix[r].size) { eastViewingDistance++ } return northViewingDistance * westViewingDistance * southViewingDistance * eastViewingDistance } fun part2(input: List<String>): Int { val matrix = Array(input.size) { IntArray(input[0].length) } for (row in input.indices) { val charArr = input[row].toCharArray() for (column in charArr.indices) { matrix[row][column] = charArr[column].digitToInt() } } var maxViewingDistance = 0 var tempViewingDistance: Int for (r in matrix.indices) { for (c in matrix[r].indices) { tempViewingDistance = computeViewingDistance(r, c, matrix) if (maxViewingDistance < tempViewingDistance) { maxViewingDistance = tempViewingDistance } } } return maxViewingDistance } val rawInput = "200210101302123001201232003214413304042424024222111455334421333412020113121332322101331130101222121,120100002010203210130421301201404231101254535242322112224524254031333224202413331320010302202022220,001200100200133300103241144403033124133341435524324143423341133252144040000423121430200100022211211,000012321202320024030320421230202213131514345325422513145221212451233202023402411040301113132131121,111103022312211340103042313022513413532253114352113252432213335135141552003023313142423321320321212,012112331020102411442404102132241553154421513555415233312432515445154422402444314033003303323320102,200110201230142322043222345241215442224221523534521123322555135454422121142320102300340211100120310,120012121330311223132012342543213553334431544155643463443115441515143121132442433102420433301221030,232202001121031432403445341332243414414443326545556526423425612114153351234111432130314202330220010,133033302004430221300431213144135422424546344243432363665246244341243432352514332142044434023131003,323030003440212122341123551231453352464334362343245665335563565343421512431425213111441304340011231,003000034413321402514254435224115366533425244663634336625232232553226312522142535212414040004113221,203203234020411021411532552144456644553434362455342664624546642245543563524451523133334201141411113,103032442424101341214421543433253563535422262333555222632224462463423526635422354541113034433423000,020133314440123532124351233325245665424345546323747756264656566346366665333444354252523314300303020,303102341103425544443131253325266522334544545666744335557473366256323634266213415324324341134211112,023044020203451414535535625633224445223364357435363343536455577666362444542245113553311434011140201,130031020304324235255516652533544625454347643363434554557436654343442356543323225524232341230421320,220403302205252431242554332553635575345744474647573376655365465333365246645632425211423335322131241,214400202003451322143346242334324356456753434655775663756755654555657245563342333124515412311131042,144333342021131124452334346355653767663565565443573444757577736363654665266666525633314514341134041,111433243134224443344522523636635556736633645434676475377437457745566744646666544632522235344014021,421102342525325521256266235434736567476654664744455647574564433767653357626264235361354533341223334,030103204353142134336562363447366767454375766855756788856466566674566447433523254456444314525331002,410404421315115456635435323737634573668554668666466474777667486334467637567356564452622223212300033,012140231351312622653242266664756743747655464548677545754787855754646777456542663563451151125130001,122202541435443225443523376367336378575474446665666578564485767586653557636553243543226514123433024,322341213145516625463356665437453687675788656768568586885644456856643777435654242663525154214512210,140223342343464363346556333753354858857777544686557677466886555488585473373334765233552623543312200,422403124152143243445554363655577858878487546898958587796787475657654747656366532662626445424424410,321231255223524234247766447646866656646454795565859795788557647554485844673466335434256341522445230,434145334313623446664556646655886667557495589675986998765976684664875654474437775454342445551523513,433432522546645452345446344376857768848989787655576756768988889768856644743374354326655353222112422,420512322415655344574666457745755754768778785979569655887679799664764746786677655366663463434125353,124155335466242262756735466446866676986698997576575557966855895697587767454454543472442666623435524,415345153363443642766655644464854747967899588766957797576697788779586574578644737774624632644545113,441333524323362443745375688445665755769658789797769878578585579797547585786676677364322333511241423,434241414244556353633455448684455597576765697869997689879755769799778646786856633667554436244553435,245314523664342366643466667485888767568897999988699997889967759988686546445685776346654553265354523,321432211425653366363657657447568665877957979987786779697868577888595675855456734636524456425431142,033422313632342655364345567644755898785796699996888776886796657757797857688876376354363532536232314,052242355542323647576334458576689579586968867996689878797799969587659875547656644765646363224253444,234434342653226546436658855775896968867876797997996768779677667699889796745768337366436634632245213,445222213235346735753667755676669878598898697986687998696976996987769858656476757667332332625351514,435355546442363575345376588657989988589877788898987788998987888969858697674677876744344654353312151,133553556352633665357787686775799577779997878787787897797699998878965787455885663557545355624324115,545233354544544435573376578458655587598789677877787899897869896658788766588656837747764363655341521,211555453542466735366787685658866856979676887788987997989769978968996968546685834576542622243213155,144113123264426777463777488587699869767977889987787997788887696979756858576885677473635653233543243,311313235543366635754558457576795998769778679778889889889987668888968988774448543757733325643231422,443355342254425446767468656476595865887986787897998879979969967775865587546587644777655235234324344,442443355324564334365767887885668589686866989997898887797879967668978575855866836656334552623632351,413433144665547465436464847768768777996977968777788977797977679895685768676556634643436422334442455,453142566345254453333444885587565578677688779977889999789888796877778557847675867477652535546215422,151332265265444777364585745778956687969888787989789897978868788787686655764465553577745632625231455,445223254646322766445774546689887968566967668798798897976876999668956869458456654344465452425345523,354122314463434747436654644484979696677686898978887878797976779669677694454485555635752664656513133,012232355266625635373378685656767767887668769986988989987778777769685698467858437754343553255322444,024555213224464774353435485656687879797989768686778867676969798596899575656786466333455553355345234,132432444233664544676735848585667856997869777886887797667989767578765688576686457343436442546533142,444143435624244477333448558448667577665667766788798979786987858959699677748784665774745235262414311,231541231646652273467743578658756967656599897986666898787998598868878558884847373763743436333442222,452115141256244235637554556584849575796768969699769887767797597866989785545764765437552564345131455,425244513366263336575446588857846976888767658868676696667958899568857767458773744637333452423533532,105131435443626324576435676555478786567757999689999668897789599599856875674774656477364623225123151,032315232453426453465765574644575446896598678899586759777588775565758668474745575344566425615355433,414341314426235264647543645746457657967695558965975769898785985654576867658657635475666624352134144,100323311242236242255347744575476776858879688698797878579969975874748675444573747344653555211352221,014311441544336355454575445686757688689666888758996965685596966444845578855576543546465554243154142,342254542123656656546356366778675574845697675569556687688586558646447667434456665352633422255244414,211453143353434566563465675745864885674687588998996685977676784567474566434544466522533343353114231,313022332133466332336477634667465867888785648576775865668487487544484845366535575442326624351431012,114211155121535434243656644454647447848458486648876856858767458446765544736737656643222525432544232,010122525344156263354227756636434587458665676586887787858748554686666673755577552352343354534152040,412321535231542523462334653374657358685586488785485678564864446878734675557735423665442154552342011,104424333415333444626345536643374555557465464777678466847574454875666744474766234464241242553110441,124112314331255362622446225633636335345644866876474848854678487634655646573245644334324331251444400,312000445323443215433555564337345455776744675674478888474578745344363573744242633426233313351422233,430022234512251423424326264637465355355746637447648757857473743746654776525262553642221524414041323,233102134414232412332356226435465646465443546335436365365755446655434343246552323324433143130002111,111404313153153442123666355224747746356376564475444457353545546774737575424345446353354342244313412,234334440424325351212523232526466575445565545647676363335445774536647332224524363441415351434423203,123130340344441323432464644565445455655737653455763575457374566467753266262333355253144434121341413,032133414041244541233153446223224334665566654364436733465455436362242424353334354423444542342323120,331120000421342243325115456255364522626457536537755343436545747263466663636524533235411311121411332,332230404213303353133111256254363655255434744674474754434646343454354433433515513135334442222004010,202121313223222511453512322255566444565544643556454452443454524223535655434354335552444042314134332,213300030010040331541141441242645424354334635234565662362526354224246533454523242512414430303043302,303300002321212004244535244451242654252646636554662636263664646235263231315331142352102120130122303,331101014024440131342122251123415223633335635453354263636226636262256541131443215354304023243302102,331202033431032221244232125455313233642635432336534464333635335635423524411525215033323313120333013,033030202002100313111523432311242321352266332543436322536365535415434245433251242122313014031212313,222211100333332310242343252221251543414443226355325632364262625135251521332232522230244440201332023,000203310213011213412344315255131512335223453552465335425413252322422253334440310223340313231332020,011332231323130141310431031222132533232453353124412341254122255424331153344341340113311310010033130,010021033100310312123242131122524221555411455523421253253142545515323423322444300142424333201332021,110101220202201114310003401420513324334525253112533435355244442344311112421320024234333132222021000,020011123333222200003244032430305123255531342321413242534522552125444313014002424233330331130222200,100220000312023302114114440201033304323431155212155522541415515211123243000444221343002001121202102" // val rawInput = "30373,25512,65332,33549,35390" val input = rawInput.split((",")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df64adcc5d1ccab370acef01a7ed4d480ffbe2be
14,340
aoc22
Apache License 2.0
src/main/java/dev/haenara/mailprogramming/solution/y2020/m01/d26/Solution200126.kt
HaenaraShin
226,032,186
false
null
package dev.haenara.mailprogramming.solution.y2020.m01.d26 import dev.haenara.mailprogramming.solution.Solution /** * 매일프로그래밍 2020. 01. 26 * 정수 배열이 주어졌을 때, 오른쪽 원소가 왼쪽 원소보다 더 큰 경우 중 두 원소의 차가 최대가 되는 값을 찾으시오. * Input: [2, 7, 9, 5, 1, 3, 5] * Output: 7 (원소 2와 9) * * 풀이 * 문제의 조건대로 만약 두 원소의 차가 최대가 되는 경우는 둘중의 하나의 원소가 최소값 또는 최대값일 수밖에 없다. * 따라서 최소값이 나오는 경우와 최댓값이 나오는 경우를 찾아서 차이값을 갱신해나가면서 * 결과적으로 최대 차이값이 결정되는 순간을 찾는다. * 단 최소값이 좌측에 있어야 하므로, 새로운 최소값이 나오는 경우부터 새로 비교하면 된다. */ class Solution200126 : Solution<Array<Int>, Int>{ override fun solution(input: Array<Int>): Int { var currentMin = input[0] var currentMax = input[0] var currntDiff = currentMax - currentMin var maxDiff = currntDiff for (element in input) { if (currentMax < element) { currentMax = element currntDiff = currentMax - currentMin maxDiff = maxOf(currntDiff, maxDiff) } else if (currentMin > element) { currentMin = element currentMax = element currntDiff = 0 } } return maxDiff } }
0
Kotlin
0
7
b5e50907b8a7af5db2055a99461bff9cc0268293
1,558
MailProgramming
MIT License
src/Day01.kt
0nko
573,144,534
false
{"Kotlin": 1263}
fun getSums(input: List<String>): List<Int> { val sums = mutableListOf(0) input.forEach { if (it.isBlank()) { sums += 0 } else { sums[sums.lastIndex] += it.toInt() } } return sums } fun main() { fun part1(input: List<String>): Int { return getSums(input).max() } fun part2(input: List<String>): Int { return getSums(input).sorted().reversed().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4cd45703107377a05ee582ef7ed876c43b64f1ed
627
aoc2022
Apache License 2.0
src/aoc2021/Day11.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2021 import readInput fun main() { val (year, day) = "2021" to "Day11" fun navigate(input: List<String>, maxStep: Int = 0): Int { val energy = input.flatMap { line -> line.map { c -> c - '0' } }.toMutableList() var flashes = 0 var step = 0 while (true) { step++ val toFlash = ArrayDeque<Int>() energy.forEachIndexed { i, e -> energy[i] = e + 1 if (energy[i] == 10) { toFlash.addLast(i) } } val flashed = mutableSetOf<Int>() fun flash(index: Int) { flashed += index for (dx in -1..1) { for (dy in -1..1) { val x = index % 10 + dx val y = index / 10 + dy if (x in 0..9 && y in 0..9) { val p = y * 10 + x if (p !in flashed) { energy[p] += 1 if (energy[p] == 10) { toFlash.addLast(p) } } } } } } while (toFlash.isNotEmpty()) { val index = toFlash.removeFirst() energy[index] = 0 if (index !in flashed) { flash(index) } } flashes += flashed.size if (maxStep > 0 && step == maxStep) { return flashes } if (maxStep == 0 && flashed.size == 100) { return step } } return 0 } fun part1(input: List<String>) = navigate(input, maxStep = 100) fun part2(input: List<String>) = navigate(input) val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) check(part1(testInput) == 1656) println(part1(input)) check(part2(testInput) == 195) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,163
aoc-kotlin
Apache License 2.0
src/main/kotlin/g0701_0800/s0719_find_k_th_smallest_pair_distance/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0701_0800.s0719_find_k_th_smallest_pair_distance // #Hard #Array #Sorting #Binary_Search #Two_Pointers // #2023_02_27_Time_172_ms_(100.00%)_Space_37.2_MB_(100.00%) class Solution { fun smallestDistancePair(nums: IntArray, k: Int): Int { nums.sort() val length = nums.size val maxDiff = nums[length - 1] - nums[0] var start = 0 var end = maxDiff while (start < end) { val mid = start + (end - start) / 2 if (isPair(nums, mid, k)) { end = mid } else { start = mid + 1 } } return start } private fun isPair(nums: IntArray, mid: Int, k: Int): Boolean { var count = 0 var i = 0 for (j in 1 until nums.size) { while (nums[j] - nums[i] > mid) { i++ } count += j - i } return count >= k } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
947
LeetCode-in-Kotlin
MIT License
day21/kotlin/RJPlog/day2121_1_2.kts
razziel89
433,724,464
true
{"Rust": 368326, "Python": 219109, "Go": 200337, "Kotlin": 80185, "Groovy": 67858, "JavaScript": 45619, "TypeScript": 43504, "CSS": 35030, "Shell": 18611, "C": 5260, "Ruby": 2359, "Dockerfile": 2285, "HTML": 227, "C++": 153}
import java.io.File // tag::standardDice[] fun standardDice(in1: Int, in2: Int): Int { var play1 = in1 var play2 = in2 var play1Score: Int = 0 var play2Score: Int = 0 var dice: Int = 1 var diceCount = 0 while (play1Score < 1000 && play2Score < 1000) { // three turns player 1 for (i in 0..2) { play1 = ((play1 + dice - 1) % 10) + 1 dice = (dice) % 100 + 1 } diceCount += 3 play1Score = play1Score + play1 if (play1Score >= 1000) { return (play2Score * diceCount) } // three turns player 2 for (i in 0..2) { play2 = (play2 + dice - 1) % 10 + 1 dice = (dice) % 100 + 1 } diceCount += 3 play2Score = play2Score + play2 if (play2Score >= 1000) { return (play1Score * diceCount) } } return 1 } // end::standardDice[] // tag::diracDice[] fun diracDice(in1: Int, in2: Int, in3: List<Int>): Pair<Int, Long> { var play1 = in1 var play2 = in2 var play1Score: Int = 0 var play2Score: Int = 0 var dice = in3 var diceCount = 0 var numOfVars: Long = 1 var mapTable = mutableMapOf<Int, Int>() mapTable.put(3, 1) mapTable.put(4, 3) mapTable.put(5, 6) mapTable.put(6, 7) mapTable.put(7, 6) mapTable.put(8, 3) mapTable.put(9, 1) var i: Int = 0 while (true) { play1 = ((play1 + dice[i] - 1) % 10) + 1 numOfVars = numOfVars * mapTable.getValue(dice[i]) i += 1 diceCount += 3 play1Score = play1Score + play1 if (play1Score >= 21) { return Pair(1, numOfVars) } else if (i > dice.size - 1) { return Pair(0, 0) } play2 = (play2 + dice[i] - 1) % 10 + 1 numOfVars = numOfVars * mapTable.getValue(dice[i]) i += 1 diceCount += 3 play2Score = play2Score + play2 if (play2Score >= 21) { return Pair(2, numOfVars) } else if (i > dice.size - 1) { return Pair(0, 0) } } } // end::diracDice[] //fun main(args: Array<String>) { var t1 = System.currentTimeMillis() // tag::read_puzzle_input[] var startingSpace = mutableListOf<Int>() File("day2121_puzzle_input.txt").forEachLine { startingSpace.add(it.takeLast(1).toString().toInt()) } var play1 = startingSpace[0] var play2 = startingSpace[1] // end::read_puzzle_input[] // tag::part1[] var solution1 = standardDice(play1, play2) // end::part1[] // tag::part2[] var play1Wins: Long = 0 var play2Wins: Long = 0 var diceVarOverall = MutableList(0) { mutableListOf<Int>() } var diceVarOverallNew = MutableList(0) { mutableListOf<Int>() } var diceVariation = mutableListOf<Int>() for (ii in 3..9) { for (iii in 3..9) { diceVariation.add(ii) diceVariation.add(iii) diceVarOverall.add(diceVariation.toMutableList()) diceVariation.clear() println("-----------------") println("-- next turn --") println("-----------------") print(" diceVarOverall: ") println(diceVarOverall) while (diceVarOverall.isNotEmpty()) { diceVarOverall.forEach { var result = diracDice(play1, play2, it) if (result.first == 1) { play1Wins = play1Wins + result.second } else if (result.first == 2) { play2Wins = play2Wins + result.second } else if (result.first == 0) { for (i in 3..9) { var diceVariationNew = it.toMutableList() diceVariationNew.add(i) diceVarOverallNew.add(diceVariationNew.toMutableList()) // diceVariationNew.clear() } } } diceVarOverall.clear() diceVarOverall.addAll(diceVarOverallNew) diceVarOverallNew.clear() } // end While (diceVarOverall.isNotEmpty()) println() } } var solution2 = maxOf(play1Wins, play2Wins) // end::part2[] // tag::output[] // print solution for part 1 println("*******************************") println("--- Day 21: <NAME> ---") println("*******************************") println("Solution for part1") println(" $solution1 you get if you multiply the score of the losing player by the number of times the die was rolled during the game") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 are the most wins in all universes") println() // end::output[] t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") //}
1
Rust
0
0
0042891cfcecdc2b65ee32882bd04de80ecd7e1c
4,170
aoc-2021
MIT License
src/commonMain/kotlin/io/schlawiner/game/Score.kt
schl4win3r
658,803,928
false
{"Kotlin": 74826}
package io.schlawiner.game import io.schlawiner.game.Score.Companion.EMPTY // use String instead of Term here, since the 'term' could also be "skipped" or "timeout" data class Score(val term: String, val difference: Int) { override fun toString(): String = "$term Δ $difference" companion object { val EMPTY: Score = Score("", -1) } } /** * Represents one row of the [score board](Scoreboard) with the numbers as rows and the players as columns. * * | | Player 1 | Player 2 | * |---:|---------:|---------:| * | 12 | 3 | 1 | * | 34 | 1 | 2 | * | 4 | 1 | 2 | * | 52 | 1 | 2 | * | 57 | 1 | 2 | * | 80 | 1 | 2 | */ class NumberScore(val number: Int, players: Players) { private val scores: MutableMap<Player, Score> = players.associateWith { Score.EMPTY }.toMutableMap() val complete: Boolean get() = scores.values.all { it != EMPTY } operator fun get(player: Player) = scores[player] ?: Score.EMPTY operator fun set(player: Player, score: Score) { scores[player] = score } override fun toString(): String = "NumberScore($number, $scores)" } /** * Represents one row of the [score board](Scoreboard) with the players as rows and the numbers as columns. * * | | 12 | 34 | 4 | 52 | 57 | 80 | * |----------|---:|---:|---:|---:|---:|---:| * | Player 1 | 1 | 0 | 2 | 1 | 0 | 4 | * | Player 2 | 0 | 0 | 1 | 2 | 0 | 3 | */ class PlayerScore(val player: Player, numbers: Numbers) { private val scores: MutableMap<Int, Score> = numbers.associateWith { Score.EMPTY }.toMutableMap() val complete: Boolean get() = scores.values.all { it != EMPTY } operator fun get(number: Int) = scores[number] ?: Score.EMPTY operator fun set(number: Int, score: Score) { scores[number] = score } override fun toString(): String = "PlayerScore($player, $scores)" } class Scoreboard(players: Players, numbers: Numbers) { val numberScores: List<NumberScore> = numbers.map { NumberScore(it, players) } val playerScores: List<PlayerScore> = players.map { PlayerScore(it, numbers) } val complete: Boolean get() = numberScores.all { it.complete } && playerScores.all { it.complete } private val _playerSums: MutableMap<Player, Int> = players.associateWith { 0 }.toMutableMap() val playerSums: Map<Player, Int> get() = _playerSums operator fun get(player: Player, number: Int): Score = numberScores.find { it.number == number }?.get(player) ?: Score.EMPTY operator fun set(player: Player, number: Int, score: Score) { numberScores.find { it.number == number }?.let { numberScore -> numberScore[player] = score } playerScores.find { it.player == player }?.let { playerScore -> playerScore[number] = score } _playerSums[player]?.let { current -> _playerSums[player] = current + score.difference } } fun winners(): List<Player> { val min = playerSums.values.min() return playerSums.filterValues { it == min }.keys.toList() } override fun toString(): String = "Scoreboard(playerSums: $playerSums)" }
0
Kotlin
0
0
124cf417ef4247aa6080d47fbef016a988a098e0
3,294
schlawiner-engine-kotlin
Apache License 2.0
sort/src/main/kotlin/com/lillicoder/algorithms/sort/Quicksort.kt
lillicoder
754,271,079
false
{"Kotlin": 16213}
package com.lillicoder.algorithms.sort import com.lillicoder.algorithms.collections.swap /** * Implementation of [Quicksort](https://en.wikipedia.org/wiki/Quicksort). */ class Quicksort : Sort { override fun <T : Comparable<T>> sort(list: List<T>) = list.toMutableList().apply { sort(this) } /** * Sorts the given [MutableList] using Quicksort. * @param list List to sort. */ private fun <T : Comparable<T>> sort(list: MutableList<T>) { if (list.isEmpty()) return val pivot = partition(list) sort(list.subList(0, pivot)) sort(list.subList(pivot + 1, list.size)) } /** * Partitions the given [MutableList] and returns the pivot index. * @param list List to partition. * @return Pivot index. */ private fun <T : Comparable<T>> partition(list: MutableList<T>): Int { val pivot = list.last() var pivotIndex = -1 list.forEachIndexed { index, element -> if (element < pivot) { pivotIndex++ list.swap(pivotIndex, index) } } // Move pivot to final position pivotIndex++ list.swap(pivotIndex, list.size - 1) return pivotIndex } }
0
Kotlin
0
0
8f96def65d07f646facaa3007cee6c8c99e71320
1,291
algorithms-kotlin
Apache License 2.0
src/Day06.kt
rafael-ribeiro1
572,657,838
false
{"Kotlin": 15675}
fun main() { fun part1(input: String): Int { return input.detectMarkerFinalPosition(4) } fun part2(input: String): Int { return input.detectMarkerFinalPosition(14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test")[0] check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06")[0] println(part1(input)) println(part2(input)) } fun String.detectMarkerFinalPosition(size: Int): Int { return 1 + this.withIndex() .filter { it.index >= size } .first { val marker = this.substring(it.index - size + 1, it.index + 1) marker.length == marker.toSet().size }.index }
0
Kotlin
0
0
5cae94a637567e8a1e911316e2adcc1b2a1ee4af
764
aoc-kotlin-2022
Apache License 2.0
src/2022/Day24.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import common.Linearizer import common.Offset import common.around import java.io.File import java.util.* fun main() { Day24().solve() } class Day24 { val maxTime = 10000 val input1 = """ #.##### #.....# #>....# #.....# #...v.# #.....# #####.# """.trimIndent() val input2 = """ #.###### #>>.<^<# #.<..<<# #>v.><># #<^v^^># ######.# """.trimIndent() enum class Dir { RIGHT, DOWN, LEFT, UP; fun turn(d: String): Dir { if (d == "R") { return Dir.values()[(ordinal+1)%4] } return Dir.values()[(ordinal+3)%4] } fun toChar(): Char { return when (this) { LEFT -> '<' UP -> '^' RIGHT -> '>' DOWN -> 'v' } } } fun Char.toDir(): Dir { var r = Dir.RIGHT for (d in Dir.values()) { if (d.toChar() == this) { r = d } } return r } data class Blizzard(val ix: Int, val dir: Dir) class Valley(val walls: Set<Int>, val blizzards: Map<Int, Set<Blizzard>>, val l: Linearizer) { val blizzardMoves = mapOf( Dir.LEFT to l.offset(-1, 0), Dir.RIGHT to l.offset(1, 0), Dir.UP to l.offset(0, -1), Dir.DOWN to l.offset(0, 1) ) val personMoves = listOf( l.offset(-1, 0), l.offset(1, 0), l.offset(0, -1), l.offset(0, 1), l.offset(0, 0) ) fun next(): Valley { val nextBlizzards = mutableMapOf<Int, MutableSet<Blizzard>>() for (b0 in blizzards) { for (b1 in b0.value) { val b2 = move(b1) if (!nextBlizzards.containsKey(b2.ix)) { nextBlizzards[b2.ix] = mutableSetOf() } nextBlizzards[b2.ix]!!.add(b2) } } return Valley(walls, nextBlizzards, l) } fun move(b: Blizzard): Blizzard { val ix1 = blizzardMoves[b.dir]!!.apply(b.ix)!! if (walls.contains(ix1)) { val xy = l.toCoordinates(ix1) if (xy[0] == 0) { return Blizzard(l.toIndex(l.dimensions[0]-2, xy[1]), b.dir) } if (xy[0] == l.dimensions[0]-1) { return Blizzard(l.toIndex(1, xy[1]), b.dir) } if (xy[1] == 0) { return Blizzard(l.toIndex(xy[0], l.dimensions[1]-2), b.dir) } if (xy[1] == l.dimensions[1]-1) { return Blizzard(l.toIndex(xy[0], 1), b.dir) } println("${xy[0]} ${xy[1]}") throw RuntimeException() } return Blizzard(ix1, b.dir) } fun toString(p: Int?): String { val sb = StringBuilder() for (j in 0 until l.dimensions[1]) { for (i in 0 until l.dimensions[0]) { val ix = l.toIndex(i, j) if (p == ix) { sb.append('X') } else if (walls.contains(ix)) { sb.append('#') } else if (blizzards.containsKey(ix)) { val n = blizzards[ix]?.size when (n) { null -> throw RuntimeException() 0 -> throw RuntimeException() 1 -> sb.append(blizzards[ix]?.first()!!.dir.toChar()) in 2..9 -> sb.append(n.toString()) else -> sb.append('+') } } else { sb.append('.') } } sb.appendLine() } return sb.toString() } fun next(p: Int): List<Int> { return personMoves.around(p).filter { open(it) } } fun open(p: Int): Boolean { return !walls.contains(p) && !blizzards.containsKey(p) } override fun toString(): String { return toString(null) } } class Valleys(valley: Valley) { val valleys: MutableList<Valley> = mutableListOf(valley) val l = valley.l val frequency = (l.dimensions[0]-2) * (l.dimensions[1]-2) // FIXME: LCM operator fun get(i0: Int): Valley { val i = i0%frequency while (i > valleys.size-1) { valleys.add(valleys.last().next()) } return valleys[i] } fun code(valley: Int, ix: Int): Int { val c = valley * l.size + ix if (valley(c) != valley || ix(c) != ix) { throw RuntimeException() } return c } fun valley(c: Int): Int { return c/l.size } fun ix(c: Int): Int { return c % l.size } } class Minimums { val codeToMin = mutableMapOf<Int, Int>() val minToCode = mutableMapOf<Int, MutableSet<Int>>() val finished = mutableMapOf<Int, Int>() fun add(c: Int, v: Int) { var oldMin: Int? = null var newMin: Int? = null if (finished.containsKey(c)) { if (v < finished[c]!!) { throw RuntimeException() } return } if (codeToMin.containsKey(c)) { if (v < codeToMin[c]!!) { oldMin = codeToMin[c] codeToMin[c] = v newMin = v } } else { codeToMin[c] = v newMin = v } if (oldMin != null) { minToCode[oldMin]!!.remove(c) } if (newMin != null) { if (!minToCode.containsKey(newMin)) { minToCode[newMin] = mutableSetOf() } minToCode[newMin]!!.add(c) } } fun getFinished(c: Int): Int { return finished[c]!! } fun minOrNull(): Int? { val m = minToCode.keys.minOrNull() if (m != null) { return minToCode[m]!!.first() } return null } fun finish(c: Int) { val m = codeToMin[c]!! codeToMin.remove(c) minToCode[m]!!.remove(c) if (minToCode[m]!!.isEmpty()) { minToCode.remove(m) } finished[c] = m } } fun findMin(t0: Int, startIx: Int, endIx: Int, valleys: Valleys): Int { val mins = Minimums() // val v0 = t0 % valleys.frequency val v0 = t0 mins.add(valleys.code(v0, startIx), 0) var next = mins.minOrNull() while (next != null) { mins.finish(next) val minSteps = mins.getFinished(next) val valley0 = valleys.valley(next) val ix0 = valleys.ix(next) // println("finish $valley0 ${l.toCoordinates(ix0)[0]} ${l.toCoordinates(ix0)[1]} $minSteps") // println("${valleys[valley0].toString(ix0)}") // println("${valleys[valley0+1].next(ix0)}") // println("${valleys[valley0+1].toString()}") if (ix0 == endIx) { return minSteps } for (ix in valleys[valley0+1].next(ix0)) { // println("add $valley0 ${l.toCoordinates(ix0)[0]} ${l.toCoordinates(ix0)[1]} $minSteps") // println("${valleys[valley0+1].toString(ix)}") mins.add(valleys.code(valley0+1, ix), minSteps+1) } next = mins.minOrNull() } throw RuntimeException() } fun solve() { val f = File("src/2022/inputs/day24.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) val walls = mutableSetOf<Int>() val blizzards = mutableMapOf<Int, Set<Blizzard>>() val lines = mutableListOf<String>() while (s.hasNextLine()) { val line = s.nextLine().trim() if (!line.isEmpty()) { lines.add(line) } } val x = lines.first().length val y = lines.size val l = Linearizer(x, y) for (j in 0 until y) { for (i in 0 until x) { val c = lines[j][i] val ix = l.toIndex(i, j) when (c) { '.' -> Unit '#' -> walls.add(ix) else -> blizzards[ix] = setOf(Blizzard(ix, c.toDir())) } } } val valley = Valley(walls, blizzards, l) val valleys = Valleys(valley) val startPos = l.toIndex(1, 0) val endPos = l.toIndex(l.dimensions[0]-2, l.dimensions[1]-1) println("${valleys[0].toString(startPos)}") println("${valleys[1].toString(endPos)}") for (i in 0..0) { println("${i}") println("${valleys[i].toString()}") } // val mins = Minimums() // mins.add(valleys.code(0, startPos), 0) // var next = mins.minOrNull() // while (next != null) { // mins.finish(next) // val minSteps = mins.getFinished(next) // val valley0 = valleys.valley(next) // val ix0 = valleys.ix(next) //// println("finish $valley0 ${l.toCoordinates(ix0)[0]} ${l.toCoordinates(ix0)[1]} $minSteps") //// println("${valleys[valley0].toString(ix0)}") //// println("${valleys[valley0+1].next(ix0)}") //// println("${valleys[valley0+1].toString()}") // if (ix0 == endPos) { // println("${minSteps}") // break // } // for (ix in valleys[valley0+1].next(ix0)) { //// println("add $valley0 ${l.toCoordinates(ix0)[0]} ${l.toCoordinates(ix0)[1]} $minSteps") //// println("${valleys[valley0+1].toString(ix)}") // mins.add(valleys.code(valley0+1, ix), minSteps+1) // } // next = mins.minOrNull() // } println("${findMin(0, startPos, endPos, valleys)}") val t1 = findMin(0, startPos, endPos, valleys) val t2 = findMin(t1, endPos, startPos, valleys) val t3 = findMin(t2+t1, startPos, endPos, valleys) println("$t1 $t2 $t3 ${t1 + t2 + t3}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
10,973
advent-of-code
Apache License 2.0
src/main/kotlin/SparseMerkleTree.kt
avoloshko
122,376,429
false
null
import kotlin.math.pow class SparseMerkleTree(input: Map<Int, ByteArray>, val depth: Int = 256, val hash: (ByteArray) -> ByteArray = { data -> SHA256Digest.digest(data) }) { val root: ByteArray private val defaultNodes: Array<ByteArray> private val tree: Array<Map<Int, ByteArray>> init { // validate data val max = 2.0.pow(depth - 1).toInt() if (input.size > max) { throw IndexOutOfBoundsException("There are too many leaves for the tree to build") } for (idx in input.keys) { if (idx < 0 || idx >= max) { throw IndexOutOfBoundsException() } } defaultNodes = defaultNodes(depth) if (input.isNotEmpty()) { tree = createTree(input, depth) root = tree.last().values.last() } else { tree = emptyArray() root = defaultNodes.last() } } private fun defaultNodes(depth: Int): Array<ByteArray> { val res = mutableListOf(ByteArray(32)) for (level in 1 until depth) { val prev = res[level - 1] res += hash(prev + prev) } return res.toTypedArray() } private fun createTree(input: Map<Int, ByteArray>, depth: Int): Array<Map<Int, ByteArray>> { val tree = mutableListOf(input) var treeLevel = input.toSortedMap() for (level in 0 until (depth - 1)) { val nextLevel = mutableMapOf<Int, ByteArray>() var prevIndex = -1 for ((index, value) in treeLevel) { if (index % 2 == 0) { nextLevel[index / 2] = hash(value + defaultNodes[level]) } else { if (index == prevIndex + 1) { nextLevel[index / 2] = hash(treeLevel[prevIndex]!! + value) } else { nextLevel[index / 2] = hash(defaultNodes[level] + value) } } prevIndex = index } tree.add(nextLevel) treeLevel = nextLevel.toSortedMap() } return tree.toTypedArray() } fun proofForIndex(idx: Int): List<ByteArray> { var index = idx val proof = mutableListOf<ByteArray>() for (level in 0 until (depth - 1)) { val siblingIndex = if (index % 2 == 0) index + 1 else index - 1 index /= 2 if (tree[level].containsKey(siblingIndex)) { proof += tree[level][siblingIndex]!! } else { proof += defaultNodes[level] } } return proof } fun verifyProof(proof: List<ByteArray>, root: ByteArray, leaf: ByteArray, idx: Int): Boolean { var computedHash = leaf var i = idx for (proofElement in proof) { if (i % 2 == 0) { computedHash = hash(computedHash + proofElement) } else { computedHash = hash(proofElement + computedHash) } i /= 2; } return byteArrayComparator.compare(computedHash, root) == 0 } companion object { private val byteArrayComparator = Comparator<ByteArray> { a, b -> var res = 0 for (i in 0 until a.size) { val cmp = a[i].toChar().compareTo(b[i].toChar()) if (cmp != 0) { res = cmp break } } res } } }
1
Kotlin
4
11
ff8dd711bdb113c5932d54d682574886a568deb3
3,588
merkle-tree
MIT License
src/main/kotlin/com/ComplexCalculator/MeanValueCalculatorClassInterval.kt
tamalbag117
430,126,002
false
{"Kotlin": 36650}
package com.ComplexCalculator import java.util.* class MeanValueCalculatorClassInterval { fun meanValueCalculatorClassInterval() { val sc = Scanner(System.`in`) val obj = Summation() println( "\n\n\t\tMeasures of Central Tendency\t\n\nTopic:\tClass interval and Mean Value calculation\n\n" ) println("Total number of class interval present in the equation:") val s: Int = sc.nextInt() val a = DoubleArray(s) val b = DoubleArray(s) val c = DoubleArray(s) val d = DoubleArray(s) val e = DoubleArray(s) val f = DoubleArray(s) println("Enter the Class Interval :one by one ") for (i in 0 until s) { println("The value of Class interval for column no." + (i + 1)) a[i] = sc.nextDouble() b[i] = sc.nextDouble() println("The frequency of The :" + a[i] + "-" + b[i] + " interval class is") f[i] = sc.nextDouble() } println("\n\nlet's find out the minvalue") for (i in 0 until s) { println( " in column no." + (i + 1) + "The mid value (X)of " + a[i] + "-" + b[i] + " interval class is" ) c[i] = (b[i] + a[i]) / 2 println(c[i]) } val cc = c[s / 2] val dd = b[1] - a[1] println("Calculate the y for the table \t∵y=(x-c)/d\t") for (i in 0 until s) { println( " in column no." + (i + 1) + "The value y in " + a[i] + "-" + b[i] + " interval class is" ) d[i] = (c[i] - cc) / dd println(d[i]) } for (i in 0 until s) { println( " in column no." + (i + 1) + "Fy=frequency*y in " + a[i] + "-" + b[i] + " interval class is" ) e[i] = d[i] * f[i] println(e[i]) } println("\n\n\nso the table is:\n\n\n") println("\t\t\t\tclass interval\t\t\tfrequency\t\tmid value\t\ty\t\tfrequency*y\t\t") for (i in 0 until s) { println( " in column no." + (i + 1) + "\t" + a[i] + "\t-\t" + b[i] + "\t\t" + f[i] + "\t\t" + c[i] + "\t\t" + d[i] + "\t\t" + e[i] + "\t\t\t\n\n" ) } println( "___________________________________________________________________________________________________________________________________________" ) println("\t\t\t\t\t\t\t\t∑f=" + obj.Sum1(f, s) + "\t\t\t∑Fy=\t" + obj.Sum1(e, s)) println("\n\nsum of frequency is ∑f=\t" + obj.Sum1(f, s)) println("\n\nsum of x is frequency*y=\t∑Fy=\t" + obj.Sum1(e, s)) println("\n\ncalculation\n\n x bar =$cc\t+$dd*y bar") println("the value of y bar is:" + obj.Sum1(e, s) / obj.Sum1(f, s)) println("x bar=" + cc + "+\t" + dd + "(" + (obj.Sum1(e, s) / obj.Sum1(f, s)) + ")") val x = cc + dd * obj.Sum1(e, s) / obj.Sum1(f, s) println("\n\n The answer is:\n\t\t\t$x") } }
0
Kotlin
0
1
82b987343250624cfdedec4d59d3a35d85393345
3,072
ArithmaticComplexCalculator
MIT License
grokking-algorithms/07 - Dijkstra’s/01_dijkstras.kt
arturschaefer
427,090,600
false
{"C": 48055, "Kotlin": 24446, "C++": 16696, "Dart": 3630, "QMake": 168}
import java.util.Deque import java.util.LinkedList import kotlin.collections.last import kotlin.math.cos private const val START = "start" private const val A = "A" private const val B = "B" private const val FIN = "FIN" private const val NONE = "none" fun main() { val graph = hashMapOf( START to hashMapOf<String, Int>(), A to hashMapOf<String, Int>(), B to hashMapOf<String, Int>(), FIN to hashMapOf<String, Int>(), ) val costs = hashMapOf<String, Int>() val parents = hashMapOf<String, String>() val processed = hashSetOf<String>() graph[START]?.put(A, 6) graph[START]?.put(B, 2) graph[A]?.put(FIN, 1) graph[B]?.put(A, 3) graph[B]?.put(FIN, 5) costs[A] = 6 costs[B] = 2 costs[FIN] = Int.MAX_VALUE parents[A] = START parents[B] = START parents[NONE] = NONE var node = findLowestCostNode(costs, processed) var totalCost = costs[node] ?: 0 while (node != NONE){ val cost = costs[node] ?: 0 val neighbors = graph[node] for (n in neighbors?.keys!!){ val newCost = cost + (neighbors[n] ?: 0) costs[n] = newCost parents[n] = node } processed.add(node) node = findLowestCostNode(costs, processed) totalCost += costs[node] ?: 0 } println(parents) println(costs) println(processed) } fun findLowestCostNode(costs: HashMap<String, Int>, processed: Set<String>): String { var lowestCost = Int.MAX_VALUE var lowestCostNode = NONE for (node in costs) { val cost = node.value if (cost < lowestCost && !processed.contains(node.key)) { lowestCost = cost lowestCostNode = node.key } } return lowestCostNode }
0
C
0
0
04c34298739cab13b5cd755b4c6786fc1fe236cd
1,794
computer-science-studies
Apache License 2.0
kotlin/src/com/leetcode/17_LetterCombinationsOfAPhoneNumber.kt
programmerr47
248,502,040
false
null
package com.leetcode private class Solution17 { private val letterDict = arrayOf( arrayOf('a', 'b', 'c'), arrayOf('d', 'e', 'f'), arrayOf('g', 'h', 'i'), arrayOf('j', 'k', 'l'), arrayOf('m', 'n', 'o'), arrayOf('p', 'q', 'r', 's'), arrayOf('t', 'u', 'v'), arrayOf('w', 'x', 'y', 'z') ) fun letterCombinations(digits: String): List<String> { if (digits.isEmpty()) return emptyList() val bucketArr = IntArray(digits.length) digits.forEachIndexed { i, c -> val index: Int = c - '2' bucketArr[i] = index } val letterArr = CharArray(digits.length) val result = ArrayList<String>(bucketArr.reduce { acc, item -> acc * item }) combine(result, letterArr, bucketArr, 0) return result } private fun combine(result: MutableList<String>, letterArr: CharArray, bucketArr: IntArray, bucketI: Int) { if (bucketI == bucketArr.size) { result += letterArr.joinToString(separator = "") return } letterDict[bucketArr[bucketI]].forEach { bucketLetter -> letterArr[bucketI] = bucketLetter combine(result, letterArr, bucketArr, bucketI + 1) } } } fun main() { println(Solution17().letterCombinations("23")) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
1,384
problemsolving
Apache License 2.0
ion-schema/src/main/kotlin/com/amazon/ionschema/model/ContinuousRange.kt
amazon-ion
148,685,964
false
{"Kotlin": 802107, "Inno Setup": 15625, "Java": 795, "Shell": 631}
package com.amazon.ionschema.model import com.amazon.ionschema.model.ContinuousRange.Limit interface IContinuousRange<T> where T : Comparable<T>, T : Any { val start: Limit<T> val end: Limit<T> operator fun contains(value: T): Boolean fun intersect(that: ContinuousRange<T>): Pair<Limit<T>, Limit<T>>? } /** * A range over a type that is an uncountably infinite set. * * A `ContinuousRange` is a _bounded interval_ when both limits are non-null, and it is a _half-bounded interval_ * when one of the limits is `null`. At least one of [start] and [end] must be non-null. * * A `ContinuousRange` can be _open_, _half-open_, or _closed_ depending on [Limit.exclusive] of the limits. * * A `ContinuousRange` is allowed to be a _degenerate interval_ (i.e. `start == end` when both limits are closed), * but it may not be an empty interval (i.e. `start == end` when either limit is open, or `start > end`). */ open class ContinuousRange<T : Comparable<T>> internal constructor(final override val start: Limit<T>, final override val end: Limit<T>) : IContinuousRange<T> { private constructor(value: Limit.Closed<T>) : this(value, value) internal constructor(value: T) : this(Limit.Closed(value)) sealed class Limit<out T> { abstract val value: T? interface Bounded<T> { val value: T } data class Closed<T : Comparable<T>>(override val value: T) : Limit<T>(), Bounded<T> data class Open<T : Comparable<T>>(override val value: T) : Limit<T>(), Bounded<T> object Unbounded : Limit<Nothing>() { override val value: Nothing? get() = null override fun equals(other: Any?) = other is Unbounded override fun hashCode() = 0 } } init { require(start is Limit.Bounded<*> || end is Limit.Bounded<*>) { "range may not be unbounded both above and below" } require(!isEmpty(start, end)) { "range may not be empty" } } /** * Returns the intersection of `this` `DiscreteRange` with [other]. * If the two ranges do not intersect, returns `null`. */ final override fun intersect(that: ContinuousRange<T>): Pair<Limit<T>, Limit<T>>? { val newStart = when { this.start is Limit.Unbounded -> that.start that.start is Limit.Unbounded -> this.start this.start.value!! > that.start.value!! -> this.start that.start.value!! > this.start.value!! -> that.start this.start is Limit.Open -> this.start that.start is Limit.Open -> that.start else -> this.start // They are both closed and equal } val newEnd = when { this.end is Limit.Unbounded -> that.end that.end is Limit.Unbounded -> this.end this.end.value!! < that.end.value!! -> this.end that.end.value!! < this.end.value!! -> that.end this.end is Limit.Open -> this.end that.end is Limit.Open -> that.end else -> this.end // They are both closed and equal } return if (isEmpty(newStart, newEnd)) null else newStart to newEnd } /** * Checks whether the given value is contained within this range. */ final override operator fun contains(value: T): Boolean = start.isBelow(value) && end.isAbove(value) private fun Limit<T>.isAbove(other: T) = when (this) { is Limit.Closed -> value >= other is Limit.Open -> value > other is Limit.Unbounded -> true } private fun Limit<T>.isBelow(other: T) = when (this) { is Limit.Closed -> value <= other is Limit.Open -> value < other is Limit.Unbounded -> true } /** * Checks whether the range is empty. The range is empty if its start value is greater than the end value for * non-exclusive endpoints, or if the start value equals the end value when either endpoint is exclusive. */ private fun isEmpty(start: Limit<T>, end: Limit<T>): Boolean { if (start is Limit.Unbounded || end is Limit.Unbounded) return false val exclusive = start is Limit.Open || end is Limit.Open return if (exclusive) start.value!! >= end.value!! else start.value!! > end.value!! } final override fun toString(): String { val lowerBrace = if (start is Limit.Closed) '[' else '(' val lowerValue = start.value ?: " " val upperValue = end.value ?: " " val upperBrace = if (end is Limit.Closed) ']' else ')' return "$lowerBrace$lowerValue,$upperValue$upperBrace" } final override fun equals(other: Any?): Boolean { return other is ContinuousRange<*> && other.start == start && other.end == end } override fun hashCode(): Int { var result = start.hashCode() result = 31 * result + end.hashCode() return result } }
38
Kotlin
14
26
bbab678c12fdd07bcb9b5d632fb7364a04541a73
4,897
ion-schema-kotlin
Apache License 2.0
aoc21/day_02/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File fun String.name() = this.split(" ")[0] fun String.x() = this.split(" ")[1].toInt() data class Pos(val horiz: Int, val depth: Int, val aim: Int) { fun nextFirst(cmd: String, x: Int) = when (cmd) { "forward" -> Pos(horiz + x, depth, aim) "down" -> Pos(horiz, depth + x, aim) "up" -> Pos(horiz, depth - x, aim) else -> this } fun nextSecond(cmd: String, x: Int) = when (cmd) { "forward" -> Pos(horiz + x, depth + aim * x, aim) "down" -> Pos(horiz, depth, aim + x) "up" -> Pos(horiz, depth, aim - x) else -> this } } fun main() { val insts = File("input").readLines() val first = insts.fold(Pos(0, 0, 0)) { pos, cmd -> pos.nextFirst(cmd.name(), cmd.x()) } println("First: ${first.horiz * first.depth}") val second = insts.fold(Pos(0, 0, 0)) { pos, cmd -> pos.nextSecond(cmd.name(), cmd.x()) } println("Second: ${second.horiz * second.depth}") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
967
advent-of-code
MIT License
kotlin/src/Day09.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.IllegalStateException import java.lang.Integer.parseInt fun main() { fun part1(input: List<String>): Int { val heightMap = input.map { line -> line.map(Char::toString).map(::parseInt) } return heightMap.flatMapIndexed { lineIndex, line -> line.filterIndexed { rowIndex, height -> when (lineIndex) { 0 -> { when (rowIndex) { 0 -> { height < heightMap[1][0] && height < heightMap[0][1] } heightMap[0].size - 1 -> { height < heightMap[1][rowIndex] && height < heightMap[0][rowIndex - 1] } else -> { height < heightMap[1][rowIndex] && height < heightMap[0][rowIndex - 1] && height < heightMap[0][rowIndex + 1] } } } heightMap.size - 1 -> { when (rowIndex) { 0 -> { height < heightMap[lineIndex - 1][0] && height < heightMap[lineIndex][1] } heightMap[0].size - 1 -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] } else -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] && height < heightMap[lineIndex][rowIndex + 1] } } } else -> { when (rowIndex) { 0 -> { height < heightMap[lineIndex - 1][0] && height < heightMap[lineIndex][1] && height < heightMap[lineIndex + 1][0] } heightMap[0].size - 1 -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] && height < heightMap[lineIndex + 1][rowIndex] } else -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] && height < heightMap[lineIndex][rowIndex + 1] && height < heightMap[lineIndex + 1][rowIndex] } } } } } }.sumOf { height -> height + 1 } } fun part2(input: List<String>): Int { val heightMap = input.map { line -> line.map(Char::toString).map(::parseInt) } val lowPointIndexes = heightMap.flatMapIndexed { index, line -> line.mapIndexed { rowIndex, height -> index to rowIndex to height }.filter { (indexes, height) -> val rowIndex = indexes.second when (val lineIndex = indexes.first) { 0 -> { when (rowIndex) { 0 -> { height < heightMap[1][0] && height < heightMap[0][1] } heightMap[0].size - 1 -> { height < heightMap[1][rowIndex] && height < heightMap[0][rowIndex - 1] } else -> { height < heightMap[1][rowIndex] && height < heightMap[0][rowIndex - 1] && height < heightMap[0][rowIndex + 1] } } } heightMap.size - 1 -> { when (rowIndex) { 0 -> { height < heightMap[lineIndex - 1][0] && height < heightMap[lineIndex][1] } heightMap[0].size - 1 -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] } else -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] && height < heightMap[lineIndex][rowIndex + 1] } } } else -> { when (rowIndex) { 0 -> { height < heightMap[lineIndex - 1][0] && height < heightMap[lineIndex][1] && height < heightMap[lineIndex + 1][0] } heightMap[0].size - 1 -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] && height < heightMap[lineIndex + 1][rowIndex] } else -> { height < heightMap[lineIndex - 1][rowIndex] && height < heightMap[lineIndex][rowIndex - 1] && height < heightMap[lineIndex][rowIndex + 1] && height < heightMap[lineIndex + 1][rowIndex] } } } } }.map { (indexes, _) -> indexes } } val largeBasinSizes = lowPointIndexes.map { lowPosition -> var basinSize = 0 val visited = Array(heightMap.size) { Array(heightMap[0].size) { false } } val stack = arrayListOf(lowPosition) while (stack.isNotEmpty()) { val nextPosition = stack.removeAt(stack.size - 1) if (nextPosition.first in visited.indices && nextPosition.second in visited[0].indices) { if (!visited[nextPosition.first][nextPosition.second]) { visited[nextPosition.first][nextPosition.second] = true if (heightMap[nextPosition.first][nextPosition.second] != 9) { basinSize++ stack.addAll( setOf( nextPosition.first to nextPosition.second - 1, nextPosition.first to nextPosition.second + 1, nextPosition.first + 1 to nextPosition.second, nextPosition.first - 1 to nextPosition.second ) ) } } } } basinSize }.sorted().reversed() return largeBasinSizes[0] * largeBasinSizes[1] * largeBasinSizes[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 15) { "${part1(testInput)}" } check(part2(testInput) == 1134) { "${part2(testInput)}" } val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
8,552
aoc-2021
MIT License
2019/04 - Secure Container/kotlin/src/app.kt
Adriel-M
225,250,242
false
null
import kotlin.math.pow data class DedupeDigitEntry(val digit: Int, var repeats: Int) open class NumberValidator(private val number: Int) { val encodedNumber = encodeNumber() private fun getPowValue(position: Int): Int { val base = 10.toDouble() val exponent = (5 - position).toDouble() return base.pow(exponent).toInt() } private fun getDigit(position: Int): Int { val powValue = getPowValue(position) return (number / powValue) % 10 } private fun encodeNumber(): List<DedupeDigitEntry> { val firstDigit = getDigit(0) val encodedNumber = mutableListOf(DedupeDigitEntry(firstDigit, 1)) for (i in 1 until 6) { val currentDigit = getDigit(i) val previousEntry = encodedNumber.last() if (currentDigit == previousEntry.digit) { previousEntry.repeats += 1 } else { encodedNumber.add(DedupeDigitEntry(currentDigit, 1)) } } return encodedNumber.toList() } private fun isWithinRange(): Boolean { return number in 100000..999999 } private fun isIncreasing(): Boolean { for (i in 1 until encodedNumber.size) { if (encodedNumber[i].digit < encodedNumber[i - 1].digit) { return false } } return true } open fun containsPair(): Boolean { for (entry in encodedNumber) { if (entry.repeats >= 2) { return true } } return false } fun isValid(): Boolean { if (!isWithinRange()) { return false } if (!isIncreasing()) { return false } if (!containsPair()) { return false } return true } } class NumberValidatorStrict(number: Int): NumberValidator(number) { override fun containsPair(): Boolean { for (entry in encodedNumber) { if (entry.repeats == 2) { return true } } return false } } fun part1(): Int { var numberOfValidPasswords = 0 for (i in 246515..739105) { if (NumberValidator(i).isValid()) { numberOfValidPasswords += 1 } } return numberOfValidPasswords } fun part2(): Int { var numberOfValidPasswords = 0 for (i in 246515..739105) { if (NumberValidatorStrict(i).isValid()) { numberOfValidPasswords += 1 } } return numberOfValidPasswords } fun main() { println("===== Part 1 =====") println(part1()) println("===== Part 2 =====") println(part2()) }
0
Kotlin
0
0
ceb1f27013835f13d99dd44b1cd8d073eade8d67
2,685
advent-of-code
MIT License
src/main/kotlin/problems/OutOfBoundary.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
package problems /** * Leetcode : medium * https://leetcode.com/problems/out-of-boundary-paths/ * There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. * You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the * grid crossing the grid boundary). You can apply at most maxMove moves to the ball. * Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths * to move the ball out of the grid boundary. * * Since the answer can be very large, return it modulo 109 + 7. */ object OutOfBoundary { private val memoized: Array<Array<IntArray>> by lazy { Array(51) { Array(51) { IntArray(51) { -1 } } } } fun findPaths(m: Int, n: Int, maxMove: Int, startRow: Int, startColumn: Int): Int { return findPathsHelper(m, n, maxMove, startRow, startColumn) } private fun findPathsHelper(m: Int, n: Int, maxMove: Int, i: Int, j: Int): Int { if (i >= m || i < 0 || j >= n || j < 0) { return 1 } if (maxMove <= 0) { return 0 } if (memoized[i][j][maxMove] != -1) { return memoized[i][j][maxMove] } var res = 0L res += findPathsHelper(m, n, maxMove - 1, i + 1, j) res += findPathsHelper(m, n, maxMove - 1, i, j + 1) res += findPathsHelper(m, n, maxMove - 1, i - 1, j) res += findPathsHelper(m, n, maxMove - 1, i, j - 1) memoized[i][j][maxMove] = (res % 1000000007).toInt() return memoized[i][j][maxMove] } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,647
data-structures
MIT License
src/main/kotlin/com/ichipsea/kotlin/matrix/NumberMatrix.kt
mouEsam
143,008,487
true
{"Kotlin": 19119}
package com.ichipsea.kotlin.matrix import kotlin.math.* operator fun <M : Number, N : Number> Matrix<M>.plus(other: Matrix<N>): Matrix<Double> { if (rows != other.rows || cols != other.cols) throw IllegalArgumentException("Matrices not match") return mapIndexed { x, y, value -> value.toDouble() + other[x, y].toDouble() } } operator fun <N : Number> Matrix<N>.unaryMinus(): Matrix<Double> { return map { -it.toDouble() } } operator fun <M : Number, N : Number> Matrix<M>.minus(other: Matrix<N>): Matrix<Double> { return this + (-other) } operator fun <M : Number, N : Number> Matrix<M>.times(other: Matrix<N>): Matrix<Double> { if (rows != other.rows || cols != other.cols) throw IllegalArgumentException("Matrices not match") return mapIndexed { x, y, value -> value.toDouble() * other[x, y].toDouble() } } operator fun <M : Number> Matrix<M>.times(other: Number): Matrix<Double> { return map { it.toDouble() * other.toDouble() } } operator fun <M : Number> Number.times(other: Matrix<M>): Matrix<Double> { return other * this } operator fun <M : Number, N : Number> Matrix<M>.div(other: Matrix<N>): Matrix<Double> { if (rows != other.rows || cols != other.cols) throw IllegalArgumentException("Matrices not match") return mapIndexed { x, y, value -> value.toDouble() / other[x, y].toDouble() } } operator fun <M : Number> Matrix<M>.div(other: Number): Matrix<Double> { assert(other.toDouble() != 0.0) { println("Cannot divide by zero") } return map { it.toDouble() / other.toDouble() } } infix fun <M : Number, N : Number> Matrix<M>.x(other: Matrix<N>): Matrix<Double> { if (other.rows != cols) throw IllegalArgumentException("Matrices not match first ${this.rows}x${this.cols} second ${other.rows}x${other.cols}") return createMatrix(other.cols, rows) { x, y -> var value = .0 for (i in 0 until cols) value += this[i, y].toDouble() * other[x, i].toDouble() value } } infix fun <M: Number, N: Number> Matrix<M>.xReverse(other: Matrix<N>): Matrix<Double> { if (rows !== other.cols) throw IllegalArgumentException("Matrices not match") return createMatrix(cols, other.rows) { x, y -> var value = .0 for (i in 0..rows-1) value += this[x, i].toDouble() * other[i, y].toDouble() value } } fun <M : Number> Matrix<M>.sum(): Double { var sum = 0.0 forEach { sum += it.toDouble() } return sum } fun <M : Number> Matrix<M>.cofactor(): Matrix<Double> { return createMatrix(cols, rows) { x, y -> var value = determinantOfSubMatrix(x, y) value = if ((x + y)%2!=0) -value else value value } } fun <M : Number> Matrix<M>.adjugate(): Matrix<Double> { return cofactor().asTransposed() } fun <M : Number> Matrix<M>.inverse(): Matrix<Double> { val det = determinant() assert(det != 0.0) { throw IllegalArgumentException("cannot calculate an inverse of a zero-determined matrix") } return adjugate() / det } fun <M : Number> Matrix<M>.rightInverse(): Matrix<Double> { return asTransposed() x (this x asTransposed()).inverse() } fun <M : Number> Matrix<M>.leftInverse(): Matrix<Double> { return (asTransposed() x this).inverse() x asTransposed() } fun <M : Number> Matrix<M>.determinant(): Double { assert(this.cols == this.rows) { println("Can't calculate determinant for a non-cubic matrix") } return if (this.cols == 1 && this.rows == 1) { this[0, 0].toDouble() } else if (this.cols == 2 && this.rows == 2) { this[0, 0].toDouble() * this[1, 1].toDouble() - (this[1, 0].toDouble() * this[0, 1].toDouble()) } else if (this.cols > 2 && this.rows > 2) { var mvalue = 0.0 var negative: Boolean = false for (i in 0 until this.cols) { val posValue = this[i, 0].toDouble() * determinantOfSubMatrix(i, 0) mvalue += if (negative) -posValue else posValue negative = !negative } mvalue } else Double.NaN } private fun <M : Number> Matrix<M>.determinantOfSubMatrix(col: Int, row: Int): Double { val list: MutableList<Double> = mutableListOf() mapIndexed { x, y, value -> if (x != col && y != row) list.add(value.toDouble()) value } return matrixOf(cols - 1, rows - 1, *list.toTypedArray()).determinant() } fun <M : Number> log(matrix: Matrix<M>, sub: M): Matrix<Double> = matrix.map { log(it.toDouble(), sub.toDouble()) } fun <M : Number> loge(matrix: Matrix<M>): Matrix<Double> = matrix.map { log(it.toDouble(), exp(1.0)) } fun <M : Number> log10(matrix: Matrix<M>): Matrix<Double> = matrix.map { log10(it.toDouble()) } fun <M : Number> Matrix<M>.pow(sup: M): Matrix<Double> = map { it.toDouble().pow(sup.toDouble()) } fun <M : Number> Matrix<M>.pow(sup: Matrix<M>): Matrix<Double> = mapIndexed { x, y, value -> value.toDouble().pow(sup[x, y].toDouble()) } fun <M : Number> round(matrix: Matrix<M>, decimalPlaces: Int = 3): Matrix<Double> = matrix.map { round(x = it.toDouble() * 10.0.pow(decimalPlaces)) / 10.0.pow(decimalPlaces) } fun <M : Number> ceil(matrix: Matrix<M>): Matrix<Double> = matrix.map { ceil(it.toDouble()) } fun <M : Number> sin(matrix: Matrix<M>): Matrix<Double> = matrix.map { sin(it.toDouble()) } fun <M : Number> tan(matrix: Matrix<M>): Matrix<Double> = matrix.map { tan(it.toDouble()) } fun <M : Number> floor(matrix: Matrix<M>): Matrix<Double> = matrix.map { floor(it.toDouble()) } fun <M : Number> sqrt(matrix: Matrix<M>): Matrix<Double> = matrix.map { sqrt(it.toDouble()) } fun <M : Number> solveEquations(coefs: Matrix<M>, cons: Matrix<M>): Matrix<Double> = coefs.inverse() x cons
0
Kotlin
0
0
137b9e93dbd34821210484081730448d8709ec15
5,738
kotlin-matrix
Apache License 2.0
src/main/kotlin/be/tabs_spaces/advent2021/days/Day02.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days import be.tabs_spaces.advent2021.days.Day02.Position.ReferenceFrame.ABSOLUTE import be.tabs_spaces.advent2021.days.Day02.Position.ReferenceFrame.AIMED class Day02 : Day(2) { override fun partOne(): Any { val submarine = Submarine.absolutelyPositioned() move(submarine) return submarine.position.product } override fun partTwo(): Any { val submarine = Submarine.aimed() move(submarine) return submarine.position.product } private fun move(submarine: Submarine) { submarine.executeManoeuvres(inputList.map { Instruction.from(it) }) } private class Submarine private constructor( val position: Position ) { companion object { fun absolutelyPositioned() = Submarine(Position()) fun aimed() = Submarine(Position(referenceFrame = AIMED)) } fun executeManoeuvres(instructions: List<Instruction>) = instructions.forEach { when (it.direction) { Instruction.Direction.FORWARD -> position.forward(it.units) Instruction.Direction.DOWN -> position.down(it.units) Instruction.Direction.UP -> position.up(it.units) } } } private data class Position( private val referenceFrame: ReferenceFrame = ABSOLUTE, private var horizontal: Int = 0, private var depth: Int = 0, private var aim: Int = 0, ) { val product get() = horizontal * depth fun forward(units: Int) { if (referenceFrame == AIMED) { depth += aim * units } horizontal += units } fun down(units: Int) { when (referenceFrame) { AIMED -> aim += units ABSOLUTE -> depth += units } } fun up(units: Int) { down(-1 * units) } enum class ReferenceFrame { ABSOLUTE, AIMED } } private data class Instruction private constructor( val direction: Direction, val units: Int ) { companion object { fun from(textualInstruction: String): Instruction { val (direction, units) = textualInstruction.split(" ") return Instruction(Direction.valueOf(direction.uppercase()), units.toInt()) } } enum class Direction { FORWARD, UP, DOWN } } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
2,535
advent-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindNumOfLIS.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 673. Number of Longest Increasing Subsequence * @see <a href="https://leetcode.com/problems/number-of-longest-increasing-subsequence/">Source</a> */ fun interface FindNumOfLIS { operator fun invoke(nums: IntArray): Int } /** * Approach 1: Bottom-up Dynamic Programming */ class FindNumOfLISBottomUp : FindNumOfLIS { override operator fun invoke(nums: IntArray): Int { val n: Int = nums.size val length = IntArray(n) { 1 } val count = IntArray(n) { 1 } for (i in 0 until n) { for (j in 0 until i) { if (nums[j] < nums[i]) { if (length[j] + 1 > length[i]) { length[i] = length[j] + 1 count[i] = 0 } if (length[j] + 1 == length[i]) { count[i] += count[j] } } } } var maxLength = 0 var result = 0 for (len in length) { maxLength = max(maxLength, len) } for (i in 0 until n) { if (length[i] == maxLength) { result += count[i] } } return result } } /** * Approach 2: Top-down Dynamic Programming (Memoization) */ class FindNumOfLISTopDown : FindNumOfLIS { override operator fun invoke(nums: IntArray): Int { val n: Int = nums.size val length = IntArray(n) val count = IntArray(n) var maxLength = 0 var result = 0 for (i in 0 until n) { calculateDP(i, nums, length, count) maxLength = max(maxLength, length[i]) } for (i in 0 until n) { if (length[i] == maxLength) { result += count[i] } } return result } private fun calculateDP(i: Int, nums: IntArray, length: IntArray, count: IntArray) { if (length[i] != 0) { return } length[i] = 1 count[i] = 1 for (j in 0 until i) { if (nums[j] < nums[i]) { calculateDP(j, nums, length, count) if (length[j] + 1 > length[i]) { length[i] = length[j] + 1 count[i] = 0 } if (length[j] + 1 == length[i]) { count[i] += count[j] } } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,105
kotlab
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[330]按要求补齐数组.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都 //可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。 // // 示例 1: // // 输入: nums = [1,3], n = 6 //输出: 1 //解释: //根据 nums 里现有的组合 [1], [3], [1,3],可以得出 1, 3, 4。 //现在如果我们将 2 添加到 nums 中, 组合变为: [1], [2], [3], [1,3], [2,3], [1,2,3]。 //其和可以表示数字 1, 2, 3, 4, 5, 6,能够覆盖 [1, 6] 区间里所有的数。 //所以我们最少需要添加一个数字。 // // 示例 2: // // 输入: nums = [1,5,10], n = 20 //输出: 2 //解释: 我们需要添加 [2, 4]。 // // // 示例 3: // // 输入: nums = [1,2,2], n = 5 //输出: 0 // // Related Topics 贪心算法 // 👍 195 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun minPatches(nums: IntArray, n: Int): Int { //假设数组元素现在可构成的和的区间为[1, total] //插入元素number后,可构成的区间为[1,total] U [1+number, total+number] U [number], 等价于[1,total] U [number, total+number] //可分为两种情况: //如果 total>= number-1, 区间可合并为[1, total+number] // [1,4] U [5,7] --> 4>=5-1 即可合并 //否则,区间无法合并。可通过插入 total+1, 把区间扩展为 [1, 2total+1] //注意:插入元素的范围为[1,n], 若total<n, 则total+1属于[1,n]之间 // 时间复杂度 O(n) var count = 0; //插入元素数目 var total:Long = 0; //遍历 index var index =0; while(total < n){ if(index < nums.size && total >= nums[index]-1){ total += nums[index] index++ }else{ total += total+1 count++ } } return count } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,064
MyLeetCode
Apache License 2.0
codeforces/kotlinheroes6/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.kotlinheroes6 import kotlin.math.abs private fun solve() { val (n, xIn, yIn) = readInts() val (x, y) = listOf(xIn, yIn).sorted().map { it - 1 } val ans = List(n) { m -> maxOf(solve(0, m, x), solve(m, n, y)) }.minOrNull() println(ans) } private fun solve(from: Int, to: Int, x: Int): Int { if (from == to) return 0 return minOf(dist(x, from), dist(x, to - 1)) + to - from - 1 } private fun dist(x: Int, y: Int): Int { return abs(x - y) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
698
competitions
The Unlicense
src/easy/Math/744-CountPrimes.kt
diov
170,882,024
false
null
import kotlin.math.sqrt fun main() { val n = 10 println(countPrimes2(n)) } // [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) fun countPrimes1(n: Int): Int { if (n < 3) return 0 val array = IntArray(n) { 1 } array[0] = 0 for (i in 2..sqrt(n.toFloat()).toInt()) { if (array[i - 1] == 0) continue for (j in i*i..n step i) { array[j - 1] = 0 } } return array.sum() - array[array.count() - 1] } fun countPrimes2(n: Int): Int { if (n < 3) return 0 val array = BooleanArray(n) { true } for (i in 2..sqrt(n.toFloat()).toInt()) { if (!array[i]) continue for (j in i*i until n step i) { array[j] = false } } var result = 0 for (i in 2 until n) { if (array[i]) result++ } return result }
0
Kotlin
0
0
668ef7d6d1296ab4df2654d5a913a0edabc72a3c
856
leetcode
MIT License
src/main/kotlin/days/Day5.kt
tcrawford-figure
435,911,433
false
{"Kotlin": 23558}
package days import kotlin.math.absoluteValue import kotlin.math.sign /** * https://adventofcode.com/2021/day/5 * Taken with advice from: https://todd.ginsberg.com/post/advent-of-code/2021/day5/ */ class Day5 : Day(5) { private data class Point(val x: Int, val y: Int) { infix fun sharesAxisWith(that: Point): Boolean = x == that.x || y == that.y // Builds list of coordinates along a line from point a to b infix fun lineTo(that: Point): List<Point> { val dx = that.x - x val dy = that.y - y val dxSign = dx.sign val dySign = dy.sign val steps = maxOf(dx.absoluteValue, dy.absoluteValue) return (1..steps).scan(this) { last, _ -> Point(last.x + dxSign, last.y + dySign) } } } private val instructions = inputList.map { parseLine(it) } override fun partOne(): Int = solve { it.first sharesAxisWith it.second } override fun partTwo(): Int = solve { true } private fun solve(lineFilter: (Pair<Point, Point>) -> Boolean) = instructions .filter { lineFilter(it) } .flatMap { it.first lineTo it.second } // Creates a flat list of "highlighted"/"selected" coordinates .groupingBy { it } // Creates a map of coordinates associated to a count .eachCount() .count { it.value > 1 } private fun parseLine(line: String): Pair<Point, Point> = Pair( line.substringBefore(" ").split(",").map { it.toInt() }.let { Point(it.first(), it.last()) }, line.substringAfterLast(" ").split(",").map { it.toInt() }.let { Point(it.first(), it.last()) } ) }
0
Kotlin
0
0
87f689c4315e2f8eaca587b2f20fc245958efec8
1,684
aoc
Creative Commons Zero v1.0 Universal
kotlin/roman-numerals/src/main/kotlin/RomanNumeral.kt
ikr
147,076,927
false
{"C++": 22451113, "Kotlin": 136005, "CMake": 90716, "Java": 30028}
object RomanNumeral { fun value(x: Int): String { val result = StringBuilder() var remainder = x while (remainder > 0) { val next = firstNotExceeding(remainder) result.append(next.literal) remainder -= next.value } return result.toString() } } private fun firstNotExceeding(x: Int): Term { for (i in 0 until atoms.size - 1) { val candidates = if (i % 2 == 0) listOf( atoms[i], atoms[i] - atoms[i + 2] ) else listOf( atoms[i] + atoms[i + 1] + atoms[i + 1] + atoms[i + 1], atoms[i] + atoms[i + 1] + atoms[i + 1], atoms[i] + atoms[i + 1], atoms[i], atoms[i] - atoms[i + 1] ) val result = candidates.find {it.value <= x} if (result != null) return result } return atoms.last() } private val atoms = listOf( Term(1000, "M"), Term(500, "D"), Term(100, "C"), Term(50, "L"), Term(10, "X"), Term(5, "V"), Term(1, "I") ) private data class Term(val value: Int, val literal: String) { operator fun plus(other: Term): Term { return Term(value + other.value, literal + other.literal) } operator fun minus(other: Term): Term { return Term(value - other.value, other.literal + literal) } }
0
C++
0
0
37f505476ae13dd003c1de24b5113a0d7e94aaf2
1,431
exercism
MIT License
src/main/kotlin/days/Day18.kt
felix-ebert
317,592,241
false
null
package days class Day18 : Day(18) { // source: https://todd.ginsberg.com/post/advent-of-code/2020/day18/ // own try was based on substrings + recursion // keep this solution because of the simplicity and understandability override fun partOne(): Any { return inputList.map { it.replace(" ", "") }.sumOf { evaluateRuleOne(it.iterator()) } } override fun partTwo(): Any { return inputList.map { it.replace(" ", "") }.sumOf { evaluateRuleTwo(it.iterator()) } } private fun evaluateRuleOne(expression: CharIterator): Long { val numbers = mutableListOf<Long>() var operator = Char.MIN_VALUE // empty char is not allowed in Kotlin while (expression.hasNext()) { when (val next = expression.nextChar()) { '(' -> numbers += evaluateRuleOne(expression) ')' -> break in setOf('+', '*') -> operator = next else -> numbers += next.toString().toLong() } if (numbers.size == 2) { val a = numbers.removeLast() val b = numbers.removeLast() numbers += if (operator == '+') a + b else a * b } } return numbers.first() } private fun evaluateRuleTwo(expression: CharIterator): Long { val numbers = mutableListOf<Long>() var added = 0L while (expression.hasNext()) { val next = expression.nextChar() when { next == '(' -> added += evaluateRuleTwo(expression) next == ')' -> break next == '*' -> { numbers += added added = 0L } next.isDigit() -> added += next.toString().toLong() } } return (numbers + added).reduce { a, b -> a * b } } }
0
Kotlin
0
4
dba66bc2aba639bdc34463ec4e3ad5d301266cb1
1,877
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/schlaubi/aoc/Utils.kt
DRSchlaubi
573,014,474
false
{"Kotlin": 21541}
package dev.schlaubi.aoc /** * Splits a list each time [delimiter] occurs. */ fun <T> List<T>.splitBy(delimiter: T): List<List<T>> = splitWhen { it == delimiter } /** * Splits a list of Strings each time a blank entry occurs. */ fun <T : CharSequence> List<T>.splitByBlank(): List<List<T>> = splitWhen(CharSequence::isBlank) /** * Splits a list each time [predicate] returns `true`. */ inline fun <T> List<T>.splitWhen(crossinline predicate: (T) -> Boolean): List<List<T>> { return asSequence() .withIndex() .filter { (index, value) -> predicate(value) || index == 0 || index == size - 1 } // Just getting the delimiters with their index; Include 0 and last -- so to not ignore it while pairing later on .zipWithNext() // zip the IndexValue with the adjacent one so to later remove continuous delimiters; Example: Indices : 0,1,2,5,7 -> (0,1),(1,2),(2,5),(5,7) .filter { pair -> pair.first.index + 1 != pair.second.index } // Getting rid of continuous delimiters; Example: (".",".") will be removed, where "." is the delimiter .map { pair -> val startIndex = if (predicate(pair.first.value)) pair.first.index + 1 else pair.first.index // Trying to not consider delimiters val endIndex = if (!predicate(pair.second.value) && pair.second.index == size - 1) pair.second.index + 1 else pair.second.index // subList() endIndex is exclusive subList(startIndex, endIndex) // Adding the relevant sub-list }.toList() } /** * Skips the next [n] elements of the iterator. */ fun Iterator<*>.skip(n: Int = 1) = repeat(n) { if (hasNext()) next() }
1
Kotlin
0
4
4514e4ac86dd3ed480afa907d907e3ae26457bba
1,671
aoc-2022
MIT License
src/main/kotlin/day4/Day4.kt
tomaszobac
726,163,227
false
{"Kotlin": 15292}
package day4 import java.io.File fun part1(file: File): List<Int> { val pilePoints: MutableList<Int> = mutableListOf() val part2AmountOfNumbers: MutableList<Int> = mutableListOf() var index = 0 file.bufferedReader().useLines { readLines -> readLines.forEach { line -> val sets = (line.split(Regex(": +"))[1]).split(Regex(" +\\| +")) val winNumbers = (sets[0].split(Regex(" +")).map { it.toInt() }).toSet() val myNumbers = (sets[1].split(Regex(" +")).map { it.toInt() }).toSet() var points = 0 part2AmountOfNumbers.add(index,0) for (number in myNumbers) { if (winNumbers.contains(number)) { points = if (points == 0) 1 else points * 2 part2AmountOfNumbers[index] += 1 } } index++ pilePoints += points }} println(pilePoints.sum()) return part2AmountOfNumbers.toList() } fun part2(file: File) { val amountOfNumbers: List<Int> = part1(file) val numberOfCopies: MutableList<Int> = MutableList(amountOfNumbers.size) { 1 } for ((card, amount) in amountOfNumbers.withIndex()) { if (amount == 0) continue for (repeat in 1..numberOfCopies[card]) { for (index in card + 1..card + amount) { numberOfCopies[index]++ } } } println(numberOfCopies.sum()) } fun main() { val file = File("src/main/kotlin/day4/input.txt") part2(file) }
0
Kotlin
0
0
e0ce68fcf11e126c4680cff75ba959e46c5863aa
1,480
aoc2023
MIT License
src/Day11.kt
JohannaGudmandsen
573,090,573
false
{"Kotlin": 19316}
import java.io.File import kotlin.collections.* class Test(var divisibleBy:Int, var trueThrowsToMonkey:Int, var falseThrowsToMonkey:Int) class Operation(var type:String, var rightValue:String, var leftValue:String) class Monkey(var id:Int, var items:ArrayList<Long>, var op:Operation, var test:Test, var inspect:Long) fun doOneRound(monkeys:ArrayList<Monkey>, divideWorryLevelBy3:Boolean, modWorryLevelWith:Int){ for (monkey in monkeys){ for (item in monkey.items){ monkey.inspect++ var left:Long var right:Long if (monkey.op.rightValue.all { it -> it.isDigit() }){ right = monkey.op.rightValue.toLong() } else { right = item } if (monkey.op.leftValue.all { it -> it.isDigit() }){ left = monkey.op.leftValue.toLong() } else { left = item } var worryLevel:Long if (monkey.op.type == "+"){ worryLevel = (left + right) } else { worryLevel = (left * right) } if (divideWorryLevelBy3){ worryLevel /= 3 } else { worryLevel = worryLevel % modWorryLevelWith } if (worryLevel.mod(monkey.test.divisibleBy.toLong()) == 0.toLong()){ var throwToMonkey = monkeys.filter { it -> it.id == monkey.test.trueThrowsToMonkey }.first() throwToMonkey.items.add(worryLevel) } else { var throwToMonkey = monkeys.filter { it -> it.id == monkey.test.falseThrowsToMonkey }.first() throwToMonkey.items.add(worryLevel) } } monkey.items = ArrayList<Long>() } } fun Day11() { val input = File("src/input/day11.txt").readLines() var monkeysTask1 = ArrayList<Monkey>() var monkeysTask2 = ArrayList<Monkey>() var modWorryLevelWith = 1 for(i in 0..input.size-1 step 7){ var monkeyId = input[i].filter { it.isDigit() }.toInt() var startingItems = input[i+1].split(":")[1].split(",").map { it.filter { it.isDigit() }.toLong() } var op = input[i+2].split("=")[1].split(" ") var divisibleBy = input[i+3].filter { it.isDigit() }.toInt() modWorryLevelWith = modWorryLevelWith * divisibleBy var ifTrueThrowToMonkey = input[i+4].filter { it.isDigit() }.toInt() var ifFalseThrowToMonkey = input[i+5].filter { it.isDigit() }.toInt() var monkeyTask1 = Monkey( monkeyId, ArrayList<Long>(startingItems), Operation(op[2], op[1], op[3]), Test(divisibleBy, ifTrueThrowToMonkey, ifFalseThrowToMonkey), 0) var monkeyTask2 = Monkey( monkeyId, ArrayList<Long>(startingItems), Operation(op[2], op[1], op[3]), Test(divisibleBy, ifTrueThrowToMonkey, ifFalseThrowToMonkey), 0) monkeysTask1.add(monkeyTask1) monkeysTask2.add(monkeyTask2) } for (i in 0..19 step 1){ doOneRound(monkeysTask1, true, modWorryLevelWith) } for (i in 0..9999 step 1){ doOneRound(monkeysTask2, false, modWorryLevelWith) } var inspectList = monkeysTask1.map { it -> it.inspect }.sortedDescending() var task1 = inspectList[0] * inspectList[1] var inspectListTask2 = monkeysTask2.map { it -> it.inspect }.sortedDescending() var task2:Long = inspectListTask2[0].toLong() * inspectListTask2[1].toLong() println("Day 11 Task 1: $task1") // 55216 println("Day 11 Task 2: $task2") // 12848882750 }
0
Kotlin
0
1
21daaa4415bd20c14d67132e615971519211ab16
3,847
aoc-2022
Apache License 2.0
Algorithms/src/main/kotlin/PermutationInString.kt
ILIYANGERMANOV
557,496,216
false
{"Kotlin": 74485}
/** * # 567. Permutation in String * Problem: * https://leetcode.com/problems/permutation-in-string/ * * WARNING: This solution is not optimal! */ class PermutationInString { fun checkInclusion(target: String, source: String): Boolean { if (target.length > source.length) return false return permuteFind(target) { source.contains(it) } } private fun permuteFind( arr: String, n: Int = arr.length, k: Int = 0, find: (String) -> Boolean ): Boolean { if (k == n - 1) { return find(arr) } for (i in k until n) { val newArr = arr.swap(k, i) if (i != k && arr == newArr) continue if (permuteFind(arr = newArr, n = n, k = k + 1, find = find)) { return true } } return false } private fun String.swap(i: Int, j: Int): String { if (i == j) return this val arr = this.toCharArray() val temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr.concatToString() } }
0
Kotlin
0
1
4abe4b50b61c9d5fed252c40d361238de74e6f48
1,120
algorithms
MIT License
src/Day17.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
import CHAMBER_UNIT.* fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") .single() .parseMovs() val part1TestResult = part1(testInput) println("Result on test input: $part1TestResult") check(part1TestResult == 3068L) val input = readInput("Day17") .single() .parseMovs() val part1Result = part1(input) println(part1Result) check(part1Result == 3161L) val part2TestResult = part2(testInput) println(part2TestResult) check(part2TestResult == 1514285714288) //check(part2TestResult == 3068L) val part2Result = part2(input) println(part2Result) } const val CHAMBER_WIDTH = 7 private enum class ACTION { FALLING, GAS_PUSH } private class Chamber { val chamber: ArrayDeque<MutableList<CHAMBER_UNIT>> = ArrayDeque() var x: Int = 0 var y: Int = 0 var removedBottom = 0L fun startShape(shape: Shape) { repeat(3 + shape.height) { chamber.addFirst(MutableList(CHAMBER_WIDTH) { E }) } x = 2 y = 0 } fun drawShape(shape: Shape, x: Int, y: Int, u: CHAMBER_UNIT = R) { shape.mask.forEachIndexed { dy, chamberUnits -> chamberUnits.forEachIndexed { dx, chamberUnit -> if (chamberUnit == R) { chamber[y + dy][x + dx] = u } } } } fun isShapeCanBeMovedToPosition(shape: Shape, x: Int, y: Int): Boolean { if (x < 0 || x + shape.width > CHAMBER_WIDTH) { return false } if (y < 0 || y + shape.height > chamber.size) { return false } for (dy in shape.mask.indices) { for (dx in shape.mask[dy].indices) { if (shape.mask[dy][dx] == R && chamber[y + dy][x + dx] == REST_ROCK ) { return false } } } return true } fun getOutline(): List<Int> { return (0 until CHAMBER_WIDTH).map { x -> val depth = (0 until chamber.size).takeWhile { y -> chamber[y][x] == E }.count() depth } } } private fun Chamber.draw() { this.chamber.forEach { u -> println(u.joinToString("") { c -> when (c) { E -> "." REST_ROCK -> "#" R -> "@" } }) } } private fun generateChamber(input: List<Mov>, rocksCount: Long = 2022): Chamber { val chamber = Chamber() var inputPos = 0 val shapes = Shape.values() var action = ACTION.GAS_PUSH for (rockNo in 0 until rocksCount) { val shape = shapes[(rockNo % shapes.size.toLong()).toInt()] chamber.startShape(shape) while (true) { when (action) { ACTION.FALLING -> { action = ACTION.GAS_PUSH val testY = chamber.y + 1 if (chamber.isShapeCanBeMovedToPosition(shape, chamber.x, testY)) { chamber.y = testY } else { break } } ACTION.GAS_PUSH -> { val testX = chamber.x + input[inputPos].dx inputPos = (inputPos + 1) % input.size action = ACTION.FALLING if (chamber.isShapeCanBeMovedToPosition(shape, testX, chamber.y)) { chamber.x = testX } } } } chamber.drawShape(shape, chamber.x, chamber.y, REST_ROCK) while (chamber.chamber[0].all { it == E }) { chamber.chamber.removeFirst() chamber.y -= 1 } } return chamber } private fun part1(input: List<Mov>, rocksCount: Long = 2022): Long { val chamber = generateChamber(input, rocksCount) return chamber.chamber.size.toLong() + chamber.removedBottom } private fun part2(input: List<Mov>, rocksCount: Long = 1000000000000): Long { data class CacheKey( val currentShape: Shape, val inputPos: Int, val outline: List<Int> ) data class CacheValue( val rockNo: Long, val height: Long ) val seenOutlines: MutableMap<CacheKey, CacheValue> = mutableMapOf() val chamber = Chamber() var inputPos = 0 val shapes = Shape.values() var action = ACTION.GAS_PUSH var rockNo = 0L var totalHeight = 0L var lastChamberSize = 0 while (rockNo < rocksCount) { val shape = shapes[(rockNo % shapes.size.toLong()).toInt()] chamber.startShape(shape) val currentPos = inputPos while (true) { when (action) { ACTION.FALLING -> { action = ACTION.GAS_PUSH val testY = chamber.y + 1 if (chamber.isShapeCanBeMovedToPosition(shape, chamber.x, testY)) { chamber.y = testY } else { break } } ACTION.GAS_PUSH -> { val testX = chamber.x + input[inputPos].dx inputPos = (inputPos + 1) % input.size action = ACTION.FALLING if (chamber.isShapeCanBeMovedToPosition(shape, testX, chamber.y)) { chamber.x = testX } } } } chamber.drawShape(shape, chamber.x, chamber.y, REST_ROCK) while (chamber.chamber[0].all { it == E }) { chamber.chamber.removeFirst() chamber.y -= 1 } rockNo += 1 totalHeight += (chamber.chamber.size - lastChamberSize) lastChamberSize = chamber.chamber.size val outline = chamber.getOutline() val cacheKey = CacheKey( currentShape = shape, inputPos = currentPos, outline = outline ) if (cacheKey in seenOutlines) { val startCycle = seenOutlines[cacheKey]!! val rocksPerCycle = rockNo - startCycle.rockNo val heightPerCycle = chamber.chamber.size - startCycle.height val rocksLeft = rocksCount - rockNo val fullCyclesLeft = rocksLeft / rocksPerCycle if (fullCyclesLeft > 0) { println( "Found cycle. Old height: $startCycle, current height: $totalHeight\n" + "rocks per cycle: $rocksPerCycle heightPerCycle: $heightPerCycle rocksLeft: $rocksLeft " + "full cycles left: $fullCyclesLeft" ) rockNo += fullCyclesLeft * rocksPerCycle totalHeight += fullCyclesLeft * heightPerCycle } } else { seenOutlines[cacheKey] = CacheValue(rockNo = rockNo, height = totalHeight) } } return totalHeight } private enum class Mov(val dx: Int) { LEFT(-1), RIGHT(1) } private enum class Shape(val mask: List<List<CHAMBER_UNIT>>) { SH1( listOf( listOf(R, R, R, R) ) ), SH2( listOf( listOf(E, R, E), listOf(R, R, R), listOf(E, R, E), ) ), SH3( listOf( listOf(E, E, R), listOf(E, E, R), listOf(R, R, R) ) ), SH4( listOf( listOf(R), listOf(R), listOf(R), listOf(R), ) ), SH5( listOf( listOf(R, R), listOf(R, R), ) ); val width get() = this.mask[0].size val height get() = this.mask.size } private enum class CHAMBER_UNIT { E, REST_ROCK, R } private fun String.parseMovs(): List<Mov> { return this.map { when (it) { '<' -> Mov.LEFT '>' -> Mov.RIGHT else -> error("Unknown symbol $it") } } }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
8,140
aoc22-kotlin
Apache License 2.0
2021/kotlin/src/main/kotlin/aoc/days/day4/Day4Input.kt
tupini07
76,610,908
false
{"Haskell": 35857, "Elixir": 22701, "Clojure": 20266, "Kotlin": 12288, "F#": 4426, "HTML": 4256, "CSS": 4163, "Dockerfile": 1374, "Shell": 963, "C#": 489, "TypeScript": 320, "Emacs Lisp": 299, "Makefile": 182}
package aoc.days.day4 import aoc.entities.Vector2d import kotlin.math.pow class Day4Input(val orderOfDraws: List<Int>, val boards: MutableList<BingoBoard>) class BingoBoard(boardRep: String) { private val boardNumbers: List<Int> private val numbersSet: MutableList<Boolean> private val boardSize: Int private var lastDrawnNumber = -1 init { /* 22 13 17 11 0 8 2 23 4 24 21 9 14 16 7 6 10 3 18 5 1 12 20 15 19 * */ val rows = boardRep.split("\n").map { row -> row.split(" ").map { it.trim() }.filter { it.isNotEmpty() }.map(Integer::parseInt) } // we assume the shape of the board is a square boardSize = rows[0].size boardNumbers = rows.flatten() numbersSet = generateSequence { false }.take(boardSize.toDouble().pow(2.0).toInt()).toMutableList() } private fun cordsToLocalIndex(cords: Vector2d): Int = cords.y * boardSize + cords.x.toInt() private fun localIndexToCords(idx: Int): Vector2d = Vector2d(idx % boardSize, idx / boardSize) private fun isNumberAtCordsSet(cords: Vector2d): Boolean = this.numbersSet[cordsToLocalIndex(cords)] fun setDrawnNumber(drawnNumber: Int) { lastDrawnNumber = drawnNumber this.boardNumbers.mapIndexed { index, i -> if (drawnNumber == i) { this.numbersSet[index] = true return } } } fun getBoardScore(): Int { // sum all unmarked numbers var sumOfUnmarked = 0 for (x in 0 until this.boardSize) { for (y in 0 until this.boardSize) { val cords = Vector2d(x, y) if (!isNumberAtCordsSet(cords)) { sumOfUnmarked += this.boardNumbers[cordsToLocalIndex(cords)] } } } return sumOfUnmarked * this.lastDrawnNumber } fun isBoardComplete(): Boolean { // for every row for (y in 0 until this.boardSize) { var isRowComplete = true for (x in 0 until this.boardSize) { isRowComplete = isRowComplete && isNumberAtCordsSet(Vector2d(x, y)) if (!isRowComplete) break } if (isRowComplete) return true } // for every column for (x in 0 until this.boardSize) { var isColumnComplete = true for (y in 0 until this.boardSize) { isColumnComplete = isColumnComplete && isNumberAtCordsSet(Vector2d(x, y)) if (!isColumnComplete) break } if (isColumnComplete) return true } return false } }
0
Haskell
0
0
4aee7ef03880e3cec9467347dc817b1db8a5fc0f
2,735
advent-of-code
MIT License
src/main/kotlin/day03/part1/main.kt
TheMrMilchmann
225,375,010
false
null
/* * Copyright (c) 2019 <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 day03.part1 import utils.* import kotlin.math.* fun main() { val input = readInputText("/day03/input.txt") val data = input.lineSequence().map { it.split(',') }.toList() println(run(data)) } private fun run(data: List<List<String>>): Int { data class Point(val x: Int, val y: Int) fun String.toPoints(origin: Point): List<Point> { val op: (Point) -> Point = when (val dir = this[0]) { 'U' -> { it -> it.copy(y = it.y + 1) } 'D' -> { it -> it.copy(y = it.y - 1) } 'R' -> { it -> it.copy(x = it.x + 1) } 'L' -> { it -> it.copy(x = it.x - 1) } else -> error("Encountered unexpected direction: $dir") } val res = mutableListOf<Point>() var tail = origin for (i in 0 until substring(1).toInt()) { op(tail).also { tail = it res.add(it) } } return res } fun <T> Iterable<Iterable<T>>.intersectAll(): Iterable<T> { val itr = iterator() var res = if (itr.hasNext()) itr.next().toSet() else emptySet() while (itr.hasNext()) res = res.intersect(itr.next()) return res } return data.map { path -> var tail = Point(0, 0) path.flatMap { segment -> segment.toPoints(tail).also { tail = it.last() } } }.intersectAll() .filter { it != Point(0, 0) } .map { abs(it.x) + abs(it.y) } .min()!! }
0
Kotlin
0
1
9d6e2adbb25a057bffc993dfaedabefcdd52e168
2,593
AdventOfCode2019
MIT License
pulsar-skeleton/src/test/kotlin/ai/platon/pulsar/crawl/common/TestSuffixStringMatcher.kt
platonai
124,882,400
false
null
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 ai.platon.pulsar.crawl.common import ai.platon.pulsar.common.SuffixStringMatcher import org.junit.Assert import org.junit.Test /** * Unit tests for SuffixStringMatcher. */ class TestSuffixStringMatcher { private fun makeRandString(minLen: Int, maxLen: Int): String { val len = minLen + (Math.random() * (maxLen - minLen)).toInt() val chars = CharArray(len) for (pos in 0 until len) { chars[pos] = alphabet[(Math.random() * alphabet.size).toInt()] } return String(chars) } @Test fun testSuffixMatcher() { var numMatches = 0 var numInputsTested = 0 for (round in 0 until NUM_TEST_ROUNDS) { // build list of suffixes val numSuffixes = (Math.random() * MAX_TEST_SUFFIXES).toInt() val suffixes = arrayOfNulls<String>(numSuffixes) for (i in 0 until numSuffixes) { suffixes[i] = makeRandString(0, MAX_SUFFIX_LEN) } val sufmatcher = SuffixStringMatcher(suffixes) // test random strings for suffix matches for (i in 0 until NUM_TEST_INPUTS_PER_ROUND) { val input = makeRandString(0, MAX_INPUT_LEN) var matches = false var longestMatch = -1 var shortestMatch = -1 for (j in suffixes.indices) { if (suffixes[j]!!.length > 0 && input.endsWith(suffixes[j]!!)) { matches = true val matchSize = suffixes[j]!!.length if (matchSize > longestMatch) longestMatch = matchSize if (matchSize < shortestMatch || shortestMatch == -1) shortestMatch = matchSize } } if (matches) numMatches++ numInputsTested++ Assert.assertTrue("'" + input + "' should " + (if (matches) "" else "not ") + "match!", matches == sufmatcher.matches(input)) if (matches) { Assert.assertTrue(shortestMatch == sufmatcher.shortestMatch(input).length) Assert.assertTrue(input.substring(input.length - shortestMatch) == sufmatcher.shortestMatch(input)) Assert.assertTrue(longestMatch == sufmatcher.longestMatch(input).length) Assert.assertTrue(input.substring(input.length - longestMatch) == sufmatcher.longestMatch(input)) } } } println("got " + numMatches + " matches out of " + numInputsTested + " tests") } companion object { private const val NUM_TEST_ROUNDS = 20 private const val MAX_TEST_SUFFIXES = 100 private const val MAX_SUFFIX_LEN = 10 private const val NUM_TEST_INPUTS_PER_ROUND = 100 private const val MAX_INPUT_LEN = 20 private val alphabet = charArrayOf('a', 'b', 'c', 'd') } }
1
HTML
32
110
f93bccf5075009dc7766442d3a23b5268c721f54
3,828
pulsar
GNU Affero General Public License v3.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[19]删除链表的倒数第 N 个结点.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 // // 进阶:你能尝试使用一趟扫描实现吗? // // // // 示例 1: // // //输入:head = [1,2,3,4,5], n = 2 //输出:[1,2,3,5] // // // 示例 2: // // //输入:head = [1], n = 1 //输出:[] // // // 示例 3: // // //输入:head = [1,2], n = 1 //输出:[1] // // // // // 提示: // // // 链表中结点的数目为 sz // 1 <= sz <= 30 // 0 <= Node.val <= 100 // 1 <= n <= sz // // Related Topics 链表 双指针 // 👍 1382 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { //想像成两个人走路,让一个人先走N步,第二个人再开始走,这样两人的距离就距离N, // 这是当前一个人到达末尾时,后一个人刚好是倒数第N的位置 //时间复杂度 O(n) val pre = ListNode(0) pre.next = head var p: ListNode? = pre var q: ListNode? = pre var count = n while (count > 0) { q = q?.next count -= 1 } while (q?.next != null) { p = p?.next q = q.next } p?.next = p?.next?.next return pre.next } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,604
MyLeetCode
Apache License 2.0
test/com/zypus/SLIP/algorithms/genetic/UnitTest.kt
zypus
213,665,750
false
null
package com.zypus.SLIP.algorithms.genetic import com.zypus.Maze.algorithms.RnnMazeEvolution import com.zypus.Maze.controller.ARobotController import com.zypus.Maze.models.Maze import com.zypus.utilities.squared import org.junit.Assert import org.junit.Test import org.knowm.xchart.Histogram import java.util.* /** * TODO Add description * * @author fabian <<EMAIL>> * * @created 29/10/2016 */ class UnitTest { @Test fun testSelection() { val random = Random(1L) val population = Array(10) { Entity<Double, Double, Double, Double>(it.toDouble(), it.toDouble().squared, "test") { -it } } val difs = population.map { e -> val sum = e.behaviour!! val x = population.filter { it != e }.minBy { Math.abs(it.behaviour!! - sum) } Math.abs(x!!.behaviour!! - sum) } Assert.assertArrayEquals(arrayOf(1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 13.0, 15.0, 17.0), difs.toTypedArray()) Assert.assertArrayEquals(arrayOf(17.0, 15.0, 13.0, 11.0, 9.0, 7.0, 5.0, 3.0, 1.0, 1.0), difs.sortedDescending().toTypedArray()) val rankedPopulation = population.sortedByDescending { e -> val sum = e.behaviour!! val x = population.filter { it != e }.minBy { Math.abs(it.behaviour!! - sum) } Math.abs(x!!.behaviour!! - sum) } val selections = (1..100000).map { Selection(1, arrayListOf(rankedPopulation.linearSelection(1.5, random) to rankedPopulation.linearSelection(1.5, random))) } val dist = selections.foldRight((1..10).map { 0 } as MutableList) { s, f -> f[s.parents[0].first.genotype.toInt()]++ f[s.parents[0].second.genotype.toInt()]++ f } // selections.forEach{ // val parent = it.parents[0] // println("${parent.first.genotype} -> ${parent.second.genotype}") // } println(dist) } @Test fun testLinearSelection() { val populationSize = 100 val bias = 1.999 val selects = (1..1000).map { val random = it / 1000.0 (populationSize * (bias - Math.sqrt(bias * bias - 4.0 * (bias - 1) * random)) / 2.0 / (bias - 1)).toInt() } val hist = Histogram(selects, 100) print(hist.getyAxisData()) } @Test fun testReproduction() { fun solutionSort(population: List<Entity<List<Double>, ARobotController, Double, MutableList<Double>>>): List<Entity<List<Double>, ARobotController, Double, MutableList<Double>>> { return population.sortedByDescending { e -> val sum = e.behaviour!!.sum() val x = population.filter { it != e }.minBy { Math.abs(it.behaviour!!.sum() - sum) } Math.abs(x!!.behaviour!!.sum() - sum) } } fun problemSort(population: List<Entity<List<Double>, Maze, Double, MutableList<Double>>>): List<Entity<List<Double>, Maze, Double, MutableList<Double>>> { return population.sortedByDescending { e -> val sum = e.behaviour!!.sum() val x = population.filter { it != e }.minBy { Math.abs(it.behaviour!!.sum() - sum) } Math.abs(x!!.behaviour!!.sum() - sum) } } val rule = RnnMazeEvolution.rule(RnnMazeEvolution.Selectors(::solutionSort,::problemSort)) val state = rule.initialize(10, 1) Assert.assertEquals(10, state.solutions.size) Assert.assertEquals(1, state.problems.size) val hashs = state.solutions.map { it.hashCode() } state.solutions.forEach { Assert.assertEquals(0, it.behaviour!!.size) } rule.matchAndEvaluate(state) state.solutions.forEach { Assert.assertEquals(20, it.behaviour!!.size) } val afterEval = state.solutions.count { it.hashCode() in hashs } Assert.assertEquals(10, afterEval) val nextState = rule.selectAndReproduce(state) Assert.assertEquals(11, nextState.solutions.size) rule.matchAndEvaluate(nextState) nextState.solutions.forEach { Assert.assertEquals(20, it.behaviour!!.size) } state.solutions.sortedBy { it.id }.zip(nextState.solutions.sortedBy { it.id }).forEach { val (e1, e2) = it val b1 = e1.behaviour!!.sum() val b2 = e2.behaviour!!.sum() Assert.assertEquals(b1, b2,0.0) } val nextNextState = rule.selectAndReproduce(nextState) Assert.assertEquals(11, nextNextState.solutions.size) val afterEval2 = nextNextState.solutions.count { it.hashCode() in hashs } Assert.assertTrue(afterEval2 == 10 || afterEval2 == 9) } }
0
Kotlin
0
0
418ee8837752143194fd769e86fac85e15136929
4,220
SLIP
MIT License
src/main/kotlin/algorithms/LongestSubsequence.kt
jimandreas
377,843,697
false
null
@file:Suppress( "SameParameterValue", "UnnecessaryVariable", "UNUSED_VARIABLE", "ControlFlowWithEmptyBody", "unused", "MemberVisibilityCanBePrivate" ) package algorithms import org.jetbrains.kotlinx.multik.api.d1array import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.ndarray.data.get import org.jetbrains.kotlinx.multik.ndarray.data.set import org.jetbrains.kotlinx.multik.ndarray.operations.max /** * rosalind: * http://rosalind.info/problems/lgis/ * Longest Increasing Subsequence (and Decreasing) * * See also: * https://www.youtube.com/watch?v=CE2b_-XfVDk * Longest Increasing Subsequence * <NAME> - Coding Made Simple * */ class LongestSubsequence { /** * Problem A subsequence of a permutation is a collection of elements of the permutation in the order that they appear. For example, (5, 3, 4) is a subsequence of (5, 1, 3, 4, 2). A subsequence is increasing if the elements of the subsequence increase, and decreasing if the elements decrease. For example, given the permutation (8, 2, 1, 6, 5, 7, 4, 3, 9), an increasing subsequence is (2, 6, 7, 9), and a decreasing subsequence is (8, 6, 5, 4, 3). You may verify that these two subsequences are as long as possible. Given: A positive integer n≤10000 followed by a permutation π of length n Return: A longest increasing subsequence of π, followed by a longest decreasing subsequence of π. */ /** * this algorithm follows what I call the "voting" mechanism * where each number in the list has a corresponding * vote in the 1D array. The votes are tabulated by * comparing a value with previously voted components * where the previous value is less than the current value. * The votes are then scanned in reverse order to build * the subsequence. * See the youtube video referenced above for a walk through of * this technique. */ fun findLongestIncreasingSubsequence(l: List<Int>): List<Int> { val voteArray = mk.d1array(l.size) { 1 } for (i in 1 until l.size) { var maxVote = Int.MIN_VALUE for (j in 0 until i) { if (l[j] < l[i]) { if (voteArray[j] > maxVote) { maxVote = voteArray[j] voteArray[i] = maxVote + 1 } } } } /** * the voting for ascending array entries is completed. * Now walk the list backwards and pick the highest * first arrives of each vote for the list */ var maxVote = voteArray.max() val outList: MutableList<Int> = mutableListOf() for (i in l.size - 1 downTo 0) { if (voteArray[i] == maxVote) { outList.add(0, l[i]) if (--maxVote == 0) { break } } } return outList } /** * for a list [l] determine the longest * increasing and decreasing subsequences and then * @return these two lists */ fun longestSequences(l: List<Int>): List<List<Int>> { val increasingSeq = findLongestIncreasingSubsequence(l) // for the descending list - invert the list, find the increasing list // using negative numbers, then re-invert and sort descending val invertedList = l.map { it * -1 } val invertedListIncreasing = findLongestIncreasingSubsequence(invertedList) val decreasingSeq = invertedListIncreasing.map { it * -1 }.sortedDescending() return listOf(increasingSeq, decreasingSeq) } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
3,691
stepikBioinformaticsCourse
Apache License 2.0
2017/src/main/kotlin/Day12.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import utils.splitCommas import utils.splitNewlines import utils.toIntList import java.util.regex.Pattern object Day12 { fun part1(input: String): Int { val map = parse(input) return visit(map, 0).numConnected } fun part2(input: String): Int { val map = parse(input) val allIds = map.keys.toMutableSet() var numGroups = 0 while (allIds.isNotEmpty()) { val start = allIds.toList()[0] val visitInfo = visit(map, start) allIds.removeAll(visitInfo.visited) numGroups++ } return numGroups } private val PATTERN = Pattern.compile("(\\d+) <-> (.+)") private fun parse(input: String): Map<Int, Set<Int>> { val map = mutableMapOf<Int, MutableSet<Int>>() for (line in input.splitNewlines()) { val matcher = PATTERN.matcher(line) matcher.matches() val a = matcher.group(1).toInt() for (b in matcher.group(2).splitCommas().toIntList()) { connect(map, a, b) connect(map, b, a) } } return map } private fun connect(map: MutableMap<Int, MutableSet<Int>>, a: Int, b: Int) { map.getOrPut(a, { mutableSetOf() }).add(b) } private fun visit(map: Map<Int, Set<Int>>, start: Int): VisitInfo { var numConnected = 0 var visited = mutableSetOf<Int>() var queue = mutableListOf(start) while (queue.isNotEmpty()) { val a = queue.removeAt(0) if (a in visited) { continue } numConnected++ visited.add(a) queue.addAll(map[a].orEmpty()) } return VisitInfo(numConnected, visited) } data class VisitInfo(val numConnected: Int, val visited: Set<Int>) }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,644
advent-of-code
MIT License
src/main/kotlin/com/github/davio/aoc/y2021/Day7.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2021 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.getInputAsList import kotlin.math.abs import kotlin.math.pow import kotlin.math.roundToInt import kotlin.system.measureTimeMillis fun main() { Day7.getResultPart1() measureTimeMillis { Day7.getResultPart2() }.let { println("Took $it ms") } } object Day7 : Day() { /* --- Day 7: The Treachery of Whales --- A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run! Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a massive underground cave system just beyond where they're aiming! The crab submarines all need to be aligned before they'll have enough power to blast a large enough hole for your submarine to get through. However, it doesn't look like they'll be aligned before the whale catches you! Maybe you can help? There's one major catch - crab submarines can only move horizontally. You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible. For example, consider the following horizontal positions: 16,1,2,0,4,2,7,1,2,14 This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on. Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any horizontal position to align them all on, but the one that costs the least fuel is horizontal position 2: Move from 16 to 2: 14 fuel Move from 1 to 2: 1 fuel Move from 2 to 2: 0 fuel Move from 0 to 2: 2 fuel Move from 4 to 2: 2 fuel Move from 2 to 2: 0 fuel Move from 7 to 2: 5 fuel Move from 1 to 2: 1 fuel Move from 2 to 2: 0 fuel Move from 14 to 2: 12 fuel This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel). Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? */ fun getResultPart1() { val crabsByPosition = getCrabs() val minimumFuelSpent = (0..crabsByPosition.keys.maxOrNull()!!).minOf { target -> crabsByPosition.entries.sumOf { val crabsPosition = it.key val numberOfCrabsAtPosition = it.value val distance = abs(crabsPosition - target) distance * numberOfCrabsAtPosition } } println(minimumFuelSpent) } /* --- Part Two --- The crabs don't seem interested in your proposed solution. Perhaps you misunderstand crab engineering? As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on. As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5: Move from 16 to 5: 66 fuel Move from 1 to 5: 10 fuel Move from 2 to 5: 6 fuel Move from 0 to 5: 15 fuel Move from 4 to 5: 1 fuel Move from 2 to 5: 6 fuel Move from 7 to 5: 3 fuel Move from 1 to 5: 10 fuel Move from 2 to 5: 6 fuel Move from 14 to 5: 45 fuel This costs a total of 168 fuel. This is the new cheapest possible outcome; the old alignment position (2) now costs 206 fuel instead. Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position? */ fun getResultPart2() { val crabsByPosition = getCrabs() var currentMinimumFuel = Int.MAX_VALUE (0..crabsByPosition.keys.maxOrNull()!!).forEach { target -> var fuelSpent = 0 for (entry in crabsByPosition.entries) { val position = entry.key val numberOfCrabsAtPosition = entry.value val distance = abs(position - target) val fuel = (.5 * distance.toDouble().pow(2) + .5 * distance).roundToInt() fuelSpent += fuel * numberOfCrabsAtPosition if (fuelSpent > currentMinimumFuel) { break } } if (fuelSpent < currentMinimumFuel) { currentMinimumFuel = fuelSpent } } println(currentMinimumFuel) } private fun getCrabs(): Map<Int, Int> { return getInputAsList()[0].split(",").map { it.toInt() }.groupBy { it }.mapValues { it.value.size } } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
5,081
advent-of-code
MIT License
src/main/kotlin/com/colinodell/advent2016/Day02.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day02(private val instructions: List<String>) { fun solvePart1(): String = getCode(instructions, partA) fun solvePart2(): String = getCode(instructions, partB) private val movements = mapOf( 'U' to Vector2(0, -1), 'D' to Vector2(0, 1), 'L' to Vector2(-1, 0), 'R' to Vector2(1, 0), ) private val partA: Grid<Char> = mapOf( Vector2(0, 0) to '1', Vector2(1, 0) to '2', Vector2(2, 0) to '3', Vector2(0, 1) to '4', Vector2(1, 1) to '5', Vector2(2, 1) to '6', Vector2(0, 2) to '7', Vector2(1, 2) to '8', Vector2(2, 2) to '9', ) private val partB: Grid<Char> = mapOf( Vector2(2, 0) to '1', Vector2(1, 1) to '2', Vector2(2, 1) to '3', Vector2(3, 1) to '4', Vector2(0, 2) to '5', Vector2(1, 2) to '6', Vector2(2, 2) to '7', Vector2(3, 2) to '8', Vector2(4, 2) to '9', Vector2(1, 3) to 'A', Vector2(2, 3) to 'B', Vector2(3, 3) to 'C', Vector2(2, 4) to 'D', ) private fun getCode(instructions: List<String>, keypad: Grid<Char>): String { var pos = keypad.entries.find { it.value == '5' }!!.key var code = "" instructions.forEach { line -> line.forEach { char -> val nextPosition = pos + movements[char]!! if (keypad.containsKey(nextPosition)) { pos = nextPosition } } code += keypad[pos] } return code } }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
1,634
advent-2016
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day08/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day08 import com.resurtm.aoc2023.utils.findListLCM fun launchDay08(testCase: String) { val input = readInput(testCase) println("Day 08, part 1: ${calculate(input)}") println("Day 08, part 2: ${calculateV2(input)}") } private fun calculateV2(inp: Input): Long = findListLCM(inp.points.keys.filter { it.last() == 'A' }.map { calculate(inp, start = it, end = "Z") }) private fun calculate(inp: Input, start: String = "AAA", end: String = "ZZZ"): Long { var currTurn = 0 var steps = 0L var point = start do { if (currTurn == inp.turns.length) currTurn = 0 val nextPoint = inp.points[point] ?: continue if (inp.turns[currTurn] == 'L') point = nextPoint.first else if (inp.turns[currTurn] == 'R') point = nextPoint.second currTurn++ steps++ } while (!point.endsWith(end)) return steps } private fun readInput(testCase: String): Input { val ex = Exception("Cannot read the input") val rawReader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() val reader = rawReader ?: throw ex val turns = reader.readLine() ?: throw ex val points = mutableMapOf<String, Pair<String, String>>() while (true) { val line = reader.readLine() ?: break if (line.indexOfAny(charArrayOf('=', ',')) == -1) continue val temp1 = line.split('=') val temp2 = temp1[1].split(',') val key = temp1[0].trim() val value = Pair(temp2[0].trim().trim('('), temp2[1].trim().trim(')')) points[key] = value } return Input(turns = turns, points = points) } private data class Input(val turns: String, val points: MutableMap<String, Pair<String, String>>)
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
1,748
advent-of-code-2023
MIT License
day20/Part1.kt
anthaas
317,622,929
false
null
import java.io.File fun main(args: Array<String>) { val tiles = File("input.txt").bufferedReader().use { it.readText() }.split("\n\n") .map { it.split("\n").let { it[0].replace(":", "").split(" ")[1].toLong() to it.subList(1, it.size) } } val result = tiles.map { tile1 -> var count = 0 tiles.map { tile2 -> if (tile1.first != tile2.first) { getTileEdges(tile1.second).map { if (it in getTileEdges(tile2.second)) count++ } getTileEdges(tile1.second).map { if (it in getTileEdges(tile2.second).map { it.reversed() }) count++ } } } tile1.first to count }.filter { it.second == 2 }.map { it.first }.reduce { acc, l -> acc * l } println(result) } private fun getTileEdges(tile: List<String>): List<String> = listOf( tile[0], tile.map { it.takeLast(1) }.joinToString(""), tile.last(), tile.map { it[0] }.joinToString("") )
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
950
Advent-of-Code-2020
MIT License