path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/com/kylecorry/sol/math/optimization/IterativeSimpleExtremaFinder.kt
kylecorry31
294,668,785
false
{"Kotlin": 714099, "Java": 18119, "Python": 298}
package com.kylecorry.sol.math.optimization import com.kylecorry.sol.math.Range import com.kylecorry.sol.math.Vector2 import kotlin.math.sqrt class IterativeSimpleExtremaFinder( initialStep: Double, finalStep: Double, levels: Int = 2 ) : IExtremaFinder { private val stepSizes = (1..levels).map { initialStep + (finalStep - initialStep) * (it - 1) / (levels - 1).toDouble() } private val initialFinder = SimpleExtremaFinder(initialStep) override fun find(range: Range<Double>, fn: (x: Double) -> Double): List<Extremum> { // Get the initial extremas var extremas = initialFinder.find(range, fn) // Fine tune the extremas for (level in 1..<stepSizes.size) { extremas = fineTune(extremas, fn, level) } return extremas } private fun fineTune( extremas: List<Extremum>, fn: (x: Double) -> Double, level: Int ): List<Extremum> { val nextExtremas = mutableListOf<Extremum>() for (extrema in extremas) { val nextRange = createRange(extrema, stepSizes[level - 1]) nextExtremas.add( findLevel( nextRange, fn, level, extrema.isHigh ) ) } return nextExtremas } private fun createRange(extremum: Extremum, stepSize: Double): Range<Double> { val start = extremum.point.x - stepSize val end = extremum.point.x + stepSize return Range(start, end) } private fun findLevel( range: Range<Double>, fn: (x: Double) -> Double, level: Int, isHigh: Boolean ): Extremum { val step = stepSizes[level] var targetX = range.start var targetY = fn(targetX) var currentX = range.start + step while (currentX <= range.end) { val currentY = fn(currentX) if (isHigh && currentY > targetY) { targetX = currentX targetY = currentY } else if (!isHigh && currentY < targetY) { targetX = currentX targetY = currentY } // Always check the last if (currentX != range.end && currentX + step > range.end) { currentX = range.end continue } currentX += step } return Extremum( Vector2(targetX.toFloat(), targetY.toFloat()), isHigh ) } }
11
Kotlin
4
8
ac1e4f9b3635e7b50a9668f74c9303c0152c94ce
2,578
sol
MIT License
src/test/kotlin/io/github/aarjavp/aoc/day04/Day04Test.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day04 import io.kotest.assertions.withClue import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.ints.shouldBeExactly import io.kotest.matchers.maps.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test internal class Day04Test { @Test fun parseBoard() { val testBoard = """ 11 2 3 4 55 6 7 8 99 """.trimIndent() val actual = Day04.BingoBoard.parseBoard(testBoard.lines()) actual.mapping shouldContainExactly mapOf( 11 to Day04.Location(0, 0), 2 to Day04.Location(1, 0), 3 to Day04.Location(2, 0), 4 to Day04.Location(0, 1), 55 to Day04.Location(1, 1), 6 to Day04.Location(2, 1), 7 to Day04.Location(0, 2), 8 to Day04.Location(1, 2), 99 to Day04.Location(2, 2), ) actual.gridSize shouldBeExactly 3 } fun sampleBoard(): Day04.BingoBoard { val raw = """ 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 """.trimIndent() return Day04.BingoBoard.parseBoard(raw.lines()) } @Test fun testMarking() { val board = sampleBoard() data class MarkCase(val n: Int, val expectedLocation: Day04.Location?) val cases = listOf<MarkCase>( MarkCase(2, Day04.Location(1, 1)), MarkCase(4, Day04.Location(3, 1)), MarkCase(36, null), MarkCase(24, Day04.Location(4, 1)), MarkCase(10, Day04.Location(1, 3)), MarkCase(19, Day04.Location(4, 4)), ) for (case in cases) { val actualLocation = board.mark(case.n) withClue("marking ${case.n}") { actualLocation shouldBe case.expectedLocation if (actualLocation != null) board.markedLocations shouldContain case.expectedLocation } } } @Test fun checkXWin() { val board = sampleBoard() val numbersToMark = listOf(22, 2, 14, 21, 12, 9, 7, 24, 18) // marking 16 will win on center row for (n in numbersToMark) { board.mark(n) withClue("marked $n") { board.hasWon() shouldBe false } } board.mark(16) board.hasWon() shouldBe true } @Test fun checkYWin() { val board = sampleBoard() val numbersToMark = listOf(22, 2, 14, 21, 12, 19, 8, 16, 1) // marking 6 will win on first col for (n in numbersToMark) { board.mark(n) withClue("marked $n") { board.hasWon() shouldBe false } } board.mark(6) board.hasWon() shouldBe true } val solution = Day04() val testInput = """ 7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 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 3 15 0 2 22 9 18 13 17 5 19 8 7 25 23 20 11 10 24 4 14 21 16 12 6 14 21 17 24 4 10 16 15 9 19 18 8 23 26 20 22 11 13 6 5 2 0 12 3 7 """.trimIndent() @Test fun part1() { val (numbers, boards) = solution.parseSetup(testInput.lineSequence()) val score = solution.part1(numbers, boards) score shouldBeExactly 4512 } @Test fun part2() { val (numbers, boards) = solution.parseSetup(testInput.lineSequence()) val score = solution.part2(numbers, boards) score shouldBeExactly 1924 } }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
3,676
advent-of-code-2021
MIT License
app/src/main/java/com/github/oheger/locationteller/map/TimeDeltaAlphaCalculator.kt
oheger
192,119,380
false
null
/* * Copyright 2019-2022 The Developers. * * 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.github.oheger.locationteller.map /** * An interface for a component that calculates an alpha value for a marker with a specific age. * * The idea is that position markers should be rendered more and more transparently the older they become. By having * different implementations of this interface, the fading out of old positions can be configured. */ interface TimeDeltaAlphaCalculator { /** * Calculate the alpha value for a marker with the given [age in milliseconds][ageMillis]. */ fun calculateAlpha(ageMillis: Long): Float } /** * A trivial implementation of [TimeDeltaAlphaCalculator], which does not apply any fading. Instead, it always returns * the alpha value of 1.0f. This implementation is used if old markers should not fade out. */ object DisabledFadeOutAlphaCalculator : TimeDeltaAlphaCalculator { override fun calculateAlpha(ageMillis: Long): Float = 1.0f } /** * A data class defining a range for an alpha calculation. * * The meaning of the properties of this class is that in a time range between the maximum time of the previous range * and the maximum time of this range, the alpha value decreases from [alphaMax] to [alphaMin]. */ data class AlphaRange( /** The maximum alpha value (at the beginning of the time range). */ val alphaMax: Float, /** The minimum alpha value (at the end of the time range). */ val alphaMin: Float, /** The end time of this range. */ val timeMax: Long ) /** * An implementation of [TimeDeltaAlphaCalculator] that calculates an alpha value based on a list of [AlphaRange] * objects. * * The calculator determines the first element in its ranges list, for which the maximum time is larger than the time * delta passed in. Then the properties of this range are used to determine the alpha value. With this approach, alpha * values can decrease with different speeds in different, non-linear intervals. */ class RangeTimeDeltaAlphaCalculator( /** The ranges to be used by this calculator (must be sorted). */ val ranges: List<AlphaRange>, /** * The minimum alpha value. This value is returned if the time delta * exceeds the last range defined for this object. */ val alphaMin: Float ) : TimeDeltaAlphaCalculator { override fun calculateAlpha(ageMillis: Long): Float { val rangeIdx = ranges.indexOfFirst { it.timeMax > ageMillis } return rangeIdx.takeIf { it >= 0 }?.let { idx -> val range = ranges[idx] val timeMin = if (idx > 0) ranges[idx - 1].timeMax else 0 with(range) { (alphaMax - alphaMin) / (timeMin - timeMax) * (ageMillis - timeMin) + alphaMax } } ?: alphaMin } }
0
Kotlin
1
1
b5ab4bc3a65a48d4fff7dbb9c72d7ff8f79db424
3,350
LocationTeller
Apache License 2.0
Fraction_reduction/Kotlin/src/Fraction.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}
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 } fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true } val pows = intArrayOf(1, 10, 100, 1_000, 10_000) fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum } fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() } for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
2,857
rosetta
MIT License
src/ch02/iterations.kt
nickaigi
191,916,746
false
null
package ch02 import java.util.* /* fizzbuzz: * - if any number is divisible by 3 = Fizz * - if any number is divisible by 5 = Buzz * - if number is divisible by both 3 and 5 = FizzBuzz */ fun fizzBuzz(i: Int) = when { i % 15 == 0 -> "FizzBuzz " i % 3 == 0 -> "Fizz " i % 5 == 0 -> "Buzz " else -> "$i " } fun exampleOne() { /* kotlin doesn't bring anything new to the 'while' and 'do while' loops * Kotlin has the 'for-each' loop */ var count = 1 while (count < 10) { println("count $count") count += 1 } do { println("count $count") count -= 1 } while (count > 0) } fun exampleTwo() { /* to define a range in kotlin, use the .. operator * start..stop * * stop is always part of the range * */ for (i in 1..100) { print(fizzBuzz(i)) } } fun exampleThree() { /* for loop with a step */ for (i in 100 downTo 1 step 2) { print(fizzBuzz(i)) } } fun exampleFour() { /* you can use 'until' * for (x in number until size) * * Key difference between 1..10 and 1 until 10 is that * * - 1..10 includes the stop number * - 1 until 10 does not include the stop number * * */ for (i in 1 until 30) { print(fizzBuzz(i)) } } fun exampleFive() { /* iterating over maps */ val binaryReps = TreeMap<Char, String>() /* the .. syntax for creating ranges works not only for numbers by for * characters as well */ for (c in 'A'..'F') { val binary = Integer.toBinaryString(c.toInt()) binaryReps[c] = binary } for ((letter, binary) in binaryReps) { println("$letter = $binary") } } fun exampleSix(){ val list = arrayListOf("10", "11", "1001") for ((index, element) in list.withIndex()) { println("$index: $element") } } fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z' fun isNotDigt(c: Char) = c !in '0'..'9' fun exampleSeven() { println(isLetter('q')) println(isNotDigt('x')) } fun recognize(c: Char): String { var s = when (c) { in '0'..'9' -> "It's a digit!" in 'a'..'z' -> "It's a lowercase letter!" in 'A'..'Z' -> "It's a uppercase letter!" else -> "I don't know ..." } return s } fun main(args: Array<String>) { println(recognize('Z')) }
0
Kotlin
0
0
bc2a547b47fb9531399110c15a60a14c606a419a
2,380
kotlin-in-action
The Unlicense
melif/src/main/kotlin/ru/ifmo/ctddev/isaev/dataset.kt
siviae
53,358,845
false
{"Kotlin": 152748, "Java": 152582}
package ru.ifmo.ctddev.isaev import java.util.* /** * @author iisaev */ abstract class DataSet(val name: String) { abstract fun getFeatureCount(): Int abstract fun getInstanceCount(): Int abstract fun toFeatureSet(): FeatureDataSet abstract fun toInstanceSet(): InstanceDataSet } class DataInstance(val name: String, val clazz: Int, val values: List<Int>) { constructor(clazz: Int, values: List<Int>) : this("", clazz, values) override fun toString() = name + ": " + clazz } class DataSetPair(val trainSet: DataSet, val testSet: DataSet) open class Feature(val name: String, val values: List<Int>) { constructor(values: List<Int>) : this("", values) override fun toString() = name } class FeatureDataSet(unSortedFeatures: List<Feature>, val classes: List<Int>, name: String) : DataSet(name) { val features = unSortedFeatures.sortedBy { it.name } init { if (!classes.stream().allMatch { i -> i == 0 || i == 1 }) { throw IllegalArgumentException("All classes values should be 0 or 1") } features.forEach { f -> if (f.values.size != classes.size) { throw IllegalArgumentException("ru.ifmo.ctddev.isaev.Feature ${f.name} has wrong number of values") } } } override fun toFeatureSet() = this override fun toInstanceSet(): InstanceDataSet { val instances = (0 until classes.size) .map { val values = ArrayList<Int>() features.forEach { feature -> values.add(feature.values[it]) } DataInstance("instance ${it + 1}", classes[it], values) } return InstanceDataSet(instances) } fun take(size: Int): FeatureDataSet { return FeatureDataSet(features.take(size), classes, name) } fun drop(size: Int): FeatureDataSet { return FeatureDataSet(features.drop(size), classes, name) } override fun getFeatureCount(): Int { return features.size } override fun getInstanceCount(): Int { return classes.size } } class InstanceDataSet(val instances: List<DataInstance>) : DataSet("") { override fun toFeatureSet(): FeatureDataSet { val classes = instances.map { it.clazz } val features = (0 until instances[0].values.size) .map { Feature(instances.map { inst -> inst.values[it] }) } return FeatureDataSet(features, classes, name) } override fun toInstanceSet(): InstanceDataSet { return this } override fun getFeatureCount(): Int { return instances[0].values.size } override fun getInstanceCount(): Int { return instances.size } }
0
Kotlin
0
1
2a3300ea32dda160d400258f2400c03ad84cb713
2,841
parallel-feature-selection
MIT License
year2023/src/main/kotlin/net/olegg/aoc/year2023/day23/Day23.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day23 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions import net.olegg.aoc.utils.Directions.Companion.NEXT_4 import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.get import net.olegg.aoc.year2023.DayOf2023 import java.util.PriorityQueue /** * See [Year 2023, Day 23](https://adventofcode.com/2023/day/23) */ object Day23 : DayOf2023(23) { private val WALL = setOf(null, '#') private val SLOPE = mapOf('^' to U, '<' to L, '>' to R, 'v' to D) override fun first(): Any? { val start = Vector2D(x = matrix.first().indexOf('.'), y = 0) val end = Vector2D(x = matrix.last().indexOf('.'), y = matrix.lastIndex) val nodes = buildList { add(start) matrix.forEachIndexed { y, row -> row.forEachIndexed { x, c -> val curr = Vector2D(x, y) if (c !in WALL && NEXT_4.count { matrix[curr + it.step] !in WALL } > 2) { add(curr) } } } add(end) } val edges = nodes.map { nodeStart -> buildMap(4) { val queue = ArrayDeque(listOf(nodeStart to setOf(nodeStart))) while (queue.isNotEmpty()) { val (curr, visited) = queue.removeFirst() if (curr != nodeStart && curr in nodes) { this[nodes.indexOf(curr)] = visited.size - 1 } else { queue += Directions.NEXT_4 .map { curr + it.step } .filter { it !in visited } .filter { matrix[it] !in WALL } .mapNotNull { when (val char = matrix[it]) { '.' -> it to visited + it in SLOPE -> { val slide = it + SLOPE[char]!!.step if (slide !in visited && matrix[slide] !in WALL) { slide to visited + setOf(it, slide) } else { null } } else -> null } } } } } } var best = 0 val seen = mutableSetOf<List<Int>>() val queue = PriorityQueue<List<Int>>( compareBy { -it.size }, ) queue.add(listOf(0)) while (queue.isNotEmpty()) { val path = queue.remove() if (!seen.add(path)) { continue } val curr = path.last() if (curr == nodes.lastIndex) { val size = path.zipWithNext { a, b -> edges[a][b]!! }.sum() if (best < size) { best = size } } queue += edges[curr] .filter { it.key !in path } .map { path + it.key } .filter { it !in seen } } return best } override fun second(): Any? { val start = Vector2D(x = matrix.first().indexOf('.'), y = 0) val end = Vector2D(x = matrix.last().indexOf('.'), y = matrix.lastIndex) val nodes = buildList { add(start) matrix.forEachIndexed { y, row -> row.forEachIndexed { x, c -> val curr = Vector2D(x, y) if (c !in WALL && NEXT_4.count { matrix[curr + it.step] !in WALL } > 2) { add(curr) } } } add(end) } val edges = nodes.map { nodeStart -> buildMap(4) { val queue = ArrayDeque(listOf(nodeStart to setOf(nodeStart))) while (queue.isNotEmpty()) { val (curr, visited) = queue.removeFirst() if (curr != nodeStart && curr in nodes) { this[nodes.indexOf(curr)] = visited.size - 1 } else { queue += Directions.NEXT_4 .map { curr + it.step } .filter { it !in visited } .filter { matrix[it] !in WALL } .map { it to visited + it } } } } } var best = 0 val seen = mutableSetOf<List<Int>>() val queue = PriorityQueue<List<Int>>( compareBy { -it.size }, ) queue.add(listOf(0)) while (queue.isNotEmpty()) { val path = queue.remove() if (!seen.add(path)) { continue } val curr = path.last() if (curr == nodes.lastIndex) { val size = path.zipWithNext { a, b -> edges[a][b]!! }.sum() if (best < size) { best = size } } queue += edges[curr] .filter { it.key !in path } .map { path + it.key } .filter { it !in seen } } return best } } fun main() = SomeDay.mainify(Day23)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
4,615
adventofcode
MIT License
src/main/kotlin/aoc2020/ex12.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
import kotlin.math.abs fun main() { val input = readInputFile("aoc2020/input12") // val input = """ // F10 // N3 // F7 // R90 // F11 // """.trimIndent() val sea = Sea(Ship(pos = Vector.ZERO, faceDir = Dir.E), Vector(s = -1, w = -10)) val lines = input.lines() val endSea = sea.transformIndexed(lines.size) { i -> val line = lines[i] operateInstruction(line) .also { println(it) } } println(endSea) println(endSea.ship.pos.l1()) } private fun Sea.operateInstruction(line: String): Sea { val command = SeaCommand.fromChar(line[0]) val amount = line.drop(1).toInt() //return copy(ship = ship.operateCommand(Command.fromChar(command), amount)) return operateCommand(command, amount) } private fun Sea.operateCommand(command: SeaCommand, amount: Int) : Sea { return when (command) { SeaCommand.N -> copy(waypoint = waypoint + Dir.N.v * amount) SeaCommand.W -> copy(waypoint = waypoint + Dir.W.v * amount) SeaCommand.S -> copy(waypoint = waypoint + Dir.S.v * amount) SeaCommand.E -> copy(waypoint = waypoint + Dir.E.v * amount) SeaCommand.L -> copy(waypoint = waypoint.rotate(-amount)) SeaCommand.R -> copy(waypoint = waypoint.rotate(amount)) SeaCommand.F -> moveShipForward(amount) } } private fun Sea.moveShipForward(amount: Int): Sea { val dir = waypoint val movement = dir * amount return copy(ship = ship.move(movement), waypoint = waypoint) } private fun Ship.operateCommand(command: SeaCommand, amount: Int): Ship { return when (command) { SeaCommand.N -> move(Dir.N, amount) SeaCommand.W -> move(Dir.W, amount) SeaCommand.S -> move(Dir.S, amount) SeaCommand.E -> move(Dir.E, amount) SeaCommand.L -> rotate(-amount) SeaCommand.R -> rotate(amount) SeaCommand.F -> forward(amount) } } data class Sea(val ship: Ship, val waypoint: Vector) //fun Sea.operateCommand(command: Command, amount: Int) { // return when (command) { // Command.N -> this.copy(ship.operateCommand(move(Dir.N, amount) // Command.W -> move(Dir.W, amount) // Command.S -> move(Dir.S, amount) // Command.E -> move(Dir.E, amount) // Command.L -> rotate(-amount) // Command.R -> rotate(amount) // Command.F -> forward(amount) // } //} data class Ship(val pos: Vector, val faceDir: Vector) { constructor(pos: Vector, faceDir: Dir): this(pos, faceDir.v) init { require(faceDir.isDir()) { "$faceDir is not unit"} } fun move(dir: Dir, amount: Int) = move(dir.v * amount) fun move(d: Vector) = copy(pos = pos + d) fun rotate(deg: Int) = copy(faceDir = faceDir.rotate(deg)) fun forward(units: Int) = copy(pos = pos + faceDir * units) } data class Vector(val s: Int, val w: Int) { operator fun plus(v: Vector) = copy(s = s + v.s, w = w + v.w) operator fun minus(v: Vector) = copy(s = s - v.s, w = w - v.w) operator fun times(i: Int) = copy(s = s * i, w = w * i) operator fun div(i: Int) = copy(s = s / i, w = w / i) fun isDir() = l1() == 1 fun l1() = abs(w) + abs(s) private fun rotate90(): Vector = copy(s = -w, w = s) private fun rotate270() = transform(3) { rotate90() } fun rotate(deg: Int): Vector { require(deg % 90 == 0) { "$deg is not mod 90" } val rotations = deg / 90 return if (rotations >= 0) { transform(rotations) { rotate90() } } else { transform(-rotations) { rotate270() } } } companion object { val ZERO = Vector(0, 0) } } enum class Dir(val v: Vector) { S(Vector(1, 0)), N(Vector(-1, 0)), W(Vector(0, 1)), E(Vector(0, -1)); } private enum class SeaCommand { N, W, S, E, L, R, F; companion object { fun fromChar(char: Char): SeaCommand = when (char) { 'N' -> N 'W' -> W 'S' -> S 'E' -> E 'L' -> L 'R' -> R 'F' -> F else -> error("cant") } } }
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
4,147
AOC-2021
MIT License
src/main/kotlin/kgp/tree/Tree.kt
JedS6391
90,571,337
false
null
package kgp.tree import java.util.* /** * Represents the different types of tree generation methods. * * [Grow] mode will generate trees with nodes chosen randomly from * the union of the function and terminal sets, allowing trees that are * smaller than the max depth to be created. This method generally produces * asymmetric trees. * * [Full] mode will generates tree with nodes chosen from the function set, * until the maximum depth is reached when it will start choosing from the * terminal set. This tends to grow "bushy" symmetrical trees. * * [HalfAndHalf] mode will use a 50/50 combination of the full and grow modes, * meaning the trees in the initial population will have a mix of shapes. */ enum class TreeGenerationMode { Grow, Full, HalfAndHalf } /** * Options that control tree generation by a [TreeGenerator]. * * @property maxDepth The maximum depth of trees generated. * @property numFeatures The number of features available to trees generated. * @property mode The method to use for generating tress. * @property constants A set of constants available to trees generated. */ data class TreeGeneratorOptions( val maxDepth: Int, val numFeatures: Int, val mode: TreeGenerationMode, val constants: List<Double> ) /** * Generates [Tree]s using a given function set and options. * * @property functions A function set made available to the trees generated. * @property options Controls the operation of the tree generator. */ class TreeGenerator(val functions: List<Function>, val options: TreeGeneratorOptions) { private val random = Random() /** * Generates a random tree using the functions and options of this generator. * * @returns A tree that represents some program. */ fun generateTree(): Tree { // Start the tree with a function to prevent degenerate trees. val root = this.random.choice(this.functions) val tree = Tree(mutableListOf(root), this) // Delegate to the appropriate tree generation mode. return when (this.options.mode) { TreeGenerationMode.Grow -> this.grow(tree) TreeGenerationMode.Full -> this.full(tree) TreeGenerationMode.HalfAndHalf -> this.rampedHalfAndHalf(tree) } } private fun grow(tree: Tree): Tree { val terminals = mutableListOf(tree.nodes.first().arity) while (terminals.isNotEmpty()) { val depth = terminals.size // Pick a random node from the union of the function and terminal set. val choice = this.random.nextInt(this.options.numFeatures + this.functions.size) if (depth < this.options.maxDepth && choice <= this.functions.size) { // Adding a function node. val node = this.random.choice(this.functions) tree.nodes.add(node) terminals.add(node.arity) } else { // Adding a terminal node either because we've reached maximum // depth or that was the randomly chosen node. // Add 1 to number of features to determine when to use constant. val idx = this.random.nextInt(this.options.numFeatures + 1) val node = if (idx == this.options.numFeatures) { Constant(this.random.choice(this.options.constants)) } else { Input(idx) } tree.nodes.add(node) terminals[terminals.lastIndex] -= 1 while (terminals.last() == 0) { terminals.removeAt(terminals.lastIndex) if (terminals.isEmpty()) { return tree } terminals[terminals.lastIndex] -= 1 } } } // Shouldn't get here throw Exception("Error during tree construction.") } private fun full(tree: Tree): Tree { val terminals = mutableListOf(tree.nodes.first().arity) while (terminals.isNotEmpty()) { val depth = terminals.size if (depth < this.options.maxDepth) { // Adding a function node. val node = this.random.choice(this.functions) tree.nodes.add(node) terminals.add(node.arity) } else { // Adding a terminal node either because we've reached maximum // depth or that was the randomly chosen node. // Add 1 to number of features to determine when to use constant. val idx = this.random.nextInt(this.options.numFeatures + 1) val node = if (idx == this.options.numFeatures) { Constant(this.random.choice(this.options.constants)) } else { Input(idx) } tree.nodes.add(node) terminals[terminals.lastIndex] -= 1 while (terminals.last() == 0) { terminals.removeAt(terminals.lastIndex) if (terminals.isEmpty()) { return tree } terminals[terminals.lastIndex] -= 1 } } } // Shouldn't get here throw Exception("Error during tree construction.") } private fun rampedHalfAndHalf(tree: Tree): Tree { if (this.random.nextDouble() < 0.5) { return this.grow(tree) } else { return this.full(tree) } } } /** * Represents a program as a tree of nodes. * * Internally, we keep a simple list of nodes that is the "program". * * @property nodes A collection of nodes that make up this tree. * @property treeGenerator The tree generator used to create this tree (or its parent tree) */ class Tree(var nodes: MutableList<Node>, val treeGenerator: TreeGenerator) { /** * The fitness of this tree as based on some data set. * * Initially, the value will be set to a high constant (1e9) to penalise programs * that haven't had their fitness evaluated yet. */ var fitness = 1e9 /** * Executes the trees program on a set of inputs. * * @param case A collection of inputs to make available to the program. * @returns The output of the program for the given inputs. */ fun execute(case: List<Double>): Double { val node = this.nodes.first() when (node) { is Constant -> return node.value is Input -> return case[node.index] } val stack = mutableListOf<MutableList<Node>>() for (node in this.nodes) { if (node is Function) { stack.add(mutableListOf(node)) } else { stack[stack.lastIndex].add(node) } while (stack.last().size == stack.last()[0].arity + 1) { val function = stack.last()[0] val range = 1..stack.last().lastIndex val terminals = stack.last().slice(range).map { term -> when (term) { is Constant -> term.value is Input -> case[term.index] else -> throw Exception("Unexpected terminal type.") } } val result = function.evaluate(terminals) if (stack.size != 1) { stack.removeAt(stack.lastIndex) stack.last().add(Constant(result)) } else { return result } } } throw Exception("Failed to execute tree.") } /** * Creates a copy of this tree. All nodes are copied too. */ fun copy(): Tree { return Tree(this.nodes.map { n -> n }.toMutableList(), this.treeGenerator) } internal fun getRandomSubtree(program: List<Node> = this.nodes): Pair<Int, Int> { val random = Random() val probs = program.map { n -> when (n) { is Function -> 0.9 else -> 0.1 } } val normalised = probs.map { p -> p / probs.sum() }.cumulativeSum() var stack = 1 val start = normalised.insertionPoint(random.nextDouble()) var end = start while (stack > (end - start)) { val node = program[end] stack += (node as? Function)?.arity ?: 0 end += 1 } return Pair(start, end) } /** * Performs the crossover operation on this tree and the tree given. * * Note that this operation directly modifies the tree that initiates the operation. * * @param other The tree to perform crossover with. */ fun crossover(other: Tree) { // Subtree from ourselves val (start, end) = this.getRandomSubtree() // Subtree from other val (otherStart, otherEnd) = other.getRandomSubtree() // Transfer genetic material from other tree. this.nodes = ( this.nodes.subList(0, start) + other.nodes.subList(otherStart, otherEnd) + this.nodes.subList(end, this.nodes.size) ).toMutableList() } /** * Performs the point mutation operation on this tree. * * Point mutation works by choosing a collection of random nodes in the * tree to be replaced and then replacing each with another random node. * * Note that this operation directly modifies the tree that initiates the operation. * * @param replacementRate The frequency with which replacements should occur. */ fun pointMutation(replacementRate: Double) { val nodes = this.copy().nodes val random = Random() val options = this.treeGenerator.options // Get nodes to modify val mutate = (0..nodes.size - 1).map { idx -> val replace = random.nextDouble() < replacementRate Pair(idx, replace) }.filter { (_, replace) -> replace }.map { (idx, _) -> idx } mutate.map { node -> when (this.nodes[node]) { is Function -> { // Find another function with the same arity val arity = this.nodes[node].arity val replacements = this.treeGenerator.functions.filter { func -> func.arity == arity } val replacement = random.choice(replacements) this.nodes[node] = replacement } else -> { // Terminal val idx = random.nextInt(options.numFeatures + 1) val term = if (idx == options.numFeatures) { // Add small amount of noise to a constant Constant(random.choice(options.constants) + random.nextGaussian()) } else { Input(idx) } this.nodes[node] = term } } } } /** * Performs the subtree mutation operation on this tree. * * This is achieved by creating a new randomly generated tree and performing crossover * with that new randomly generated tree. * * Note that this operation directly modifies the tree that initiates the operation. */ fun subtreeMutation() { val other = this.treeGenerator.generateTree() this.crossover(other) } /** * Performs the hoist mutation operation on this tree. * * Operates by choosing a random subtree of this tree, and then a random subtree * within that subtree and replacing the first subtree by the second. This effectively * "hoists" the subtree's subtree further up in the original tree. * * Note that this operation directly modifies the tree that initiates the operation. */ fun hoistMutation() { // Find a subtree to replace val (start, end) = this.getRandomSubtree() val subtree = this.nodes.subList(start, end) // Get a subtree of the subtree to hoist val (subStart, subEnd) = this.getRandomSubtree(subtree) val hoist = subtree.subList(subStart, subEnd) this.nodes = ( this.nodes.subList(0, start) + hoist + this.nodes.subList(end, this.nodes.size) ).toMutableList() } /** * Prints the tree as an S-expression. * * @returns A string representation of this tree as an S-expression. */ override fun toString(): String { val terminals = mutableListOf(0) val sb = StringBuilder() this.nodes.forEachIndexed { idx, node -> if (node is Function) { terminals.add(node.arity) sb.append("(") sb.append(node.representation) sb.append(" ") } else { when (node) { is Constant -> sb.append(node.value) is Input -> { sb.append("x[") sb.append(node.index) sb.append("]") } } terminals[terminals.lastIndex] -= 1 while (terminals[terminals.lastIndex] == 0) { terminals.removeAt(terminals.lastIndex) terminals[terminals.lastIndex] -= 1 sb.append(")") } if (idx != this.nodes.size - 1) { sb.append(" ") } } } return sb.toString() } } /** * @suppress */ fun <T> Random.choice(list: List<T>): T { return list[(this.nextDouble() * list.size).toInt()] } /** * @suppress */ fun List<Double>.cumulativeSum(): List<Double> { var total = 0.0 return this.map { v -> total += v total } } /** * @suppress */ fun List<Double>.insertionPoint(value: Double): Int { var low = 0 var high = this.size while (low < high) { // Use bit-shift instead of divide by 2. val middle = (low + high) ushr 1 when { value <= this[middle] -> high = middle else -> low = middle + 1 } } return low }
0
Kotlin
0
1
045fd23e0fac9ea31c20489ae459bd168846d30b
14,621
KGP
MIT License
sandbox/src/main/kotlin/tomasvolker/numeriko/sandbox/co2/Regression.kt
TomasVolker
114,266,369
false
null
package tomasvolker.numeriko.sandbox.co2 import koma.extensions.get import koma.fill import koma.matrix.Matrix import kotlin.math.pow fun regressionMatrix(evaluationPoints: Matrix<Double>, basisFunctions: List<(Double)->Double>) = fill(evaluationPoints.numRows(), basisFunctions.size) { row, col -> basisFunctions[col](evaluationPoints[row]) } fun polynomialRegressionMatrix(evaluationPoints: Matrix<Double>, order: Int = 1) = regressionMatrix( evaluationPoints = evaluationPoints, basisFunctions = buildPolynomialBasisFunctions(order) ) fun buildPolynomialBasisFunctions(order: Int): List<(Double)->Double> = List(order + 1) { i -> { x: Double -> x.pow(i) } } fun linearRegressionMatrix(evaluationPoints: Matrix<Double>) = polynomialRegressionMatrix(evaluationPoints, 1) fun regression( x: List<Number>, y: List<Number>, basisFunctions: List<(Double)->Double> ): (Double)->Double { val xMat = x.toColMatrix() val yMat = y.toColMatrix() val X = regressionMatrix(xMat, basisFunctions) val weights = (X.transpose() * X).solve(X.transpose() * yMat).toList() return { input: Double -> val basisFunctionSequence = basisFunctions.asSequence() val weightSequence = weights.asSequence() basisFunctionSequence.map { it(input) } .zip(weightSequence). sumByDouble { it.first * it.second } } } fun polynomialRegression( x: List<Number>, y: List<Number>, order: Int ) = regression( x = x, y = y, basisFunctions = buildPolynomialBasisFunctions(order) ) fun linearRegression( x: List<Number>, y: List<Number> ) = polynomialRegression( x = x, y = y, order = 1 )
8
Kotlin
1
3
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
1,762
numeriko
Apache License 2.0
2020/src/main/kotlin/de/skyrising/aoc2020/day3/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2020.day3 import de.skyrising.aoc.* @PuzzleName("Toboggan Trajectory") fun PuzzleInput.part1v0(): Any { var trees = 0 var x = 0 for (line in lines) { val tree = line[x % line.length] == '#' if (tree )trees++ x += 3 } return trees } @PuzzleName("Toboggan Trajectory") fun PuzzleInput.part1v1(): Any { var trees = 0 var x = 0 val len = byteLines[0].remaining() for (line in byteLines) { val tree = line[x] == '#'.code.toByte() if (tree) trees++ x = wrap(x + 3, len) } return trees } fun PuzzleInput.part2v0(): Any { val slopes = intArrayOf(1, 3, 5, 7, 1) val step = intArrayOf(1, 1, 1, 1, 2) val trees = LongArray(5) val x = intArrayOf(0, 0, 0, 0, 0) for ((lineCount, line) in lines.withIndex()) { for (i in 0..4) { if (lineCount % step[i] == 0) { val tree = line[x[i] % line.length] == '#' if (tree) trees[i]++ x[i] += slopes[i] } } } //trees.contentToString() return trees.reduce {a, b -> a * b} } fun PuzzleInput.part2v1(): Any { var t0 = 0 var t1 = 0 var t2 = 0 var t3 = 0 var t4 = 0 var x0 = 0 var x1 = 0 var x2 = 0 var x3 = 0 var x4 = 0 val len = byteLines[0].remaining() for ((lineCount, line) in byteLines.withIndex()) { t0 += if (line[x0] == '#'.code.toByte()) 1 else 0 x0 = wrap(x0 + 1, len) if (x0 >= len) x0 -= len t1 += if (line[x1] == '#'.code.toByte()) 1 else 0 x1 = wrap(x1 + 3, len) if (x1 >= len) x1 -= len t2 += if (line[x2] == '#'.code.toByte()) 1 else 0 x2 = wrap(x2 + 5, len) if (x2 >= len) x2 -= len t3 += if (line[x3] == '#'.code.toByte()) 1 else 0 x3 = wrap(x3 + 7, len) if (x3 >= len) x3 -= len if (lineCount % 2 == 0) { t4 += if (line[x4] == '#'.code.toByte()) 1 else 0 x4 = wrap(x4 + 1, len) if (x4 >= len) x4 -= len } } return t0.toLong() * t1 * t2 * t3 * t4 } inline fun wrap(x: Int, len: Int) = x - if (x >= len) len else 0
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
2,198
aoc
MIT License
src/day25/Day25.kt
crmitchelmore
576,065,911
false
{"Kotlin": 115199}
package day25 import helpers.ReadFile import java.math.BigInteger class Day25 { fun parseSnafu(string: String) : Long { val chars = string.split("").filter { it.isNotEmpty() }.reversed() var mult = 1L var total = 0L for (char in chars) { if (char.toCharArray().first().isDigit()) { total += char.toLong() * mult } else if (char == "-") { total -= mult } else { total -= 2 * mult } mult *= 5 } return total } fun toSnafu(long: Long) : String { println("Long: $long Base 5: ${BigInteger.valueOf(long).toString(5)} Back: ${BigInteger.valueOf(long).toString(5).toBigInteger(5).toString(10)}") var base5 = BigInteger.valueOf(long).toString(5).split("").filter { it.isNotEmpty() }.map{ it.toInt() }.reversed().toMutableList() var result = "" //12322024001244014000 //2==221=-002=0-02-000 for (i in base5.indices) { if (base5[i] > 4) { base5[i] -= 5 if (i+1 == base5.size) { base5.add(1) } else { base5[i + 1] += 1 } } if (base5[i] < 3) { result = base5[i].toString() + result } else { if (i+1 == base5.size) { base5.add(0) } base5[i+1] += 1 result = (if (base5[i] == 4) "-" else "=") + result } } return result } val lines = ReadFile.named("src/day25/input.txt") fun result1() { val nums = lines.map { BigInteger.valueOf(parseSnafu(it)) } val total = nums.fold(BigInteger.valueOf(0L)) { a, b -> a + b } //29361331235500 //33939944735375 println(parseSnafu("2--221-=002-0=02=000")) // println(toSnafu(total.toLong())) } //2--221-=002-==02=000. //2--221-=002-0=02=000 //2==221=-002=0-02-000 }
0
Kotlin
0
0
fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470
2,089
adventofcode2022
MIT License
src/main/kotlin/net/dilius/daily/coding/problem/n00x/001.kt
diliuskh
298,020,928
false
null
package net.dilius.daily.coding.problem.n00x import net.dilius.daily.coding.problem.Problem /* Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? */ data class Input(val nums: List<Int>, val k: Int) class AddsUpToNum : Problem<Input, Boolean> { override fun solve(input: Input): Boolean { val (nums, k) = input for (i in nums.indices) { if (nums[i] > k) continue for (j in i+1 until nums.size) { if (nums[j] > k) continue if (nums[i] + nums[j] == k) return true } } return false } } class AddsUpToNumFast : Problem<Input, Boolean> { override fun solve(input: Input): Boolean { val checked = mutableSetOf<Int>() val (nums, k) = input for (i in nums.indices) { if (nums[i] > k) continue if (checked.contains(k - nums[i])) return true checked.add(nums[i]) } return false } }
0
Kotlin
0
0
7e5739f87dbce2b56d24e7bab63b6cee6bbc54bc
1,131
dailyCodingProblem
Apache License 2.0
src/main/kotlin/ValidParenthese.kt
mececeli
553,346,819
false
{"Kotlin": 9018}
import java.util.* //Valid Parentheses //Easy //16.9K //871 //Companies //Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // //An input string is valid if: // //Open brackets must be closed by the same type of brackets. //Open brackets must be closed in the correct order. //Every close bracket has a corresponding open bracket of the same type. // // //Example 1: // //Input: s = "()" //Output: true //Example 2: // //Input: s = "()[]{}" //Output: true //Example 3: // //Input: s = "(]" //Output: false // // //Constraints: // //1 <= s.length <= 104 //s consists of parentheses only '()[]{}'. fun isValidParentheses(s: String): Boolean { if (s.length % 2 == 1) return false val openingBrackets: MutableList<Char> = mutableListOf() val closingBrackets: MutableList<Char> = mutableListOf() s.forEach { char -> if (isOpeningBracket(char)) { openingBrackets.add(char) } else { closingBrackets.add(char) } } if (openingBrackets.size == closingBrackets.size) { openingBrackets.forEachIndexed { index, char -> if (isSameTypeBracket(openingChar = char, closingChar = closingBrackets[index]).not()) { return false } return true } } else { return false } return false } fun isOpeningBracket(char: Char): Boolean = when (char) { '(', '[', '{' -> true else -> false } fun isSameTypeBracket(openingChar: Char, closingChar: Char): Boolean { if (openingChar == '(' && closingChar == ')') return true if (openingChar == '[' && closingChar == ']') return true if (openingChar == '{' && closingChar == '}') return true return false } //----------------------------------------------------------------------------- Stack Solution fun isValidParenthesesStack(s: String): Boolean { if (s.length % 2 != 0) return false val map = mapOf('}' to '{', ')' to '(', ']' to '[') val stack = Stack<Char>() s.forEach { if (it == '}' || it == ')' || it == ']') { if (stack.isEmpty() || stack.peek() != map[it]) return false stack.pop() } else stack.push(it) } return stack.isEmpty() }
0
Kotlin
0
0
d05ee9d32c42d11e71e136f4138bb0335114f360
2,283
Kotlin_Exercises
Apache License 2.0
ArrayTools.kt
chynerdu
650,674,895
false
null
fun main() { println("Hello World") println(averageArray(arrayOf(1, 2, 2, 4, 4))) println(averageArray(arrayOf(1, -2, -2, 4, 4))) println(checkValueExistence(arrayOf(1, 2, 2, 4, 4), 8)) println(reverseArray(arrayOf(1, 2, 3, 4, 5, 6, 7, 34, 28))) val ciphertext = caesarCipherFunc() println(ciphertext) println(findMaxValue(arrayOf(-1, -2, -3, -4, -5))) } /** * Find the average of an array * @param inputArray contains the array to be averaged * @return the average of type Double */ fun averageArray(inputArray: Array<Int>): Double { var listSum = 0.0 for (datax in inputArray) { listSum += datax } return listSum / inputArray.size } /** * Check if a value exist in an array * @param valueList contains an array of string * @param value is the value to check if it exist in the array * @return A boolean value if the value exists or not */ fun checkValueExistence(valueList: Array<Int>, value: Int): Boolean { for (x in valueList) { if (x == value) { return true } } return false } /** * Reverse an array * @param inputArray contains the array to be reversed * @return A mutable list of the reversed array */ fun reverseArray(inputArray: Array<Int>): MutableList<Int> { var reversedList = MutableList<Int>(inputArray.size) { 0 } var index = inputArray.size - 1 println(index) for (num in inputArray) { reversedList[index] = num index-- } return reversedList } /** * Caeser Cipher function encrypts the string entered by the user by a specific shift value * @return An encrypted string */ fun caesarCipherFunc(): String { try { val shiftedText = StringBuilder() println("Enter input string to encrypt") val stringValue = readLine() println("Enter the shift value") val shift = readLine()?.toInt() if (!stringValue.isNullOrEmpty() && shift != null) { for (char in stringValue) { if (char.isLetter()) { val startOffset = if (char.isUpperCase()) 'A' else 'a' val shiftedChar = (((char.toInt() - startOffset.toInt()) + shift) % 26 + startOffset.toInt()).toChar() shiftedText.append(shiftedChar) } else { shiftedText.append(char) } } } return shiftedText.toString() } catch (e: NumberFormatException) { return "Invalid input entered" } } fun findMaxValue(inputList: Array<Int>): Int { var maxValue = Int.MIN_VALUE for (value in inputList) { if (value > maxValue) { maxValue = value } } return maxValue }
0
Kotlin
0
0
74926900639459e3ad2b939c6916ea5d5f81e1e8
2,743
JAV1001-Lab2
MIT License
src/Day06.kt
risboo6909
572,912,116
false
{"Kotlin": 66075}
fun main() { fun findUniq(line: String, windowSize: Int): Int? { val window = ArrayDeque<Char>(windowSize+1) for ((i, s) in line.withIndex()) { window.addLast(s) if (window.size == windowSize+1) { window.removeFirst() } if (window.size == windowSize) { if (window.toSet().size == windowSize) { return i + 1 } } } return null } fun part1(input: List<String>): Int? { return findUniq(input.last(), 4) } fun part2(input: List<String>): Int? { return findUniq(input.last(), 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd6f9b46d109a34978e92ab56287e94cc3e1c945
957
aoc2022
Apache License 2.0
plugin/src/main/kotlin/nl/tudelft/hyperion/plugin/metric/APIMetric.kt
SERG-Delft
254,399,628
false
null
package nl.tudelft.hyperion.plugin.metric /** * Represents an element as the result of an /api/v1/metrics API call. * Contains the aggregated log counts over the specified interval, i.e. * an interval of 60 represents the logs that happened in the last minute. */ data class APIMetricsResult( val interval: Int, /** * A mapping of version to a List of Metrics (all metrics relative to this version). * The version is represented by a String. */ val versions: Map<String, List<APIMetric>> ) /** * Represents the response from an /api/v1/metrics/period API call. * * @param T signifies if this is project wide or file specific bin metrics. * @property interval the time in seconds between each [APIBinMetricsResult]. * @property results a list of metrics for each interval which contains a map * of versions and corresponding line metrics. */ data class APIBinMetricsResponse<T : BaseAPIMetric>( val interval: Int, val results: List<APIBinMetricsResult<T>> ) { fun filterVersion(version: String, lineNumber: Int) = results.map { it.filterVersion(version, lineNumber) } } /** * Represents an element as the result of an /api/v1/metrics/period API call. * The API call returns a list of bins where each bin is the aggregated log * counts starting from the given start time. * * @param T signifies if this is project wide or file specific bin metrics. * @property startTime unix epoch time in seconds of the starting time of this * bin. * @property versions map of version identifier with metrics. */ data class APIBinMetricsResult<T : BaseAPIMetric>( val startTime: Int, val versions: MutableMap<String, List<T>> ) { fun filterVersion(version: String, lineNumber: Int) { if (version in versions) { versions[version] = versions[version]?.filter { it.line == lineNumber }!! } } } /** * The base class for all metrics. * * @property line the log line for which this metrics was triggered. * @property severity the log severity of this log line. * @property count the number of times this line has been triggered. */ sealed class BaseAPIMetric( open val line: Int, open val severity: String, open val count: Int ) /** * Represents a single grouped metric of a (project, file, line, version, * severity) tuple. Contains the line for which it was triggered, the * severity of the log and the amount of times that specific log was * triggered. */ data class APIMetric( override val line: Int, override val severity: String, override val count: Int ) : BaseAPIMetric(line, severity, count) /** * Represents a single grouped metric of a (project, file, line, version, * severity) tuple. Contains the line for which it was triggered, the * severity of the log and the amount of times that specific log was * triggered. */ data class FileAPIMetric( override val line: Int, override val severity: String, override val count: Int, val file: String ) : BaseAPIMetric(line, severity, count)
0
Kotlin
1
13
a010d1b6e59592231a2ed29a6d11af38644f2834
3,047
hyperion
Apache License 2.0
kotlin/126.Word Ladder II(单词接龙 II).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Given two words (<em>beginWord</em> and <em>endWord</em>), and a dictionary&#39;s word list, find all shortest transformation sequence(s) from <em>beginWord</em> to <em>endWord</em>, such that:</p> <ol> <li>Only one letter can be changed at a time</li> <li>Each transformed word must exist in the word list. Note that <em>beginWord</em> is <em>not</em> a transformed word.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>Return an empty list if there is no such transformation sequence.</li> <li>All words have the same length.</li> <li>All words contain only lowercase alphabetic characters.</li> <li>You may assume no duplicates in the word list.</li> <li>You may assume <em>beginWord</em> and <em>endWord</em> are non-empty and are not the same.</li> </ul> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output:</strong> [ [&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;], &nbsp; [&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] ] </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot; endWord = &quot;cog&quot; wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output: </strong>[] <strong>Explanation:</strong>&nbsp;The endWord &quot;cog&quot; is not in wordList, therefore no possible<strong>&nbsp;</strong>transformation. </pre> <ul> </ul> <p>给定两个单词(<em>beginWord</em> 和 <em>endWord</em>)和一个字典 <em>wordList</em>,找出所有从 <em>beginWord </em>到 <em>endWord </em>的最短转换序列。转换需遵循如下规则:</p> <ol> <li>每次转换只能改变一个字母。</li> <li>转换过程中的中间单词必须是字典中的单词。</li> </ol> <p><strong>说明:</strong></p> <ul> <li>如果不存在这样的转换序列,返回一个空列表。</li> <li>所有单词具有相同的长度。</li> <li>所有单词只由小写字母组成。</li> <li>字典中不存在重复的单词。</li> <li>你可以假设 <em>beginWord</em> 和 <em>endWord </em>是非空的,且二者不相同。</li> </ul> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>输出:</strong> [ [&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;], &nbsp; [&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] ] </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot; endWord = &quot;cog&quot; wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>输出: </strong>[] <strong>解释:</strong>&nbsp;<em>endWord</em> &quot;cog&quot; 不在字典中,所以不存在符合要求的转换序列。</pre> <p>给定两个单词(<em>beginWord</em> 和 <em>endWord</em>)和一个字典 <em>wordList</em>,找出所有从 <em>beginWord </em>到 <em>endWord </em>的最短转换序列。转换需遵循如下规则:</p> <ol> <li>每次转换只能改变一个字母。</li> <li>转换过程中的中间单词必须是字典中的单词。</li> </ol> <p><strong>说明:</strong></p> <ul> <li>如果不存在这样的转换序列,返回一个空列表。</li> <li>所有单词具有相同的长度。</li> <li>所有单词只由小写字母组成。</li> <li>字典中不存在重复的单词。</li> <li>你可以假设 <em>beginWord</em> 和 <em>endWord </em>是非空的,且二者不相同。</li> </ul> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>输出:</strong> [ [&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;], &nbsp; [&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] ] </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot; endWord = &quot;cog&quot; wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>输出: </strong>[] <strong>解释:</strong>&nbsp;<em>endWord</em> &quot;cog&quot; 不在字典中,所以不存在符合要求的转换序列。</pre> **/ class Solution { fun findLadders(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
4,837
leetcode
MIT License
src/day17/d17_2.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val jugs = input.lines().map { it.toInt() } // dynamic programming array // dp[n][r][c] = number of ways to fill capacity "c" when using exactly "r" of the first "n" jugs val dp = Array(jugs.size + 1) { Array(jugs.size + 1) { Array(150 + 1) { 0 } } } (1 until dp.size).forEach { n -> (1 until dp[n].size).forEach { r -> (1 until dp[n][r].size).forEach { c -> dp[n][r][c] = dp[n - 1][r][c] + if (jugs[n - 1] > c) 0 else if (jugs[n - 1] < c) dp[n - 1][r - 1][c - jugs[n - 1]] else 1 } } } println(dp.last().map { it.last() }.find { it > 0 }) }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
682
aoc2015
MIT License
src/main/java/challenges/leetcode/PalindromeNumber.kt
ShabanKamell
342,007,920
false
null
package challenges.leetcode import java.util.* /** Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is a palindrome while 123 is not. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -231 <= x <= 231 - 1 Follow up: Could you solve it without converting the integer to a string? */ object PalindromeNumber { private fun isPalindrome(x: Int): Boolean { if (x < 0) return false return isPalindrome(x.toString()) } private fun isPalindrome(s: String): Boolean { val length = s.length val chars = s.toCharArray() for (i in s.indices) { if (chars[i] != chars[length - i - 1]) return false } return true } private fun isPalindrome2(s: String): Boolean { val length = s.length val chars = s.toCharArray() var fast = 0 var slow = 0 val stack = Stack<Char>() while (fast < length - 1) { stack.push(chars[slow]) fast += 2 slow++ } // Skip the middle slow++ while (stack.isNotEmpty()) { val item = stack.pop() if (chars[slow] != item) return false slow++ } return true } fun isPalindrome3(_num: Int): Boolean { var num = _num if (num < 0) return false var reversed = 0 var remainder: Int val original = num while (num != 0) { // reversed integer is stored in variable remainder = num % 10 // multiply reversed by 10 then add the remainder, so it gets stored at next decimal place. reversed = reversed * 10 + remainder // the last digit is removed from num after division by 10. num /= 10 } // palindrome if original and reversed are equal return original == reversed } @JvmStatic fun main(args: Array<String>) { var x = 13231 println("$x: ${isPalindrome(x)}") println("$x: ${isPalindrome2(x.toString())}") println("$x: ${isPalindrome3(x)}") x = 132311 println("$x: ${isPalindrome(x)}") println("$x: ${isPalindrome2(x.toString())}") println("$x: ${isPalindrome3(x)}") } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,720
CodingChallenges
Apache License 2.0
src/main/kotlin/ctci/chapterten/SearchInRotatedArray.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chapterten // 10.3 - page 150 // Given a sorted array of n integers that has been rotated an unknown number of times, write Kotlin code to // find an element in the array. You may assume that the array was originally sorted in increasing order. fun main() { val arr = intArrayOf(15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14) val target = 5 val index = binarySearch(arr, 0, arr.size - 1, target) if (index != -1) { println("Element found at index: $index") } else { println("Element not found") } } //use binary search to find the target element in the sorted and rotated array. We compare the middle element of the // array with the target element, and depending on which half of the array is sorted, we either continue the search in // the left half or the right half of the array. If the target is not found, the function returns -1. fun binarySearch(arr: IntArray, low: Int, high: Int, target: Int): Int { if (low > high) return -1 val mid = (low + high) / 2 if (arr[mid] == target) return mid // If left side of mid is sorted if (arr[low] <= arr[mid]) { if (target >= arr[low] && target <= arr[mid]) { return binarySearch(arr, low, mid - 1, target) } else { return binarySearch(arr, mid + 1, high, target) } } else { if (target >= arr[mid] && target <= arr[high]) { return binarySearch(arr, mid + 1, high, target) } else { return binarySearch(arr, low, mid - 1, target) } } } //The time complexity of this algorithm is O(log n), because it uses binary search to search for the element in the // array. The space complexity is O(1), because the algorithm only uses a few variables to store intermediate results, // and does not require any additional data structures.
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,850
dsa-kotlin
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day04.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year18 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.mostFrequent import com.grappenmaker.aoc.splitInts import java.text.SimpleDateFormat import java.time.ZoneOffset fun PuzzleSet.day4() = puzzle { // Wacky way to do this stuff val format = SimpleDateFormat("yyyy-MM-dd HH:mm") val events = inputLines.sorted().map { l -> val timePart = l.substringAfter('[').substringBefore(']') val minute = format.parse(timePart).toInstant().atZone(ZoneOffset.UTC).minute when { "begins shift" in l -> GuardStartShift(minute, l.splitInts().last()) "falls asleep" in l -> GuardSleep(minute) "wakes up" in l -> GuardWakeUp(minute) else -> error("Invalid guard message $l") } } // Double parsing, prob should've avoided val shifts = buildList { var current = events.first() as GuardStartShift var sleepTime = current.minute for (event in events) { when (event) { is GuardStartShift -> current = event is GuardSleep -> sleepTime = event.minute is GuardWakeUp -> add(GuardShift(current.id, current.minute, sleepTime, event.minute)) } } }.groupBy { it.id } // Actual solution, lol val sleepIndex = shifts.mapValues { (_, t) -> t.flatMap { (it.sleep..<it.wake).toList() } } val (p1ID, targetMinutes) = sleepIndex.maxBy { (_, v) -> v.size } val bestMinute = targetMinutes.mostFrequent() partOne = (p1ID * bestMinute).s() val (p2ID, globalBestMinute) = sleepIndex.flatMap { (k, v) -> v.map { t -> k to t } }.mostFrequent() partTwo = (p2ID * globalBestMinute).s() } sealed interface GuardEvent { val minute: Int } data class GuardStartShift(override val minute: Int, val id: Int) : GuardEvent data class GuardWakeUp(override val minute: Int) : GuardEvent data class GuardSleep(override val minute: Int) : GuardEvent data class GuardShift(val id: Int, val start: Int, val sleep: Int, val wake: Int)
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,074
advent-of-code
The Unlicense
src/main/kotlin/bk66/Problem3.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package bk66 fun main() { val result = Problem3().minCost(intArrayOf(0, 3), intArrayOf(2, 3), intArrayOf(5, 4, 3), intArrayOf(8, 2, 6, 7)) println(result) } class Problem3 { fun minCost(startPos: IntArray, homePos: IntArray, rowCosts: IntArray, colCosts: IntArray): Int { val startI = startPos[0] val startJ = startPos[1] val homeI = homePos[0] val homeJ = homePos[1] if (startI == homeI && startJ == homeJ) return 0 var result = 0 if (startJ < homeJ) { for (i in startJ + 1..homeJ) result += colCosts[i] } else { for (i in startJ - 1 downTo homeJ) result += colCosts[i] } if (startI < homeI) { for (i in startI + 1..homeI) result += rowCosts[i] } else { for (i in startI - 1 downTo homeI) result += rowCosts[i] } return result } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
904
leetcode-kotlin
MIT License
src/Day07.kt
luiscobo
574,302,765
false
{"Kotlin": 19047}
enum class FileType { PLAIN_FILE, DIRECTORY } data class Node(val fileName: String, val fileType: FileType, var size: Int, var parent: Node? = null) { private val children: MutableList<Node> = mutableListOf() fun getChildByName(dirName: String): Node? { return children.firstOrNull { it.fileName == dirName } } fun getChild(position: Int) = children[position] operator fun get(i: Int) = children[i] val indices: IntRange get() = IntRange(0, children.size - 1) val isDir get() = this.fileType == FileType.DIRECTORY fun addChild(node: Node) { children.add(node) } val length: Int get() = children.size } // La estructura de directorios var root: Node? = null const val TOTAL_DISK_SPACE_AVAILABLE = 70_000_000 const val UNUSED_SPACE_NEEDED = 30_000_000 fun calculateTotalSize(node: Node): Int { var total = 0 for (i in node.indices) { val n = node[i] total += if (n.fileType == FileType.PLAIN_FILE) { n.size } else { calculateTotalSize(n) } } node.size = total return total } fun printNode(node: Node, spaces: String = "") { println("$spaces ${node.fileName} : ${node.size}") if (node.fileType == FileType.DIRECTORY) { for (i in node.indices) { val child = node[i] if (child.fileType == FileType.DIRECTORY) { printNode(child, "$spaces ") } } } } fun main() { fun getCommandParts(line: String): Pair<Boolean, String> { val arguments = line.split(" ") return if (arguments[1] == "ls") { false to "" } else if (arguments[1] == "cd") { true to arguments[2] } else { false to "ERROR" } } fun getFileInfo(line: String): Node { val arguments = line.split(" ") if (arguments[0] == "dir") { return Node(arguments[1], FileType.DIRECTORY, 0) } return Node(arguments[1], FileType.PLAIN_FILE, arguments[0].toInt()) } fun getTotalSizeDirectoriesAtMost100K(node: Node): Int { var total = 0 if (node.fileType == FileType.DIRECTORY) { if (node.size <= 100_000) { total += node.size } for (i in node.indices) { val child = node[i] if (child.isDir) { total += getTotalSizeDirectoriesAtMost100K(child) } } } return total } fun part1(input: List<String>): Int { var workingDir: Node? = null for (command in input) { if (command[0] == '$') { val (isCD, directory) = getCommandParts(command) if (isCD) { when (directory) { "/" -> { if (root == null) { root = Node("/", FileType.DIRECTORY, 0) } workingDir = root!! } ".." -> workingDir = workingDir!!.parent else -> workingDir = workingDir?.getChildByName(directory) } } } else { val node = getFileInfo(command) node.parent = workingDir workingDir!!.addChild(node) } } calculateTotalSize(root!!) return getTotalSizeDirectoriesAtMost100K(root!!) } fun totalSizeDirectoryToDelete(node: Node, needed: Int): Int { var menor = 0 if (node.isDir) { menor = if (node.size >= needed) node.size else Int.MAX_VALUE for (i in node.indices) { val child = node[i] if (child.isDir) { val total = totalSizeDirectoryToDelete(child, needed) if (total in needed until menor) { menor = total } } } } return menor } fun part2(input: List<String>): Int { root = null part1(input) val unused = TOTAL_DISK_SPACE_AVAILABLE - root!!.size if (unused >= UNUSED_SPACE_NEEDED) { return 0 } val needed = UNUSED_SPACE_NEEDED - unused println("Needed $needed") return totalSizeDirectoryToDelete(root!!, needed) } fun part3(lines: List<String>) { val pattern = """[$] cd (.*)|(\d+).*""".toRegex() for (line in lines) { val match = pattern.matchEntire(line) ?: continue if (match.groups[1] != null) { println("Line $line => Group 1 = ${match.groups[1]!!.value}") } if (match.groups[2] != null) { println("Line $line => Group 2 = ${match.groups[2]!!.value}") } } } val input = readInput("day07_test") println(part1(input)) println(part2(input)) part3(input) }
0
Kotlin
0
0
c764e5abca0ea40bca0b434bdf1ee2ded6458087
5,136
advent-of-code-2022
Apache License 2.0
core/model/src/main/java/online/partyrun/partyrunapplication/core/model/util/RunningRecordCalculation.kt
SWM-KAWAI-MANS
649,352,661
false
{"Kotlin": 806784}
package online.partyrun.partyrunapplication.core.model.util import online.partyrun.partyrunapplication.core.model.running_result.common.RunnerRecord import online.partyrun.partyrunapplication.core.model.running_result.common.RunnerStatus import java.time.Duration import kotlin.math.roundToInt fun formatPace(pace: Double): String { val minutesPart = (pace / 60).toInt() val secondsPart = (pace % 60).toInt() // %02d는 정수를 두 자리로 표현하는데, 만약 한 자리수면 앞에 0 추가 return "${minutesPart}'${String.format("%02d", secondsPart)}''" } fun formatDurationToTimeString(duration: Duration): String { val hours = duration.toHours() val minutes = duration.toMinutes() % 60 val seconds = duration.seconds % 60 return String.format("%02d:%02d:%02d", hours, minutes, seconds) } fun calculateAveragePace(runnerStatus: RunnerStatus): String { val seconds = runnerStatus.secondsElapsedTime.toDouble() val lastRecordDistance = runnerStatus.records.lastOrNull()?.distance ?: 0.0 val distanceInKm = lastRecordDistance / 1000.0 val pace = if (distanceInKm > 0) seconds / distanceInKm else 0.0 return formatPace(pace) } fun calculatePaceInMinPerKm(speedInMetersPerSec: Double): String { if (speedInMetersPerSec == 0.0) { return "0'00''" } val paceInMinPerKm = (1 / speedInMetersPerSec) * (1000 / 60) val minutes = paceInMinPerKm.toInt() val seconds = ((paceInMinPerKm - minutes) * 60).roundToInt() // %02d는 정수를 두 자리로 표현하는데, 만약 한 자리수면 앞에 0 추가 return "${minutes}'${String.format("%02d", seconds)}''" } fun calculateAverageAltitude(runnerStatus: RunnerStatus): Double { return if (runnerStatus.records.isNotEmpty()) { (runnerStatus.records.sumOf { it.altitude } / runnerStatus.records.size) .roundToInt().toDouble() } else { 0.0 } } fun calculateCumulativePacePerMinute(records: List<RunnerRecord>): List<Pair<String, Double>> { if (records.isEmpty()) return emptyList() val startTime = records.first().time return records.drop(1).mapNotNull { record -> val timeElapsed = Duration.between(startTime, record.time) val currentDistanceInKm = record.distance / 1000.0 if (!timeElapsed.isZero && currentDistanceInKm != 0.0) { val rawPaceInSeconds = timeElapsed.toSeconds().toDouble() / currentDistanceInKm val minutesPart = (rawPaceInSeconds / 60).toInt() val secondsPart = (rawPaceInSeconds % 60).toInt() val formattedPace = "$minutesPart.${secondsPart}" Pair(formatDurationToTimeString(timeElapsed), formattedPace.toDouble()) } else { null } } } fun calculateDistanceOverTime(records: List<RunnerRecord>): List<Pair<String, Double>> { if (records.isEmpty()) return emptyList() val startTime = records.first().time return records.map { record -> val timeElapsed = Duration.between(startTime, record.time) Pair(formatDurationToTimeString(timeElapsed), record.distance) } } fun calculateAltitudeOverTime(records: List<RunnerRecord>): List<Pair<String, Double>> { if (records.isEmpty()) return emptyList() val startTime = records.first().time return records.map { record -> val timeElapsed = Duration.between(startTime, record.time) Pair(formatDurationToTimeString(timeElapsed), record.altitude.roundToInt().toDouble()) } }
0
Kotlin
1
13
c1a613d5632726a579a35cc0f534e5607c3d6d74
3,518
party-run-application
MIT License
src/main/kotlin/g0101_0200/s0130_surrounded_regions/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0130_surrounded_regions // #Medium #Top_Interview_Questions #Array #Depth_First_Search #Breadth_First_Search #Matrix // #Union_Find #Algorithm_II_Day_8_Breadth_First_Search_Depth_First_Search // #2022_10_08_Time_355_ms_(84.42%)_Space_51.2_MB_(68.83%) class Solution { fun solve(board: Array<CharArray>) { // Edge case, empty grid if (board.size == 0) { return } // Traverse first and last rows ( boundaries) for (i in board[0].indices) { // first row if (board[0][i] == 'O') { // It will covert O and all it's touching O's to # dfs(board, 0, i) } // last row if (board[board.size - 1][i] == 'O') { // Coverts O's to #'s (same thing as above) dfs(board, board.size - 1, i) } } // Traverse first and last Column (boundaries) for (i in board.indices) { // first Column if (board[i][0] == 'O') { // Converts O's to #'s dfs(board, i, 0) } // last Column if (board[i][board[0].size - 1] == 'O') { // Coverts O's to #'s dfs(board, i, board[0].size - 1) } } // Traverse through entire matrix for (i in board.indices) { for (j in board[0].indices) { if (board[i][j] == 'O') { // Convert O's to X's board[i][j] = 'X' } if (board[i][j] == '#') { // Convert #'s to O's board[i][j] = 'O' } } } } fun dfs(board: Array<CharArray>, row: Int, column: Int) { if (row < 0 || row >= board.size || column < 0 || column >= board[0].size || board[row][column] != 'O') { return } board[row][column] = '#' dfs(board, row + 1, column) dfs(board, row - 1, column) dfs(board, row, column + 1) dfs(board, row, column - 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,152
LeetCode-in-Kotlin
MIT License
src/Day08.kt
Misano9699
572,108,457
false
null
fun main() { fun determineGrid(input: List<String>): List<List<Int>> { val grid = mutableListOf<List<Int>>() input.forEach { line -> grid.add(line.toCharArray().map { it.toString().toInt() }.toList()) } return grid } fun addToVisibleTrees(visibleTrees: MutableMap<Pair<Int, Int>, Int>, pair: Pair<Int, Int>, size: Int) { if (!visibleTrees.containsKey(pair)) { visibleTrees[pair] = size } } fun determineVisibleTrees(grid: List<List<Int>>): Map<Pair<Int, Int>, Int> { val visibleTrees =mutableMapOf<Pair<Int, Int>, Int>() (grid.indices).forEach { x -> var previousSize = -1 (grid[x].indices).forEach { y -> val size = grid[x][y] if (size > previousSize ) { previousSize = size addToVisibleTrees(visibleTrees, Pair(x, y), size) } } } (grid[0].indices).forEach { y -> var previousSize = -1 (grid.indices).forEach { x -> val size = grid[x][y] if (size > previousSize ) { previousSize = size addToVisibleTrees(visibleTrees, Pair(x, y), size) } } } (grid.indices).reversed().forEach { x -> var previousSize = -1 (grid[x].indices).reversed().forEach { y -> val size = grid[x][y] if (size > previousSize ) { previousSize = size addToVisibleTrees(visibleTrees, Pair(x, y), size) } } } (grid[0].indices).reversed().forEach { y -> var previousSize = -1 (grid.indices).reversed().forEach { x -> val size = grid[x][y] if (size > previousSize ) { previousSize = size addToVisibleTrees(visibleTrees, Pair(x, y), size) } } } return visibleTrees } fun left(x: Int, y: Int, grid: List<List<Int>>): Int { val size = grid[x][y] var i = x - 1 var count = 0 var stop = false while (i >= 0 && !stop) { count++ if (grid[i][y] >= size) stop = true i-- } return count } fun right(x: Int, y: Int, grid: List<List<Int>>): Int { val size = grid[x][y] var i = x + 1 var count = 0 var stop = false while (i < grid.size && !stop) { count++ if (grid[i][y] >= size) stop = true i++ } return count } fun up(x: Int, y: Int, grid: List<List<Int>>): Int { val size = grid[x][y] var j = y - 1 var count = 0 var stop = false while (j >= 0 && !stop) { count++ if (grid[x][j] >= size ) stop = true j-- } return count } fun down(x: Int, y: Int, grid: List<List<Int>>): Int { val size = grid[x][y] var j = y + 1 var count = 0 var stop = false while (j < grid[x].size && !stop) { count++ if (grid[x][j] >= size) stop = true j++ } return count } fun determineScenicTrees(grid: List<List<Int>>): Map<Pair<Int, Int>, Int> { val scenicTrees = mutableMapOf<Pair<Int, Int>, Int>() (grid.indices).forEach { x -> (grid[x].indices).forEach { y -> val treesLeft = left(x, y, grid) val treesRight = right(x, y, grid) val treesUp = up(x, y, grid) val treesDown = down(x, y, grid) scenicTrees[Pair(x,y)]=treesLeft * treesRight * treesUp * treesDown } } return scenicTrees } fun part1(input: List<String>): Int { val grid: List<List<Int>> = determineGrid(input) println(grid) val visibleTrees = determineVisibleTrees(grid) println(visibleTrees) return visibleTrees.count() } fun part2(input: List<String>): Int { val grid: List<List<Int>> = determineGrid(input) println(grid) val scenicTrees = determineScenicTrees(grid) println(scenicTrees) return scenicTrees.maxOf { it.value } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val input = readInput("Day08") println("---- PART 1 ----") check(part1(testInput).also { println("Answer test input part1: $it") } == 21) println("Answer part1: " + part1(input)) println("---- PART 2 ----") check(part2(testInput).also { println("Answer test input part2: $it") } == 8) println("Answer part2: " + part2(input)) }
0
Kotlin
0
0
adb8c5e5098fde01a4438eb2a437840922fb8ae6
4,921
advent-of-code-2022
Apache License 2.0
year2018/src/main/kotlin/net/olegg/aoc/year2018/day14/Day14.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day14 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 14](https://adventofcode.com/2018/day/14) */ object Day14 : DayOf2018(14) { override fun first(): Any? { val rounds = data.toInt() val recipes = mutableListOf(3, 7) (1..rounds).fold(0 to 1) { (first, second), _ -> val next = recipes[first] + recipes[second] if (next > 9) { recipes += (next / 10) } recipes += (next % 10) val (newFirst, newSecond) = (first + recipes[first] + 1) % recipes.size to (second + recipes[second] + 1) % recipes.size return@fold (newFirst to newSecond) } return recipes.subList(rounds, rounds + 10).joinToString(separator = "") } override fun second(): Any? { val tail = data val recipes = mutableListOf(3, 7) val builder = StringBuilder("37") (1..1_000_000_000).fold(0 to 1) { (first, second), _ -> val next = recipes[first] + recipes[second] if (next > 9) { recipes += (next / 10) builder.append(next / 10) if (builder.endsWith(tail)) { return builder.length - tail.length } } recipes += (next % 10) builder.append(next % 10) if (builder.endsWith(tail)) { return builder.length - tail.length } val (newFirst, newSecond) = (first + recipes[first] + 1) % recipes.size to (second + recipes[second] + 1) % recipes.size return@fold (newFirst to newSecond) } return null } } fun main() = SomeDay.mainify(Day14)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,600
adventofcode
MIT License
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/strings/special/SubstrCount.kt
slobanov
200,526,003
false
null
package ru.amai.study.hackerrank.practice.interviewPreparationKit.strings.special import java.lang.Integer.max import java.util.* fun subStrCount(string: String): Long = cntSubstringsWithSameChars(string) + cntSubstringsWithSameCharsExceptMiddle(string) private fun cntSubstringsWithSameCharsExceptMiddle(string: String): Long { fun withinBounds(index: Int, offset: Int): Boolean = ((index - offset) >= 0) && ((index + offset) < string.length) fun substringIsValid(currChar: Char, index: Int, offset: Int): Boolean = if (withinBounds(index, offset)) { val lChar = string[index - offset] val rChar = string[index + offset] (lChar == currChar) && (rChar == currChar) } else false var substringCnt = 0L var index = 1 while (index < string.length - 1) { val currChar = string[index - 1] if (string[index] == currChar) { index++ continue } val offset = generateSequence(1) { it + 1 } .takeWhile { offset -> substringIsValid(currChar, index, offset) } .count() substringCnt += offset index += max(offset, 1) } return substringCnt } private fun cntSubstringsWithSameChars(string: String): Long = string.drop(1).fold(CharCounterHolder(string.first())) { counter, char -> if (char == counter.char) counter.increment() else counter.switchChar(char) }.countValue() private data class CharCounterHolder( val char: Char, val currentCount: Long = 1L, val partialResult: Long = 0 ) { fun increment(): CharCounterHolder = copy(currentCount = currentCount + 1) fun switchChar(char: Char) = CharCounterHolder(char = char, partialResult = countValue()) fun countValue() = partialResult + (currentCount * (currentCount + 1) / 2) } fun main() { val scan = Scanner(System.`in`) scan.nextLine() val s = scan.nextLine() val result = subStrCount(s) println(result) }
0
Kotlin
0
0
2cfdf851e1a635b811af82d599681b316b5bde7c
2,032
kotlin-hackerrank
MIT License
core/src/main/kotlin/grammar/classification.kt
SalHe
471,474,974
false
{"Kotlin": 74974, "C": 281}
package com.github.salhe.compiler.grammar import com.github.salhe.compiler.filterComment import com.github.salhe.compiler.grammar.GrammarClassification.* import com.github.salhe.compiler.token.* import com.github.salhe.compiler.token.scanner.Scanner import java.io.ByteArrayInputStream enum class GrammarClassification { /** * 无限制文法 * */ PSG, /** * 上下文相关文法 * */ CSG, /** * 上下文无关文法 * */ CFG, /** * 正规文法 * */ RG } sealed class Letter(val exp: String) { override fun toString(): String { return "<${this::class.java.simpleName}, $exp>" } override fun equals(other: Any?): Boolean { return other is Letter // 得是字母 && other.javaClass == this.javaClass // 是同类(都是终结符火非终结符) && other.exp == this.exp // 是同样的表达式 } override fun hashCode(): Int { return "${this.javaClass.simpleName}:${exp}".hashCode() } class Terminal(exp: String) : Letter(exp) class NonTerminal(exp: String) : Letter(exp) } data class Producer( val left: List<Letter>, val right: List<Letter> ) data class Grammar( val nonTerminals: List<Letter.NonTerminal>, val terminals: List<Letter.Terminal>, val producers: List<Producer>, val start: Letter ) /** * 分析语法 * * TODO 本来想做成先分析成语法树的,但是暂时先不考虑了。 * * @param grammar * @return */ fun analyseGrammar(grammar: String): Grammar { val tokens = Scanner(ByteArrayInputStream(grammar.toByteArray()).reader()).scan() return analyseGrammar(tokens) } fun analyseGrammar(tokens: List<Token>): Grammar { val iterator = tokens.filterComment().iterator() if (!iterator.hasNext() || iterator.next() != Punctuation.LBracket) throw MissingBracketException("左括号", "(") val nonTerminals = listLetterSet(iterator) { Letter.NonTerminal(it) } if (!iterator.hasNext() || iterator.next() != Punctuation.Comma) throw MissingCommaException("分隔两集合") val terminals = listLetterSet(iterator) { Letter.Terminal(it) } val letters = nonTerminals + terminals fun findLetter(exp: String) = letters.find { it.exp == exp } ?: throw UndefinedLetterException(exp) if (!iterator.hasNext() || iterator.next() != Punctuation.Comma) throw MissingCommaException("分隔两集合") val producers = listProducers(iterator, ::findLetter) if (!iterator.hasNext() || iterator.next() != Punctuation.Comma) throw MissingCommaException("分隔产生式集合与起始产生式") val start = findLetter((iterator.next() as Identifier).id) return Grammar(nonTerminals, terminals, producers, start) } fun classifyGrammar(grammar: Grammar): GrammarClassification { for (p in grammar.producers) { // 如果任何一个产生式左部长度为0或只包含终结符(不含非终结符),则产生式错误 if (p.left.isEmpty() || p.left.all { it is Letter.Terminal }) { throw NoNonTerminalException(p) } } // 产生式左部长度为1,则左部只包含一个非终结符(前面已经保证至少含有一个非终结符) // 可能是上下文相关文法、正规文法 val isCsgOrRg = grammar.producers.all { it.left.size == 1 } if (isCsgOrRg) { return if (grammar.producers.all { it.right.size == 1 || (it.right.size == 2 && it.right[0] is Letter.Terminal) }) { RG // 左线性正规文法 } else if (grammar.producers.all { it.right.size == 1 || (it.right.size == 2 && it.right[1] is Letter.Terminal) }) { RG // 右线性正则文法 } else { CFG // 上下文相关文法 } } else { // 右部长度至少为1 if (grammar.producers.all { it.right.isNotEmpty() }) return CSG return PSG } } private fun Token.toLetterExp(): String { if (this is Identifier) return this.id if (this is Literal.StringLiteral) return "\"${this.string}\"" if (this is Literal.NumberLiteral<*>) return "" + this.value throw IllegalStateException("此处不应该出现其他类型的Token: $this") } /** * 解析产生式集合。 * * @param iterator [Token]迭代器。 * @param findLetter [Letter]提供者,用于根据符号名提供对应的符号。 * @return */ private fun listProducers(iterator: Iterator<Token>, findLetter: (String) -> Letter) = buildList { // 缺少左花括号 if (!iterator.hasNext() || iterator.next() != Punctuation.LCurlyBracket) throw GrammarException("字母集是一个花括号包裹、逗号分隔的集合") if (!iterator.hasNext()) throw GrammarException("字母集合描述不完整") var next = iterator.next() while (next != Punctuation.RCurlyBracket) { val left = buildList { while (next != Operator.Greater) { add(findLetter(next.toLetterExp())) next = iterator.next() } } next = iterator.next() val right = buildList { while (next != Punctuation.Comma && next != Punctuation.RCurlyBracket) { add(findLetter(next.toLetterExp())) next = iterator.next() } } add(Producer(left, right)) if (!iterator.hasNext()) throw GrammarException("不完整的集合") if (next == Punctuation.RCurlyBracket) break if (next != Punctuation.Comma) throw IllegalStateException("请用逗号','分隔字母") next = iterator.next() } } /** * 解析符号集合 * * @param R 符号类型,参见[Letter]。 * @param iterator [Token]的迭代器。 * @param builder 符号构建者,接受一个参数:符号名。 * @return */ private fun <R> listLetterSet(iterator: Iterator<Token>, builder: (exp: String) -> R) = buildList { // 缺少左花括号 if (!iterator.hasNext() || iterator.next() != Punctuation.LCurlyBracket) throw GrammarException("字母集是一个花括号包裹、逗号分隔的集合") if (!iterator.hasNext()) throw GrammarException("字母集合描述不完整") var next = iterator.next() while (next != Punctuation.RCurlyBracket) { add(builder(next.toLetterExp())) if (!iterator.hasNext()) throw GrammarException("不完整的集合") next = iterator.next() if (next == Punctuation.RCurlyBracket) break if (next != Punctuation.Comma) throw GrammarException("请用逗号','分隔字母") next = iterator.next() } }
1
Kotlin
1
0
2347899312fc18dba2543746927fa8594cf0288a
6,663
compiler
MIT License
src/leetcode/aprilChallenge2020/weekthree/LeftmostColumnWithAtLeastOne.kt
adnaan1703
268,060,522
false
null
package leetcode.aprilChallenge2020.weekthree private class BinaryMatrix(val grid: Array<IntArray>) { fun get(x: Int, y: Int): Int { return grid[x][y] } fun dimensions(): List<Int> { return listOf(grid.size, grid[0].size) } } fun main() { var grid = arrayOf( intArrayOf(0, 0), intArrayOf(1, 1) ) println(leftMostColumnWithOne(BinaryMatrix(grid))) // ans: 0 grid = arrayOf( intArrayOf(0, 0), intArrayOf(0, 0) ) println(leftMostColumnWithOne(BinaryMatrix(grid))) // ans: -1 grid = arrayOf( intArrayOf(0, 0, 0, 1), intArrayOf(0, 0, 1, 1), intArrayOf(0, 1, 1, 1) ) println(leftMostColumnWithOne(BinaryMatrix(grid))) // ans: 1 grid = arrayOf( intArrayOf(0, 0, 1, 1), intArrayOf(0, 1, 1, 1), intArrayOf(0, 0, 0, 1), intArrayOf(0, 0, 0, 0) ) println(leftMostColumnWithOne(BinaryMatrix(grid))) // ans: 1 } private fun leftMostColumnWithOne(binaryMatrix: BinaryMatrix): Int { var ans = -1 val dimens: List<Int> = binaryMatrix.dimensions() var row = 0 var col = dimens[1] - 1 while (col in 0 until dimens[1] && row in 0 until dimens[0]) { row = binaryMatrix.goDown(row, col, dimens[0] - 1) col = binaryMatrix.goLeft(row, col) ans = if (col != -1) col else ans row++ } return ans } private fun BinaryMatrix.safeGet(row: Int, col: Int): Int { if (row >= 0 && col >= 0) return this.get(row, col) return 0 } private fun BinaryMatrix.goDown(row: Int, col: Int, n: Int): Int { var ans = row while (ans <= n) { if (this.get(ans, col) == 1) return ans ans++ } return -1 } private fun BinaryMatrix.goLeft(row: Int, col: Int): Int { if (row == -1 || col == -1) return -1 var low = 0 var high = col while (low in 0..high && high >= 0) { val mid = (low + high) shr 1 val curr = this.safeGet(row, mid) val prev = this.safeGet(row, mid - 1) if (curr == 1 && prev == 0) return mid if (curr == 1) high = mid - 1 else low = mid + 1 } return -1 }
0
Kotlin
0
0
e81915db469551342e78e4b3f431859157471229
2,260
KotlinCodes
The Unlicense
src/utils/Math.kt
jrmacgill
573,065,109
false
{"Kotlin": 76362}
@file:Suppress("unused") package utils import kotlin.math.absoluteValue import kotlin.math.pow /** * Euclid's algorithm for finding the greatest common divisor of a and b. */ fun gcd(a: Int, b: Int): Int = if (b == 0) a.absoluteValue else gcd(b, a % b) fun gcd(f: Int, vararg n: Int): Int = n.fold(f, ::gcd) fun Iterable<Int>.gcd(): Int = reduce(::gcd) /** * Euclid's algorithm for finding the greatest common divisor of a and b. */ fun gcd(a: Long, b: Long): Long = if (b == 0L) a.absoluteValue else gcd(b, a % b) fun gcd(f: Long, vararg n: Long): Long = n.fold(f, ::gcd) fun Iterable<Long>.gcd(): Long = reduce(::gcd) /** * Find the least common multiple of a and b using the gcd of a and b. */ fun lcm(a: Int, b: Int) = (a safeTimes b) / gcd(a, b) fun lcm(f: Int, vararg n: Int): Long = n.map { it.toLong() }.fold(f.toLong(), ::lcm) @JvmName("lcmForInt") fun Iterable<Int>.lcm(): Long = map { it.toLong() }.reduce(::lcm) /** * Find the least common multiple of a and b using the gcd of a and b. */ fun lcm(a: Long, b: Long) = (a safeTimes b) / gcd(a, b) fun lcm(f: Long, vararg n: Long): Long = n.fold(f, ::lcm) fun Iterable<Long>.lcm(): Long = reduce(::lcm) /** * Simple algorithm to find the primes of the given Int. */ fun Int.primes(): Sequence<Int> = sequence { var n = this@primes var j = 2 while (j * j <= n) { while (n % j == 0) { yield(j) n /= j } j++ } if (n > 1) yield(n) } /** * Simple algorithm to find the primes of the given Long. */ fun Long.primes(): Sequence<Long> = sequence { var n = this@primes var j = 2L while (j * j <= n) { while (n % j == 0L) { yield(j) n /= j } j++ } if (n > 1) yield(n) } infix fun Number.pow(power: Number): Double = this.toDouble().pow(power.toDouble()) infix fun Int.pow(power: Int): Int = this.toDouble().pow(power.toDouble()).toInt()
0
Kotlin
0
1
3dcd590f971b6e9c064b444139d6442df034355b
1,967
aoc-2022-kotlin
Apache License 2.0
shared/impl/src/main/kotlin/dev/eduayuso/cgkotlin/shared/impl/algorithms/AlgorithmUtil.kt
eduayuso
353,986,267
false
{"Kotlin": 84337}
package dev.eduayuso.cgkotlin.shared.impl.algorithms import dev.eduayuso.cgkotlin.shared.domain.entities.PointEntity import dev.eduayuso.cgkotlin.shared.domain.entities.PointSetEntity import dev.eduayuso.cgkotlin.shared.domain.entities.SegmentEntity object AlgorithmUtil { /** * Checks if point s is at left of vector p->q */ fun toLeft(p: PointEntity, q: PointEntity, s: PointEntity) = (p.x * q.y - p.y * q.x + q.x * s.y - q.y * s.x + s.x * p.y - s.y * p.x) > 0 fun toLeft(points: PointSetEntity, p: Int, q: Int, s: Int) = toLeft(points.list[p], points.list[q], points.list[s]) /** * Returns the lower and left most point index of the set */ fun lowerThenLeftMost(points: PointSetEntity): Int { val n = points.list.size var ltl = 0 for (s in 0 until n) { val ltlp = points.list[ltl] val sp = points.list[s] if (sp.y < ltlp.y || sp.y == ltlp.y && sp.x <= ltlp.x) { ltl = s } } return ltl } /** * Returns 1 if polar angle between p0 and a is greater than between p0 and b, else -1 */ fun polarAngleComparator(p0: PointEntity, a: PointEntity, b: PointEntity): Int { /* val deltaY = kotlin.math.abs(a.y - b.y) val deltaX = kotlin.math.abs(a.x - b.x) return Math.toDegrees(kotlin.math.atan2(deltaY.toDouble(), deltaX.toDouble()))*/ val cotanA = -(a.x - p0.x) / (a.y - p0.y) val cotanB = -(b.x - p0.x) / (b.y - p0.y) return if (cotanA - cotanB < 0) 1 else -1 } /** * ------------------------------------------------------------------------------------ * First we find the lines intersection according to the formula: * LineP => y1 = m1*x1 + c1 * LineQ => y2 = m2*x2 + c2 * The point x,y where intersects is the one who assert this: * y1 = y2 and x1 = x2 * ------------------------------------------------------------------------------------ * Second, we check if the intersection point is inside the two segments */ fun findIntersection(p: SegmentEntity, q: SegmentEntity): PointEntity? { /** * First we find the lines intersection */ val lineP = p.toLine() val lineQ = q.toLine() val x = (lineQ.yIntercept - lineP.yIntercept) / (lineP.slope - lineQ.slope) val y = lineP.slope * x + lineP.yIntercept /** * Second, we check if the intersection point is inside the two segments */ val i = PointEntity(x, y) if (p.isPointInsideBox(i) && q.isPointInsideBox(i)) { return i } else { return null } } }
0
Kotlin
0
0
4e1b5272088b77353a87073255dddbb6487318f7
2,764
compose-computational-geometry
Apache License 2.0
kotlin/dp/ShortestHamiltonianCycle.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package dp import java.util.Arrays object ShortestHamiltonianCycle { fun getShortestHamiltonianCycle(dist: Array<IntArray>): Int { val n = dist.size val dp = Array(1 shl n) { IntArray(n) } for (d in dp) Arrays.fill(d, Integer.MAX_VALUE / 2) dp[1][0] = 0 var mask = 1 while (mask < 1 shl n) { for (i in 1 until n) { if (mask and 1 shl i != 0) { for (j in 0 until n) { if (mask and 1 shl j != 0) { dp[mask][i] = Math.min(dp[mask][i], dp[mask xor (1 shl i)][j] + dist[j][i]) } } } } mask += 2 } var res: Int = Integer.MAX_VALUE for (i in 1 until n) { res = Math.min(res, dp[(1 shl n) - 1][i] + dist[i][0]) } // reconstruct path var cur = (1 shl n) - 1 val order = IntArray(n) var last = 0 for (i in n - 1 downTo 1) { var bj = -1 for (j in 1 until n) { if (cur and 1 shl j != 0 && (bj == -1 || dp[cur][bj] + dist[bj][last] > dp[cur][j] + dist[j][last])) { bj = j } } order[i] = bj cur = cur xor (1 shl bj) last = bj } System.out.println(Arrays.toString(order)) return res } // Usage example fun main(args: Array<String?>?) { val dist = arrayOf( intArrayOf(0, 1, 10, 1, 10), intArrayOf(1, 0, 10, 10, 1), intArrayOf(10, 10, 0, 1, 1), intArrayOf(1, 10, 1, 0, 10), intArrayOf(10, 1, 1, 10, 0) ) System.out.println(5 == getShortestHamiltonianCycle(dist)) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,822
codelibrary
The Unlicense
src/main/kotlin/org/maspitzner/presencesimulation/evaluation/NeedlemanWunschAlgorithm.kt
MASpitzner
374,770,623
false
null
package org.maspitzner.presencesimulation.evaluation import java.lang.Double.min /** * Class abstraction to implement the needleman wunsch algorithm. * This is used to calculate a global alignment between two label sequences * (at least in this context). * */ class NeedlemanWunschAlgorithm { //Since this is a dynamic programming algorithm it calculates the final result // via this table private lateinit var scoringMatrix: Array<Array<Double>> /**The [WeightMatrix] object which is used to calculate the score between two labels */ private val weightMatrix = WeightMatrix() /** * Computes the scoring Matrix or DP-Table between two label lists. * The alignment score between the to label sequences can be found in the [scoringMatrix] at * position scoringMatrix[scoringMatrix.size - 1][scoringMatrix[0].size - 1] * This executes the needleman wunsch algorithm * @param firstSequence the first label sequence * @param secondSequence the other label sequence */ private fun computeScoringMatrix(firstSequence: List<String>, secondSequence: List<String>) { scoringMatrix = Array((firstSequence.size + 1)) { Array(secondSequence.size + 1) { 0.0 } } for (i in scoringMatrix.indices) { for (j in 0 until scoringMatrix[i].size) { if (i == 0 || j == 0) { scoringMatrix[i][j] = i.or(j) * weightMatrix.gapCost continue } val cost = weightMatrix.getCost(firstSequence[i - 1], secondSequence[j - 1]) val diagonalPredecessorCost = cost + scoringMatrix[i - 1][j - 1] val leftPredecessorCost = scoringMatrix[i][j - 1] + weightMatrix.gapCost val topPredecessorCost = scoringMatrix[i - 1][j] + weightMatrix.gapCost scoringMatrix[i][j] = min( diagonalPredecessorCost, min( topPredecessorCost, leftPredecessorCost ) ) } } } /** * Calculates and returns the alignment quality between two label sequences. * @param firstSequence the first label sequence * @param secondSequence the other label sequence * @return the alignment quality as Double */ fun align(firstSequence: List<String>, secondSequence: List<String>): Double { computeScoringMatrix(firstSequence, secondSequence) return scoringMatrix[scoringMatrix.size - 1][scoringMatrix[0].size - 1] } }
0
Kotlin
0
0
9d2cf33f987e7e509c62a299ae747df15031e116
2,644
PresenceSimulation
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/linked_list/FlattenAMultilevelDoublyLinkedList.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.linked_list /** * You are given a doubly linked list, * which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. * This child pointer may or may not point to a separate doubly linked list, * also containing these special nodes. * These child lists may have one or more children of their own, and so on, * to produce a multilevel data structure as shown in the example below. * * Given the head of the first level of the list, * flatten the list so that all the nodes appear in a single-level, doubly linked list. * Let curr be a node with a child list. * The nodes in the child list should appear after curr and before curr.next in the flattened list. * * Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. * * Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] * Output: [1,2,3,7,8,11,12,9,10,4,5,6] * Explanation: The multilevel linked list in the input is shown. */ // O(n) time | O(n) space fun flatten(head: DListNode?): DListNode? { if (head == null) return null val sentinel = DListNode(-1) sentinel.next = head var prev: DListNode? = sentinel val lifo = ArrayDeque(listOf(head)) while (lifo.isNotEmpty()) { val curr = lifo.removeFirst() prev?.next = curr curr.prev = prev if (curr.next != null) lifo.addFirst(curr.next!!) if (curr.child != null) { lifo.addFirst(curr.child!!) curr.child = null } prev = curr } sentinel.next?.prev = null // bullshit return sentinel.next } // O(n) time | O(n) space fun flattenRecursive(head: DListNode?): DListNode? { if (head == null) return null val sentinel = DListNode(-1) sentinel.next = head flattenDFS(sentinel, head) sentinel.next?.prev = null return sentinel.next } private fun flattenDFS(prev: DListNode?, curr: DListNode?): DListNode? { if (curr == null) return prev curr.prev = prev prev?.next = curr val next = curr.next val tail = flattenDFS(curr, curr.child) curr.child = null return flattenDFS(tail, next) }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
2,238
algs4-leprosorium
MIT License
2023/src/main/kotlin/de/skyrising/aoc2023/day16/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day16 import de.skyrising.aoc.* import java.util.* @JvmInline value class State(val intValue: Int) { constructor(x: Int, y: Int, dir: Direction): this(((x and 0x7fff) shl 15) or (y and 0x7fff) or (dir.ordinal shl 30)) val x inline get() = intValue shl 2 shr 17 val y inline get() = intValue shl 17 shr 17 val dir inline get() = Direction(intValue ushr 30) inline operator fun component1() = x inline operator fun component2() = y inline operator fun component3() = dir } fun CharGrid.traverseBeam(state: State, beam: BitSet, positions: BitSet, deque: IntArrayDeque) { deque.enqueue(state.intValue) while (!deque.isEmpty) { var (x, y, dir) = State(deque.dequeueLastInt()) while (true) { if (x >= 0 && y >= 0 && x < width && y < height) { val beamIndex = localIndex(x, y) shl 2 or dir.ordinal val seen = beam.get(beamIndex) beam.set(beamIndex) if (seen) break } x += dir.x y += dir.y if (!contains(x, y)) break positions.set(localIndex(x, y)) dir = when (this[x, y]) { '.' -> dir '/' -> Direction(dir.ordinal xor 1) '\\' -> Direction(dir.ordinal.inv() and 3) '-' -> if (dir == Direction.N || dir == Direction.S) { deque.enqueue(State(x, y, Direction.W).intValue) Direction.E } else { dir } '|' -> if (dir == Direction.E || dir == Direction.W) { deque.enqueue(State(x, y, Direction.N).intValue) Direction.S } else { dir } else -> error("Invalid character: ${this[x, y]}") } } } } inline fun CharGrid.maxBeam(posX: Int, posY: Int, dir: Direction, beam: BitSet, positions: BitSet, deque: IntArrayDeque): Int { beam.clear() positions.clear() deque.clear() traverseBeam(State(posX, posY, dir), beam, positions, deque) return positions.cardinality() } val test = TestInput(""" .|...\.... |.-.\..... .....|-... ........|. .......... .........\ ..../.\\.. .-.-/..|.. .|....-|.\ ..//.|.... """) @PuzzleName("The Floor Will Be Lava") fun PuzzleInput.part1(): Any { val grid = charGrid return grid.maxBeam( -1, 0, Direction.E, BitSet(grid.width * grid.height * 4), BitSet(grid.width * grid.height), IntArrayDeque(128) ) } fun PuzzleInput.part2(): Any { val grid = charGrid var max = 0 val beam = BitSet(grid.width * grid.height * 4) val positions = BitSet(grid.width * grid.height) val deque = IntArrayDeque(128) for (x in 0 until grid.width) { max = maxOf(max, grid.maxBeam(x, -1, Direction.S, beam, positions, deque)) max = maxOf(max, grid.maxBeam(x, grid.height, Direction.N, beam, positions, deque)) } for (y in 0 until grid.height) { max = maxOf(max, grid.maxBeam(-1, y, Direction.E, beam, positions, deque)) max = maxOf(max, grid.maxBeam(grid.width, y, Direction.W, beam, positions, deque)) } return max }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
3,332
aoc
MIT License
src/chapter5/section1/MSD.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section1 import chapter2.swap /** * 高位优先的字符串排序 */ object MSD { private const val R = 256 private const val M = 10 fun sort(array: Array<String>) { val aux = Array(array.size) { "" } sort(array, aux, 0, array.size - 1, 0) } private fun sort(array: Array<String>, aux: Array<String>, low: Int, high: Int, d: Int) { if (high - low < M) { // 切换插入排序 insertionSort(array, low, high, d) } else { // 因为字符索引从0开始,所以R需要加2而不是1(LSD针对特定字符串排序,索引不会为0) val count = IntArray(R + 2) for (i in low..high) { count[charAt(array[i], d) + 2]++ } for (i in 1..R + 1) { count[i] += count[i - 1] } for (i in low..high) { val index = charAt(array[i], d) + 1 aux[count[index]] = array[i] count[index]++ } for (i in low..high) { // 注意这里aux的索引要减去low的值 array[i] = aux[i - low] } // 递归对R个子区间排序 for (i in 0 until R) { // count[0]表示已经到达结尾的字符串数量,不需要继续排序,所以从low+count[i]开始排序 sort(array, aux, low + count[i], low + count[i + 1] - 1, d + 1) } } } private fun charAt(string: String, d: Int): Int { return if (d < string.length) string[d].toInt() else -1 } private fun insertionSort(array: Array<String>, low: Int, high: Int, d: Int) { for (i in low + 1..high) { for (j in i downTo low + 1) { if (less(array, j, j - 1, d)) { array.swap(j, j - 1) } else break } } } /** * 比较字符串指定位置之后字符的大小,Java中substring()方法时间复杂度为常数 */ private fun less(array: Array<String>, i: Int, j: Int, d: Int): Boolean { if (i == j) return false return array[i].substring(d) < array[j].substring(d) } } fun getMSDData() = arrayOf( "she", "sells", "seashells", "by", "the", "seashore", "the", "shells", "she", "sells", "are", "surely", "seashells" ) fun main() { val array = getMSDData() MSD.sort(array) println(array.joinToString(separator = "\n")) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,627
Algorithms-4th-Edition-in-Kotlin
MIT License
src/Day14.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
fun main() { fun List<String>.toRocks(): Set<Coordinates> { val rocksCoordinates = this.map { it.split(" -> ").map { coordinates -> coordinates.split(",").let { point -> Coordinates(x = point.first().toInt(), y = point.last().toInt()) } } } val allRocksCoordinates = mutableSetOf<Coordinates>() rocksCoordinates.forEach { rocksLineCoordinates -> rocksLineCoordinates .windowed(2) .forEach { val startRock = it.first() val endRock = it.last() allRocksCoordinates += when { startRock.x == endRock.x -> IntRange(minOf(startRock.y, endRock.y), maxOf(startRock.y, endRock.y)) .map { y -> Coordinates(startRock.x, y) } startRock.y == endRock.y -> IntRange(minOf(startRock.x, endRock.x), maxOf(startRock.x, endRock.x)) .map { x -> Coordinates(x, startRock.y) } else -> throw IllegalStateException("Cannot draw line if x or y don't match!") } } } return allRocksCoordinates } fun part1(input: List<String>): Int { val startSandCoordinates = Coordinates(x = 500, y = 0) var currentSandCoordinates = startSandCoordinates var restingSandCount = 0 val rocks = input.toRocks() val sands = mutableSetOf<Coordinates>() val depth = rocks.maxOf { it.y } while (true) { val straightDownSandCoordinates = currentSandCoordinates.copy(y = currentSandCoordinates.y + 1) val leftDownSandCoordinates = currentSandCoordinates.copy(x = currentSandCoordinates.x - 1, y = currentSandCoordinates.y + 1) val rightDownSandCoordinates = currentSandCoordinates.copy(x = currentSandCoordinates.x + 1, y = currentSandCoordinates.y + 1) val filledCoordinates = rocks + sands currentSandCoordinates = when { straightDownSandCoordinates !in filledCoordinates -> straightDownSandCoordinates leftDownSandCoordinates !in filledCoordinates -> leftDownSandCoordinates rightDownSandCoordinates !in filledCoordinates -> rightDownSandCoordinates else -> { restingSandCount++ sands += currentSandCoordinates startSandCoordinates } } if (currentSandCoordinates.y >= depth) break } return restingSandCount } fun part2(input: List<String>): Int { val startSandCoordinates = Coordinates(x = 500, y = 0) var currentSandCoordinates = startSandCoordinates var restingSandCount = 0 val rocks = input.toRocks() val sands = mutableSetOf<Coordinates>() val depth = rocks.maxOf { it.y } + 2 while (true) { val straightDownSandCoordinates = currentSandCoordinates.copy(y = currentSandCoordinates.y + 1) val leftDownSandCoordinates = currentSandCoordinates.copy(x = currentSandCoordinates.x - 1, y = currentSandCoordinates.y + 1) val rightDownSandCoordinates = currentSandCoordinates.copy(x = currentSandCoordinates.x + 1, y = currentSandCoordinates.y + 1) val filledCoordinates = rocks + sands val hasReachedBottom = straightDownSandCoordinates.y == depth currentSandCoordinates = when { !hasReachedBottom && straightDownSandCoordinates !in filledCoordinates -> straightDownSandCoordinates !hasReachedBottom && leftDownSandCoordinates !in filledCoordinates -> leftDownSandCoordinates !hasReachedBottom && rightDownSandCoordinates !in filledCoordinates -> rightDownSandCoordinates else -> { restingSandCount++ sands += currentSandCoordinates if (currentSandCoordinates == startSandCoordinates) break startSandCoordinates } } } return restingSandCount } check(part1(readInput("Day14_test")) == 24) check(part2(readInput("Day14_test")) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
4,484
AdventOfCode2022
Apache License 2.0
src/day03/Day03.kt
robin-schoch
572,718,550
false
{"Kotlin": 26220}
package day03 import AdventOfCodeSolution fun main() { Day03.run() } fun splittIntoCompartments(content: String) = with(content.length / 2) { content.take(this).toSet() to content.takeLast(this).toSet() } fun Char.calculatePriority() = when { isLowerCase() -> this - 'a' + 1 isUpperCase() -> this - 'A' + 27 else -> throw IllegalStateException("item must be letter") } fun findBadges(rucksack: List<String>) = rucksack .map { it.toSet() } .reduce { items, sack -> items intersect sack } object Day03 : AdventOfCodeSolution<Int, Int> { override val testSolution1 = 157 override val testSolution2 = 70 override fun part1(input: List<String>) = input .map { splittIntoCompartments(it) } .flatMap { (sack1, sack2) -> sack1 intersect sack2 } .sumOf { it.calculatePriority() } override fun part2(input: List<String>) = input .windowed(3, 3) .flatMap { findBadges(it) } .sumOf { it.calculatePriority() } }
0
Kotlin
0
0
fa993787cbeee21ab103d2ce7a02033561e3fac3
999
aoc-2022
Apache License 2.0
src/main/aoc2019/Day20.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2019 import org.magicwerk.brownies.collections.GapList class Day20(input: List<String>) { data class Bounds(val u: Int, val iu: Int, val id: Int, val d: Int, val l: Int, val il: Int, val ir: Int, val r: Int) val parsedInput = parseInput(input) private val bounds = findBounds(parsedInput) private fun Map<Pos, Char>.maxY() = keys.maxByOrNull { it.y }!!.y private fun Map<Pos, Char>.maxX() = keys.maxByOrNull { it.x }!!.x private fun parseInput(input: List<String>): Map<Pos, Char> { val ret = mutableMapOf<Pos, Char>() for (y in input.indices) { for (x in input[y].indices) { ret[Pos(x, y)] = input[y][x] } } return ret } private fun findBounds(map: Map<Pos, Char>): Bounds { val bounds = mutableListOf(2) val fixedX = map.maxY() / 2 for (y in 2..map.maxY()) { if (bounds.size == 1 && !listOf('.', '#').contains(map[Pos(fixedX, y)])) { bounds.add(y - 1) } if (bounds.size == 2 && listOf('.', '#').contains(map[Pos(fixedX, y)])) { bounds.add(y) } if (bounds.size == 3 && !listOf('.', '#').contains(map[Pos(fixedX, y)])) { bounds.add(y - 1) break } } bounds.add(2) val fixedY = map.maxX() / 2 for (x in 2..map.maxX()) { if (bounds.size == 5 && !listOf('.', '#').contains(map[Pos(x, fixedY)])) { bounds.add(x - 1) } if (bounds.size == 6 && listOf('.', '#').contains(map[Pos(x, fixedY)])) { bounds.add(x) } if (bounds.size == 7 && !listOf('.', '#').contains(map[Pos(x, fixedY)])) { bounds.add(x - 1) break } } return Bounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5], bounds[6], bounds[7]) } private fun findPortals(map: Map<Pos, Char>): Pair<MutableMap<Pos, Pos>, MutableMap<String, MutableSet<Pos>>> { val portals = map.filter { listOf('.').contains(it.value) }.keys .filter { it.y in listOf(bounds.u, bounds.d) || // Outer top or bottom it.x in listOf(bounds.l, bounds.r) || // Outer left or right (it.y in listOf(bounds.iu, bounds.id) && it.x in bounds.il..bounds.ir) || // inner top/bottom (it.x in listOf(bounds.il, bounds.ir) && it.y in bounds.iu..bounds.id) // inner left/right } val labels = mutableMapOf<String, MutableSet<Pos>>() portals.forEach { val label = labelForPortal(map, it) if (!labels.containsKey(label)) { labels[label] = mutableSetOf() } labels[label]!!.add(it) } val portalMap = mutableMapOf<Pos, Pos>() labels.values.forEach { coordinates -> if (coordinates.size > 1) { // Ignore entry and exit portalMap[coordinates.first()] = coordinates.last() portalMap[coordinates.last()] = coordinates.first() } } return Pair(portalMap, labels) } private fun labelForPortal(map: Map<Pos, Char>, portal: Pos): String = when { portal.y in listOf(bounds.u, bounds.id) -> "${map[Pos(portal.x, portal.y - 2)]}${map[Pos(portal.x, portal.y - 1)]}" portal.y in listOf(bounds.iu, bounds.d) -> "${map[Pos(portal.x, portal.y + 1)]}${map[Pos(portal.x, portal.y + 2)]}" portal.x in listOf(bounds.l, bounds.ir) -> "${map[Pos(portal.x - 2, portal.y)]}${map[Pos(portal.x - 1, portal.y)]}" portal.x in listOf(bounds.il, bounds.r) -> "${map[Pos(portal.x + 1, portal.y)]}${map[Pos(portal.x + 2, portal.y)]}" else -> throw IllegalStateException("Not a portal: $portal") } private fun shortestPath(withFloors: Boolean): Int { val (portals, labels) = findPortals(parsedInput) val start = labels["AA"]!!.first() val end = labels["ZZ"]!!.first() return find(parsedInput, start, end, portals, withFloors).size } fun solvePart1(): Int { return shortestPath(false) } fun solvePart2(): Int { return shortestPath(true) } private fun portalDirection(portal: Pos) = when { portal.x in listOf(bounds.l, bounds.r) || portal.y in listOf(bounds.u, bounds.d) -> -1 else -> 1 } data class Pos(val x: Int, val y: Int, val z: Int = 0) { override fun toString() = "($x, $y, $z)" fun flatten() = Pos(x, y, 0) } // Order of directions specifies which is preferred when several paths is shortest private enum class Dir(val dx: Int, val dy: Int) { UP(0, -1), LEFT(-1, 0), RIGHT(1, 0), DOWN(0, 1); fun from(pos: Pos) = Pos(pos.x + dx, pos.y + dy, pos.z) } private fun availableNeighbours(map: Map<Pos, Char>, pos: Pos, portals: Map<Pos, Pos>, withFloors: Boolean): List<Pos> { return Dir.entries.map { dir -> dir.from(pos) } .filter { newPos -> map.containsKey(newPos.flatten()) && map[newPos.flatten()] == '.' } .toMutableList() .apply { portals[pos.flatten()]?.let { val newFloor = if (withFloors) pos.z + portalDirection(pos) else 0 if (newFloor >= 0 && newFloor < portals.size / 2) { // heuristic for speed improvement, don't go trough portals too many times // on average max once per portal should be enough add(Pos(it.x, it.y, newFloor)) } } } } fun find(map: Map<Pos, Char>, from: Pos, to: Pos, portals: Map<Pos, Pos>, withFloors: Boolean = false): List<Pos> { val toCheck = GapList<List<Pos>>() availableNeighbours(map, from, portals, withFloors).forEach { toCheck.add(listOf(it)) } val alreadyChecked = mutableSetOf<Pos>() while (toCheck.isNotEmpty()) { val pathSoFar = toCheck.remove() if (pathSoFar.last() == to) { return pathSoFar } availableNeighbours(map, pathSoFar.last(), portals, withFloors) .forEach { if (it !in alreadyChecked) { alreadyChecked.add(it) toCheck.add(pathSoFar + it) } } } return emptyList() } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
6,777
aoc
MIT License
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day11/Day11.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2023.calendar.day11 import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile import java.util.* import javax.inject.Inject import kotlin.math.abs class Day11 @Inject constructor( private val generatorFactory: InputGeneratorFactory ) { // find shortest paths fun findShortestPaths(fileName: String, expansionFactor: Long): Long { val lines = readStringFile(fileName) val (universe, galaxies) = expandUniverse(lines, expansionFactor) val shortestPaths: MutableMap<Path, Int> = mutableMapOf() (1..galaxies.size).forEach { first -> ((first + 1)..galaxies.size).forEach { second -> shortestPaths[Path(galaxies[first]!!, galaxies[second]!!)] = Int.MAX_VALUE } } (1..galaxies.size).forEach { findShortestPathsFromGalaxy(it, galaxies.size - it, universe, galaxies, shortestPaths) } return shortestPaths.map { it.value + abs(it.key.galaxy2.emptyRowsAbove-it.key.galaxy1.emptyRowsAbove) + abs(it.key.galaxy2.emptyColumnsLeft-it.key.galaxy1.emptyColumnsLeft) }.sum() } fun findShortestPathsFromGalaxy( start: Int, numberOfPaths: Int, universe: List<List<Int>>, galaxies: Map<Int, Galaxy>, shortestPaths: MutableMap<Path, Int> ) { var startState = State(Cell(-1, -1), Int.MAX_VALUE) val pathsDetermined: MutableSet<Int> = mutableSetOf() val universeHeight = universe.size val universeWidth = universe[0].size val stateUniverse: MutableList<MutableList<State>> = mutableListOf() universe.forEachIndexed { row, line -> run { val stateLine: MutableList<State> = mutableListOf() line.forEachIndexed { column, cell -> if (cell == start) { startState = State(Cell(row, column), 0) stateLine.add(startState) } else { stateLine.add(State(Cell(row, column), Int.MAX_VALUE)) } } stateUniverse.add(stateLine) } } while (pathsDetermined.size < numberOfPaths) { val todo: Deque<State> = ArrayDeque() todo.add(startState) fun checkCell(cell: Cell, distance: Int) { val cellToCheck = stateUniverse[cell.row][cell.column] cellToCheck.seen = true if (universe[cell.row][cell.column] != 0) { pathsDetermined.add(universe[cell.row][cell.column]) } if (cellToCheck.distance > distance) { cellToCheck.distance = distance todo.add(cellToCheck) } } fun checkNeighbours(current: State) { with(current.cell) { if (row > 0) { checkCell(Cell(row - 1, column), current.distance + 1) } if (row < universeHeight - 1) { checkCell(Cell(row + 1, column), current.distance + 1) } if (column > 0) { checkCell(Cell(row, column - 1), current.distance + 1) } if (column < universeWidth - 1) { checkCell(Cell(row, column + 1), current.distance + 1) } } } while (!todo.isEmpty()) { val current = todo.removeFirst() checkNeighbours(current) } stateUniverse.forEachIndexed { row, line -> run { line.forEachIndexed { column, cell -> if (universe[row][column] != 0 && universe[row][column] > start) { shortestPaths[Path(galaxies[start]!!, galaxies[universe[row][column]]!!)] = cell.distance } } } } } } fun expandUniverse(lines: List<String>, expansionFactor: Long): Pair<List<List<Int>>, Map<Int, Galaxy>> { var galaxyCounter = 1 val universe: MutableList<MutableList<Int>> = mutableListOf() val emptyRows: MutableList<Int> = mutableListOf() lines.forEachIndexed { index, it -> val galaxyLine = it.map { if (it == '.') 0 else galaxyCounter++ } universe.add(galaxyLine.toMutableList()) // expand empty rows if (!it.contains('#')) { emptyRows.add(index) } } // expand empty columns val emptyColumns: MutableList<Int> = mutableListOf() for (i in 0 until universe[0].size) { val column = universe.map { it[i] } if (column.all { it == 0 }) { emptyColumns.add(i) } } val galaxies: MutableMap<Int, Galaxy> = mutableMapOf() universe.forEachIndexed { row, line -> line.forEachIndexed { column, cell -> if(cell!=0) galaxies[cell] = Galaxy(cell, row,column) } } for (galaxy in galaxies.values) { galaxy.emptyColumnsLeft = (expansionFactor-1) * (emptyColumns.count { it < galaxy.column }) galaxy.emptyRowsAbove = (expansionFactor-1) * (emptyRows.count { it < galaxy.row }) } return Pair(universe, galaxies) } data class Galaxy(val number: Int, val row: Int, val column: Int, var emptyColumnsLeft: Long = 0L, var emptyRowsAbove: Long= 0L) data class Path(val galaxy1: Galaxy, val galaxy2: Galaxy) data class Cell(val row: Int, val column: Int) data class State(val cell: Cell, var distance: Int, var seen: Boolean = false) }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
5,252
advent-of-code
MIT License
implementation/src/main/kotlin/io/github/tomplum/aoc/engine/Engine.kt
TomPlum
724,225,748
false
{"Kotlin": 141244}
package io.github.tomplum.aoc.engine import io.github.tomplum.libs.extensions.product import io.github.tomplum.libs.math.map.AdventMap2D import io.github.tomplum.libs.math.point.Point2D import kotlin.math.abs class Engine(private val schematic: List<String>) : AdventMap2D<EnginePart>() { private var groups: List<List<Pair<Point2D, EnginePart>>> init { var x = 0 var y = 0 schematic.forEach { row -> row.forEach { column -> val tile = EnginePart(column) val position = Point2D(x, y) addTile(position, tile) x++ } x = 0 y++ } groups = findPartNumberGroups() } /** * Determines the part number of the engine from * the values in the [schematic]. * * A part number is a numerical value in an [EnginePart] * that is adjacent to a symbol. * * @return The sum of the part numbers. */ fun determinePartNumbers(): Int = groups .asSequence() .filter { val adjacent = it.map { (pos, _) -> pos }.flatMap { pos -> pos.adjacent() } adjacent.any { position -> getTile(position, EnginePart('.')).isSymbol() } } .map { entries -> entries.map { (_, part) -> part.value.toString() } } .map { numbers -> numbers.joinToString("") } .map { numberString -> numberString.toInt() } .toList() .sum() /** * Determines the ratio of every gear in the engine. * A gear is denoted by a '*' symbol in the [schematic] * that is adjacent to exactly two part numbers. * * @return The sum of the gear ratios. */ fun determineGearRatio(): Long { val numbers = groups.map { group -> group.map { (_, part) -> part.value.toString().toInt() } .joinToString("") .toLong() .let { partNumber -> Pair(group.map { (pos) -> pos }, partNumber) } } return filterTiles { part -> part.isGearCandidate() } .keys .mapNotNull { gearCandidatePos -> val adjacentPartNumbers = mutableMapOf<List<Point2D>, Long>() numbers.filterNot { (pos) -> // If the number is more than 1 row away, it can't be adjacent pos.any { (_, y) -> abs(gearCandidatePos.y - y) > 1 } } .forEach { (points, number) -> gearCandidatePos.adjacent().forEach { adjPoint -> if (!adjacentPartNumbers.containsKey(points) && adjPoint in points) { adjacentPartNumbers[points] = number } }} if (adjacentPartNumbers.size == 2) { adjacentPartNumbers.values.toList().product() } else null } .sum() } private fun findPartNumberGroups(): List<List<Pair<Point2D, EnginePart>>> { var index = 0 val groups = mutableListOf<List<Pair<Point2D, EnginePart>>>() var currentGroup = mutableListOf<Pair<Point2D, EnginePart>>() getDataMap().entries.forEach { (pos, part) -> if (part.isIntegerValue()) { currentGroup.add(Pair(pos, part)) } else { groups.add(currentGroup) currentGroup = mutableListOf() index++ } } return groups.filter { group -> group.isNotEmpty() } } }
0
Kotlin
0
1
d1f941a3c5bacd126177ace6b9f576c9af07fed6
3,542
advent-of-code-2023
Apache License 2.0
src/main/kotlin/com/leetcode/random_problems/easy/best_buy_sell_stock/Main.kt
frikit
254,842,734
false
null
package com.leetcode.random_problems.easy.best_buy_sell_stock fun main() { println("Test case 1:") println(Solution().maxProfit(intArrayOf(7, 1, 5, 3, 6, 4))) // 5 println() println("Test case 2:") println(Solution().maxProfit(intArrayOf(7, 6, 4, 3, 1))) // 0 println() println("Test case 3:") println(Solution().maxProfit(intArrayOf(2, 4, 1))) // 2 println() println("Test case 4:") println(Solution().maxProfit(intArrayOf(1, 2, 3, 4, 5))) // 4 println() } class Solution { fun maxProfit(prices: IntArray): Int { if (prices.isEmpty()) return 0 var min = prices.first() var max = Short.MIN_VALUE.toInt() var maxProfit = 0 prices.forEach { if (it < min) { min = Math.min(min, it) max = Short.MIN_VALUE.toInt() } else { max = Math.max(max, it) } maxProfit = Math.max(maxProfit, max - min) } return maxProfit } }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,027
leet-code-problems
Apache License 2.0
src/kickstart2022/g/CuteLittleButterfly.kt
vubogovich
256,984,714
false
null
package kickstart2022.g // TODO fun main() { val inputFileName = "src/kickstart2022/g/CuteLittleButterfly.in" java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) } for (case in 1..readLine()!!.toInt()) { val (n, e) = readLine()!!.split(' ').map { it.toInt() } val f = Array(n) { val (x, y, c) = readLine()!!.split(' ').map { it.toInt() } Flower(x, y, c) }.toList() val res = findBestWay(0, 500, 1, f, e) println("Case #$case: $res") } } data class Flower(val x: Int, val y: Int, val c: Int) fun findBestWay(x: Int, y: Int, d: Int, f: List<Flower>, e: Int): Int { val g = f.filter { it.y <= y } return g.mapIndexed { i, it -> when { g.size == 1 && it.x * d >= x * d -> it.c g.size == 1 && it.x * d <= x * d && it.c > e -> it.c - e g.size > 1 && it.x * d >= x * d -> it.c + findBestWay(it.x, it.y, d, g.filterIndexed { j, _ -> i != j }, e) g.size > 1 && it.x * d <= x * d && it.c > e -> it.c - e + findBestWay(it.x, it.y, -d, g.filterIndexed { j, _ -> i != j }, e) else -> 0 } }.maxOrNull() ?: 0 }
0
Kotlin
0
0
fc694f84bd313cc9e8fcaa629bafa1d16ca570fb
1,210
kickstart
MIT License
src/iii_conventions/MyDate.kt
agpopikov
79,062,354
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (year.compareTo(other.year) != 0) { return year.compareTo(other.year) } else if (month.compareTo(other.month) != 0) { return month.compareTo(other.month) } else if (dayOfMonth.compareTo(other.dayOfMonth) != 0) { return dayOfMonth.compareTo(other.dayOfMonth) } else { return 0 } } operator fun plus(interval: TimeInterval): MyDate = addTimeIntervals(interval, 1) operator fun plus(intervals: TimeIntervals): MyDate = addTimeIntervals(intervals.interval, intervals.count) } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) data class TimeIntervals(val interval: TimeInterval, val count: Int) enum class TimeInterval { DAY, WEEK, YEAR; operator fun times(n: Int): TimeIntervals { return TimeIntervals(this, n) } } class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterator<MyDate> { private var current = start override fun contains(value: MyDate): Boolean { return start <= value && value <= endInclusive } override fun hasNext(): Boolean { return current <= endInclusive } override fun next(): MyDate { val result = current; current = current.copy(year = current.year, month = current.month, dayOfMonth = current.dayOfMonth + 1) return result } }
0
Kotlin
0
0
9ff8f0b38e04623bc99d098e20d6a90deb85587b
1,606
kotlin-koans
MIT License
src/Day09.kt
trosendo
572,903,458
false
{"Kotlin": 26100}
import java.lang.Exception enum class Direction(val code: Char) { UP('U'), DOWN('D'), LEFT('L'), RIGHT('R') } data class Position(val x: Int, val y: Int) { fun move(direction: Direction) = this.move(direction.code) fun move(direction: Char): Position = when (Direction.values().find { it.code == direction }) { Direction.UP -> this.x to this.y - 1 Direction.DOWN -> this.x to this.y + 1 Direction.LEFT -> this.x - 1 to this.y Direction.RIGHT -> this.x + 1 to this.y else -> { println("Unknown direction: $direction") this.x to this.y } }.toPosition() fun Pair<Int, Int>.toPosition(): Position = Position(this.first, this.second) fun isTouching(position: Position) = (this.x == position.x && this.y == position.y) || (this.x == position.x && (this.y == position.y - 1 || this.y == position.y + 1)) || (this.y == position.y && (this.x == position.x - 1 || this.x == position.x + 1)) || (this.x == position.x - 1 && this.y == position.y - 1) || (this.x == position.x + 1 && this.y == position.y - 1) || (this.x == position.x - 1 && this.y == position.y + 1) || (this.x == position.x + 1 && this.y == position.y + 1) fun moveToBeTouching(position: Position): Position { val xDiff = this.x - position.x val yDiff = this.y - position.y return when { xDiff == 0 && yDiff > 0 -> this.move(Direction.UP) xDiff == 0 && yDiff < 0 -> this.move(Direction.DOWN) xDiff > 0 && yDiff == 0 -> this.move(Direction.LEFT) xDiff < 0 && yDiff == 0 -> this.move(Direction.RIGHT) xDiff > 0 && yDiff > 0 -> this.move(Direction.LEFT).move(Direction.UP) xDiff < 0 && yDiff > 0 -> this.move(Direction.RIGHT).move(Direction.UP) xDiff > 0 && yDiff < 0 -> this.move(Direction.LEFT).move(Direction.DOWN) xDiff < 0 && yDiff < 0 -> this.move(Direction.RIGHT).move(Direction.DOWN) else -> { throw Exception("This should not happen") } } } } fun main() { fun checkTailIsTouchingHead(currentTailPosition: Position, nextHeadPosition: Position): Position { return if (!currentTailPosition.isTouching(nextHeadPosition)) { currentTailPosition.moveToBeTouching(nextHeadPosition) } else { currentTailPosition } } fun moveHeadAndTail( headPositions: List<Position>, tailPositions: List<Position>, direction: String ): Pair<List<Position>, List<Position>> { val currentHeadPosition = headPositions.last() val currentTailPosition = tailPositions.last() val nextHeadPosition = currentHeadPosition.move(direction.first()) val nextTailPosition = checkTailIsTouchingHead(currentTailPosition, nextHeadPosition) return headPositions + nextHeadPosition to tailPositions + nextTailPosition } fun processMoves(input: List<String>) = input.fold( listOf(Position(0, 0)) to listOf(Position(0, 0)) ) { (headPositions, tailPositions), s -> val (direction, amount) = s.split(" ") (0 until amount.toInt()).fold( headPositions to tailPositions ) { (headPositions, tailPositions), _ -> moveHeadAndTail(headPositions, tailPositions, direction) }.let { newPositions -> headPositions + newPositions.first.takeLast(amount.toInt()) to tailPositions + newPositions.second.takeLast(amount.toInt()) } } fun processMovesV2(input: List<String>, numberOfKnots: Int): Int { val listOfPositionsOfKnots = MutableList(numberOfKnots) { mutableListOf(Position(0, 0)) } for(s in input) { val (direction, amount) = s.split(" ") for (i in 0 until amount.toInt()) { val (newHeadPositions, newTailPositions) = moveHeadAndTail(listOfPositionsOfKnots[0], listOfPositionsOfKnots[1], direction) listOfPositionsOfKnots[0] = newHeadPositions.toMutableList() listOfPositionsOfKnots[1] = newTailPositions.toMutableList() for(knot in 1 until listOfPositionsOfKnots.size - 1) { val headPositions = listOfPositionsOfKnots[knot] val tailPositions = listOfPositionsOfKnots[knot + 1] val nextTailPosition = checkTailIsTouchingHead(tailPositions.last(), headPositions.last()) listOfPositionsOfKnots[knot + 1] += nextTailPosition } } } return listOfPositionsOfKnots.last().distinct().size } fun part1(input: List<String>): Int { val positions = processMoves(input) return positions.second.distinct().size } fun part2(input: List<String>): Int { return processMovesV2(input, 10) } println("Result of Part01 (test): " + part1(readInputAsList("Day09_test"))) println("Result of Part02 (test): " + part2(readInputAsList("Day09_test"))) println("Result of Part01: " + part1(readInputAsList("Day09"))) println("Result of Part02: " + part2(readInputAsList("Day09"))) }
0
Kotlin
0
0
ea66a6f6179dc131a73f884c10acf3eef8e66a43
5,248
AoC-2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions1.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test1() { printlnResult(15, 2) printlnResult(100, 4) printlnResult(101, 4) printlnResult(3, 4) printlnResult(96, 7) } /** * Questions 1: Implement a integer divide function, don't allow use '/', '*' and '%' */ private infix fun Int.divide(divisor: Int): Int { val dividend = this if (dividend == Int.MIN_VALUE && divisor == -1) return Int.MAX_VALUE var negative = 2 val calculateDividend = if (dividend > 0) { negative-- -dividend } else dividend val calculateDivisor = if (divisor > 0) { negative-- -divisor } else divisor val result = divideCore(calculateDividend, calculateDivisor) return if (negative == 1) -result else result } private fun divideCore(dividend: Int, divisor: Int): Int { var result = 0 var newDividend = dividend while (newDividend <= divisor) { var value = divisor var quotient = 1 while (value >= 0xc0000000 && newDividend <= value + value) { quotient += quotient value += value } result += quotient newDividend -= value } return result } private fun printlnResult(dividend: Int, divisor: Int) = println("The $dividend divide the $divisor equals (${dividend divide divisor})")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,344
Algorithm
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1143/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1143 import kotlin.math.max /** * LeetCode page: [1143. Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/); */ class Solution { /* Complexity: * Time O(MN) and Space O(MN) where M and N are the length of text1 and * text2, respectively; */ fun longestCommonSubsequence(text1: String, text2: String): Int { // dp[i][j]::= the length of LCS(text1[i:], text2[j:]) val dp = Array(text1.length + 1) { IntArray(text2.length + 1) } for (i in text1.indices.reversed()) { for (j in text2.indices.reversed()) { dp[i][j] = if (text1[i] == text2[j]) { 1 + dp[i + 1][j + 1] } else { max(dp[i + 1][j], dp[i][j + 1]) } } } return dp[0][0] } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
884
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/day01/Day1.kt
limelier
725,979,709
false
{"Kotlin": 48112}
package day01 import common.InputReader private fun String.asDigit(): Int = when(this) { "one", "1" -> 1 "two", "2" -> 2 "three", "3" -> 3 "four", "4" -> 4 "five", "5" -> 5 "six", "6" -> 6 "seven", "7" -> 7 "eight", "8" -> 8 "nine", "9" -> 9 "zero", "0" -> 0 else -> throw IllegalArgumentException("Expected string '$this' to be a digit or the name of a digit") } /** * Find the number made up of the first and last digits in the string, identified by the last group of the [regex] match. * * Overlaps are possible. */ private fun String.lineNumber(regex: Regex = """\d""".toRegex()): Int { val matches = regex.findAll(this).toList() val first = matches.first().groupValues.last().asDigit() val last = matches.last().groupValues.last().asDigit() return first * 10 + last } public fun main() { val lines = InputReader("day01/input.txt").lines() var sum1 = 0 var sum2 = 0 lines.forEach { line -> sum1 += line.lineNumber() sum2 += line.lineNumber("""(?=(one|two|three|four|five|six|seven|eight|nine|zero|\d))""".toRegex()) } println("Part 1: $sum1") println("Part 2: $sum2") }
0
Kotlin
0
0
0edcde7c96440b0a59e23ec25677f44ae2cfd20c
1,189
advent-of-code-2023-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MultiplyStrings.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL /** * Multiply Strings. * @see <a href="https://leetcode.com/problems/multiply-strings/">Source</a> */ object MultiplyStrings { operator fun invoke(num1: String, num2: String): String { val m: Int = num1.length val n: Int = num2.length val pos = IntArray(m + n) for (i in m - 1 downTo 0) { for (j in n - 1 downTo 0) { val mul: Int = (num1[i] - '0') * (num2[j] - '0') val p1 = i + j val p2 = i + j + 1 val sum = mul + pos[p2] pos[p1] += sum / DECIMAL pos[p2] = sum % DECIMAL } } val sb = StringBuilder() for (p in pos) if (!(sb.isEmpty() && p == 0)) sb.append(p) return if (sb.isEmpty()) "0" else sb.toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,492
kotlab
Apache License 2.0
src/main/java/Exercise21.kt
cortinico
317,667,457
false
null
fun main() { val food = object {} .javaClass .getResource("input-21.txt") .readText() .split("\n") .map { it.replace("(", "").replace(")", "").replace(",", "") } .map { it.split(" contains ") } .map { it[0].trim().split(" ").toMutableSet() to it[1].trim().split(" ").toSet() } val allergenes = food .flatMap { it.second } .distinct() .associateWith { allergene -> food.filter { allergene in it.second }.map { it.first }.reduce { acc, next -> (acc intersect next).toMutableSet() } } .toMutableMap() while (allergenes.isNotEmpty()) { val entryToRemove = allergenes.filter { it.value.size == 1 }.entries.first() val keyToRemove = entryToRemove.key val valueToRemove = entryToRemove.value.first() allergenes.remove(keyToRemove) food.forEach { (ingredients, _) -> ingredients.remove(valueToRemove) } allergenes.forEach { (_, value) -> value.remove(valueToRemove) } } food.sumBy { it.first.size }.also(::println) }
1
Kotlin
0
4
a0d980a6253ec210433e2688cfc6df35104aa9df
1,191
adventofcode-2020
MIT License
leetcode/src/daily/Interview0108.kt
zhangweizhe
387,808,774
false
null
package daily fun main() { // 面试题 01.08. 零矩阵 // https://leetcode.cn/problems/zero-matrix-lcci/ val matrix = arrayOf(arrayOf(0,1,2,0).toIntArray(), arrayOf(3,4,5,2).toIntArray(), arrayOf(1,3,1,5).toIntArray()) setZeroes1(matrix) println(matrix.contentDeepToString()) } fun setZeroes(matrix: Array<IntArray>): Unit { if (matrix.isEmpty()) { return } val rowSet = HashSet<Int>() val columnSet = HashSet<Int>() for (i in matrix.indices) { for (j in matrix[0].indices) { if (matrix[i][j] == 0) { rowSet.add(i) columnSet.add(j) } } } for (rowIndex in rowSet) { for (j in matrix[0].indices) { matrix[rowIndex][j] = 0 } } for (columnIndex in columnSet) { for (i in matrix.indices) { matrix[i][columnIndex] = 0 } } } fun setZeroes1(matrix: Array<IntArray>): Unit { if (matrix.isEmpty()) { return } var firstRowContains0 = false var firstColumnContains0 = false for (rowIndex in matrix.indices) { for (columnIndex in matrix[rowIndex].indices) { if (matrix[rowIndex][columnIndex] == 0) { if (rowIndex == 0) { // 第一行包含0 firstRowContains0 = true } if (columnIndex == 0) { // 第一列包含0 firstColumnContains0 = true } // 用第一行、第一列作为标识位 matrix[0][columnIndex] = 0 matrix[rowIndex][0] = 0 } } } for (rowIndex in 1 until matrix.size) { if (matrix[rowIndex][0] == 0) { for (columnIndex in 1 until matrix[rowIndex].size) { matrix[rowIndex][columnIndex] = 0 } } } for (columnIndex in 1 until matrix[0].size) { if (matrix[0][columnIndex] == 0) { for (rowIndex in 1 until matrix.size) { matrix[rowIndex][columnIndex] = 0 } } } if (firstColumnContains0) { for (rowIndex in matrix.indices) { matrix[rowIndex][0] = 0 } } if (firstRowContains0) { for (columnIndex in matrix[0].indices) { matrix[0][columnIndex] = 0 } } }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
2,418
kotlin-study
MIT License
Kotlin/EdmondsKarp/EdmondsKarp.kt
19-2-SKKU-OSS
223,087,912
true
{"C++": 154443, "Java": 104625, "JavaScript": 78282, "Python": 75943, "HTML": 72298, "CSS": 45256, "C": 45238, "Swift": 22186, "C#": 20216, "Go": 17191, "Kotlin": 16813, "Ruby": 14089, "Haskell": 5956, "Shell": 4379, "Scala": 4198, "Rust": 3485, "Perl": 1926, "Crystal": 812, "Smalltalk": 793, "Makefile": 727, "Racket": 406, "Brainfuck": 308}
import java.util.Scanner import java.util.* //FloydWarshall fun main(args: Array<String>){ println("FloydWarshall"); var capacity = Array<IntArray>(51, {IntArray(51)}) var flow = Array<IntArray>(51, {IntArray(51)}) var visited = IntArray(51){0} val V = 5; //V : number of vertices //E : number of edges capacity[1][2] = 3; //There is pipe between 1 and 2 that has 2 unit of capcity. capacity[2][3] = 3; capacity[3][4] = 5; capacity[4][5] = 4; capacity[2][5] = 6; capacity[2][1] = 3; capacity[3][2] = 3; capacity[4][3] = 5; capacity[5][4] = 4; capacity[5][2] = 6; val start: Int = 1; val end: Int = 5; var q: Queue<Int> = LinkedList(); var maxflow: Int = 0; while(true){ for(i in 1..V){ visited[i] = 0 } q.add(start) while(!q.isEmpty()){ val front = q.poll(); for(i in 1..V){ if(front != i && capacity[front][i] != 0){ if(capacity[front][i] - flow[front][i] > 0 && visited[i] == 0){ q.add(i) visited[i] = front; if(i == end){ break; } } } } }//end of while(q empty) if(visited[end] == 0) break; //there is no possible way anymore //find minimum of capacity on the way var allowable_flow: Int = 99999999 var prev = end; while(true){ if(allowable_flow > (capacity[visited[prev]][prev] - flow[visited[prev]][prev])){ allowable_flow = capacity[visited[prev]][prev] - flow[visited[prev]][prev]; } prev = visited[prev] if(prev == start) break; } prev = end; //update the flow (current flowing amount) while(true){ flow[visited[prev]][prev] += allowable_flow flow[prev][visited[prev]] += allowable_flow prev = visited[prev] if(prev == start) break; } maxflow = maxflow + allowable_flow } println(maxflow) }
0
C++
1
0
2b55676c1bcd5d327fc9e304925a05cb70e25904
2,147
2019-2-OSS-L5
Apache License 2.0
src/codeforces/problem1B/Main.kt
arnavb
241,486,069
false
null
package codeforces.problem1B fun convertToExcelFormat(coord: String, alphabet: CharArray): String { val row = coord.substring(1, coord.indexOf('C')) var column = coord.substring(coord.indexOf('C') + 1).toInt() // Convert column number to letters val resultingColumn = StringBuilder() while (column > 26) { var remainder = column % 26 if (remainder == 0) { // 0 is represented by Z with one less letter remainder = 26 } resultingColumn.append(alphabet[remainder]) column -= remainder column /= 26 } resultingColumn.append(alphabet[column]) return "${resultingColumn.reverse()}$row" } fun convertToNumericalFormat(coord: String, alphabet: CharArray): String { val firstDigitPos = coord.indexOfFirst { it.isDigit() } val row = coord.substring(firstDigitPos) val column = coord.substring(0, firstDigitPos) var convertedColumn = 0 var powerOf26 = 1 for (i in column.length - 1 downTo 0) { convertedColumn += powerOf26 * alphabet.binarySearch(column[i]) powerOf26 *= 26 } return "R${row}C$convertedColumn" } fun main() { val numLines = readLine()!!.toInt() val alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() val outputs = mutableListOf<String>() for (i in 0 until numLines) { val currentLine = readLine()!! val positionOfC = currentLine.indexOf('C') if (positionOfC > 0 && currentLine[positionOfC - 1].isDigit()) { // Input is in Row Column format outputs.add(convertToExcelFormat(currentLine, alphabet)) } else { // Input is in Letter Row format outputs.add(convertToNumericalFormat(currentLine, alphabet)) } } println(outputs.joinToString("\n")) }
0
Kotlin
0
0
5b805ce90f10192d4499d9abead8b2c109ff59ea
1,815
competitive-programming-kotlin
MIT License
src/main/kotlin/days/Day19.kt
andilau
429,557,457
false
{"Kotlin": 103829}
package days import java.util.* @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2015/day/19", date = Date(day = 19, year = 2015) ) class Day19(input: List<String>) : Puzzle { private val replacements = parseReplacements(input) private val medicine = parseMedicin(input) override fun partOne(): Int = medicine.moleculesFusion().distinct().count() override fun partTwo(): Int { var minimumSteps = Int.MAX_VALUE val queue = PriorityQueue(compareBy<IndexedValue<Molecule>> { it.value.value.length }) queue.add(IndexedValue(0, medicine)) val seen = mutableSetOf<Molecule>() while (queue.isNotEmpty()) { val poll = queue.poll() val (steps, molecule) = poll if (molecule in seen) continue seen += molecule if (steps > minimumSteps) continue if (molecule == Molecule.SINGLE_ELECTRON) { minimumSteps = steps break } molecule.moleculesFission().forEach { queue += IndexedValue(steps + 1, it) } } return minimumSteps } private fun parseReplacements(input: List<String>) = input .takeWhile(String::isNotEmpty) .map { line -> line.split(" => ").let { it.first() to it.last() } } .asSequence() private fun parseMedicin(input: List<String>) = input .dropWhile(String::isNotEmpty) .drop(1) .first() .let { Molecule(it) } private fun Molecule.moleculesFusion(): Sequence<Molecule> = replacements .flatMap { (from, to) -> this.replace(from, to) } private fun Molecule.moleculesFission(): Sequence<Molecule> = replacements .flatMap { (from, to) -> this.replace(to, from) } @JvmInline value class Molecule(val value: String) { companion object { val SINGLE_ELECTRON = Molecule("e") } } private fun Molecule.replace(from: String, to: String) = sequence { var index = 0 val molecule = this@replace while (true) { index = molecule.value.indexOf(from, index) if (index == -1) return@sequence yield( Molecule( molecule.value.substring(0, index) + to + molecule.value.substring( index + from.length, value.length ) ) ) index++ } } }
0
Kotlin
0
0
55932fb63d6a13a1aa8c8df127593d38b760a34c
2,549
advent-of-code-2015
Creative Commons Zero v1.0 Universal
src/main/kotlin/g0301_0400/s0315_count_of_smaller_numbers_after_self/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0315_count_of_smaller_numbers_after_self // #Hard #Top_Interview_Questions #Array #Binary_Search #Ordered_Set #Divide_and_Conquer // #Segment_Tree #Binary_Indexed_Tree #Merge_Sort // #2022_11_10_Time_1282_ms_(88.46%)_Space_109.8_MB_(46.15%) import java.util.LinkedList @Suppress("NAME_SHADOWING") class Solution { fun countSmaller(nums: IntArray): List<Int> { var minVal = 10001 var maxVal = -10001 for (a in nums) { minVal = Math.min(minVal, a) maxVal = Math.max(maxVal, a) } val range = maxVal - (minVal - 1) + 1 val offset = -(minVal - 1) val bit = FenwickTree(range) val ans = LinkedList<Int>() val n = nums.size var i = n - 1 while (i >= 0) { bit.update(offset + nums[i], 1) ans.addFirst(bit.ps(offset + nums[i] - 1)) i-- } return ans } private class FenwickTree(n: Int) { // binary index tree, index 0 is not used var bit: IntArray var n: Int init { this.n = n + 1 bit = IntArray(this.n) } fun update(i: Int, v: Int) { var i = i while (i < n) { bit[i] += v i += Integer.lowestOneBit(i) } } // prefix sum query fun ps(j: Int): Int { var j = j var ps = 0 while (j != 0) { ps += bit[j] j -= Integer.lowestOneBit(j) } return ps } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,607
LeetCode-in-Kotlin
MIT License
src/main/kotlin/abc/315-e.kt
kirimin
197,707,422
false
null
package abc import utilities.debugLog import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val p = (0 until n).map { val c = sc.next().toInt() (0 until c).map { sc.next().toInt() } } println(problem315e(n, p)) } fun problem315e(n: Int, p: List<List<Int>>): String { fun topologicalSort(graph: List<List<Int>>): List<Int>? { val n = graph.size val inDegree = IntArray(n) val result = mutableListOf<Int>() graph.forEach { edges -> edges.forEach { node -> inDegree[node]++ } } val queue = ArrayDeque<Int>() for (i in 0 until n) { if (inDegree[i] == 0) { queue.add(i) } } while (queue.isNotEmpty()) { val current = queue.removeFirst() result.add(current) graph[current].forEach { neighbor -> if (--inDegree[neighbor] == 0) { queue.add(neighbor) } } } return if (result.size == n) result else null } val routes = Array(n + 1) { mutableListOf<Int>() } for (i in 0 until n) { val pi = p[i] for (j in 0 until pi.size) { routes[i + 1].add(pi[j]) } } val distances = IntArray(n + 1) { -1 } val queue = ArrayDeque<Int>() queue.offer(1) distances[1] = 0 while(!queue.isEmpty()) { val current = queue.poll() for (i in 0 until routes[current].size) { val next = routes[current][i] if (distances[next] != -1) continue distances[next] = distances[current] + 1 queue.offer(next) } } val ans = mutableListOf<Int>() val sorted = topologicalSort(routes.toList())!! for (i in 0 until sorted.size) { val current = sorted[i] if (distances[current] == -1) continue ans.add(current) } return ans.drop(1).reversed().joinToString(" ") }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
2,070
AtCoderLog
The Unlicense
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2017/2017-13.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2017 fun main() { println("Part1:") println(part1(testInput1)) println(part1(input)) println() println("Part2:") println(part2(testInput1)) println(part2(input)) } private fun part1(input: String): Int { val setup = parse(input) return setup.sumOf { (layer, depth) -> if (isCaught(layer, depth)) layer * depth else 0 } } private fun part2(input: String): Int { val setup = parse(input) var delay = 0 while (true) { if (setup.none { (layer, depth) -> isCaught(layer + delay, depth) }) return delay delay++ } } private fun isCaught(time: Int, depth: Int) = time % ((depth - 1) * 2) == 0 private fun parse(input: String): List<Pair<Int, Int>> { val initial = input.lines().map { val (l, r) = it.split(": ") l.toInt() to r.toInt() } return initial } private const val testInput1 = """0: 3 1: 2 4: 4 6: 4""" private const val input = """0: 3 1: 2 2: 5 4: 4 6: 6 8: 4 10: 8 12: 8 14: 6 16: 8 18: 6 20: 6 22: 8 24: 12 26: 12 28: 8 30: 12 32: 12 34: 8 36: 10 38: 9 40: 12 42: 10 44: 12 46: 14 48: 14 50: 12 52: 14 56: 12 58: 12 60: 14 62: 14 64: 12 66: 14 68: 14 70: 14 74: 24 76: 14 80: 18 82: 14 84: 14 90: 14 94: 17"""
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,265
advent-of-code
MIT License
app/src/main/kotlin/kotlinadventofcode/2015/2015-15.kt
pragmaticpandy
356,481,847
false
{"Kotlin": 1003522, "Shell": 219}
// Originally generated by the template in CodeDAO package kotlinadventofcode.`2015` import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.grammar.parseToEnd import com.github.h0tk3y.betterParse.lexer.literalToken import com.github.h0tk3y.betterParse.lexer.regexToken import kotlinadventofcode.Day import kotlin.math.max import kotlin.math.min import kotlin.random.Random import kotlin.random.nextInt const val targetCalories = 500 const val bestScoreExcludingCalories = 21367368 const val totalIngredientAmount = 100 class `2015-15` : Day { data class Ingredient( val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int ) data class Recipe(val ingredients: Set<Pair<Ingredient, Int>>) { val score: Int by lazy { max(0, ingredients.sumOf { it.first.capacity * it.second }) * max(0, ingredients.sumOf { it.first.durability * it.second }) * max(0, ingredients.sumOf { it.first.flavor * it.second }) * max(0, ingredients.sumOf { it.first.texture * it.second }) } val tweaks: Collection<Recipe> by lazy { val ingredientsList = ingredients.toList() var result: MutableSet<Recipe> = mutableSetOf() for (indexToGive in ingredientsList.indices) { if (ingredientsList[indexToGive].second == 0) continue for (indexToTake in ingredientsList.indices.minus(indexToGive)) { result.add(Recipe( ingredientsList.indices .map { when (it) { indexToGive -> ingredientsList[it].first to ingredientsList[it].second - 1 indexToTake -> ingredientsList[it].first to ingredientsList[it].second + 1 else -> ingredientsList[it] } } .toSet())) } } result } } fun parse(input: String): List<Ingredient> { val grammar = object: Grammar<List<Ingredient>>() { // match literals first val newline by literalToken("\n") val capacity by literalToken(": capacity ") val durability by literalToken(", durability ") val flavor by literalToken(", flavor ") val texture by literalToken(", texture ") val calories by literalToken(", calories ") // then match expressions val numberToken by regexToken("""-?\d+""") val name by regexToken("""[A-Z][a-z]+""") val number by numberToken use { text.toInt() } val line by (name use { text }) and skip(capacity) and number and skip(durability) and number and skip(flavor) and number and skip(texture) and number and skip(calories) and number val ingredient by line.map { Ingredient(it.t1, it.t2, it.t3, it.t4, it.t5, it.t6) } override val rootParser by separatedTerms(ingredient, newline) } return grammar.parseToEnd(input) } /** * After verifying your solution on the AoC site, run `./ka continue` to add a test for it. */ override fun runPartOneNoUI(input: String): String { val totalIngredientAmount = 100 /* * Let's see if we can hill climb well enough to not get trapped by local maxes. * * Edit: the below as implemented works, but may not work if there were local maxes. Instead * of sampling up front, this should be changed to take one sample, run the algorithm, then * repeat. */ val ingredients = parse(input) val numStartingRecipes = 3 val startingRecipes = (1..numStartingRecipes).map { val ingredientAmounts = ingredients.map { 0 }.toMutableList() (1..totalIngredientAmount).forEach { ingredientAmounts[Random.nextInt(ingredients.indices)]++ } Recipe(ingredients.toList().zip(ingredientAmounts).toSet()) } val queue = ArrayDeque(startingRecipes) val recipesPreviouslyAddedToQueue: MutableSet<Recipe> = mutableSetOf() recipesPreviouslyAddedToQueue.addAll(startingRecipes) var bestRecipe: Recipe? = null while (queue.isNotEmpty()) { val recipe = queue.removeFirst() if (bestRecipe == null || recipe.score > bestRecipe.score) bestRecipe = recipe for (tweak in recipe.tweaks) { if (tweak !in recipesPreviouslyAddedToQueue && tweak.score >= bestRecipe.score) { queue.addLast(tweak) recipesPreviouslyAddedToQueue.add(tweak) } } } return bestRecipe?.score.toString() } /** * This was fun in that the part 1 hill climbing approach doesn't work at all. Instead, I had * to use the calorie and teaspoon targets to limit the search space. */ override fun runPartTwoNoUI(input: String): String { /** * gets all recipes that exactly match the number of teaspoons and number of calories */ fun getAllRecipes(ingredients: Set<Ingredient>, teaspoons: Int, calories: Int): Set<Recipe> { // If we need no more ingredients nor calories, there is one valid recipe which matches that. if (teaspoons == 0 && calories == 0) return setOf(Recipe(setOf())) /** * Some conditions that make any valid recipes impossible: * * one of teaspoons or calories is 0 but the other isn't * * teaspoons or calories are negative * * teaspoons and calories are non-zero, but there are no ingredients */ if (teaspoons < 1 || calories < 1 || ingredients.isEmpty()) return setOf() val result = mutableSetOf<Recipe>() val currentIngredient = ingredients.first() val otherIngredients = ingredients.minus(currentIngredient) for (currentIngredientAmount in 0..min(teaspoons, calories / currentIngredient.calories)) { for (recipe in getAllRecipes( otherIngredients, teaspoons - currentIngredientAmount, calories - (currentIngredient.calories * currentIngredientAmount))) { result.add(Recipe(recipe.ingredients + (currentIngredient to currentIngredientAmount))) } } return result } return getAllRecipes(parse(input).toSet(), totalIngredientAmount, targetCalories) .maxOf { it.score } .toString() } override val defaultInput = """Sprinkles: capacity 2, durability 0, flavor -2, texture 0, calories 3 Butterscotch: capacity 0, durability 5, flavor -3, texture 0, calories 3 Chocolate: capacity 0, durability 0, flavor 5, texture -1, calories 8 Candy: capacity 0, durability -1, flavor 0, texture 5, calories 8""" }
0
Kotlin
0
3
26ef6b194f3e22783cbbaf1489fc125d9aff9566
7,415
kotlinadventofcode
MIT License
src/main/kotlin/org/nield/kotlinstatistics/Random.kt
thomasnield
84,361,977
false
null
package org.nield.kotlinstatistics import java.util.concurrent.ThreadLocalRandom /** * Samples a single random element `T` from a `List<T>`, and throws an error if no elements exist */ fun <T> List<T>.randomFirst() = randomFirstOrNull()?: throw Exception("No elements found!") /** * Samples a single random element `T` from a `List<T>`, and returns `null` if no elements exist */ fun <T> List<T>.randomFirstOrNull(): T? { if (size == 0) return null val random = ThreadLocalRandom.current().nextInt(0,size) return this[random] } /** * Samples a single random element `T` from a `Sequence<T>`, and throws an error if no elements exist */ fun <T> Sequence<T>.randomFirst() = toList().randomFirst() /** * Samples a single random element `T` from a `Sequence<T>`, and returns `null` if no elements exist */ fun <T> Sequence<T>.randomFirstOrNull() = toList().randomFirstOrNull() /** * Samples a single random element `T` from a `Sequence<T>`, and throws an error if no elements exist */ fun <T> Iterable<T>.randomFirst() = toList().randomFirst() /** * Samples a single random element `T` from an `Iterable<T>`, and returns `null` if no elements exist */ fun <T> Iterable<T>.randomFirstOrNull() = toList().randomFirstOrNull() /** * Samples `n` distinct random elements `T` from a `Sequence<T>` */ fun <T> Sequence<T>.randomDistinct(sampleSize: Int) = toList().randomDistinct(sampleSize) /** * Samples `n` distinct random elements `T` from an `Iterable<T>` */ fun <T> List<T>.randomDistinct(sampleSize: Int): List<T> { val cappedSampleSize = if (sampleSize > size) size else sampleSize return (0..Int.MAX_VALUE).asSequence().map { ThreadLocalRandom.current().nextInt(0,size) }.distinct() .take(cappedSampleSize) .map { this[it] } .toList() } /** * Samples `n` random elements `T` from a `Sequence<T>` */ fun <T> Sequence<T>.random(sampleSize: Int) = toList().random(sampleSize) /** * Samples `n` random elements `T` from an `Iterable<T>` */ fun <T> List<T>.random(sampleSize: Int): List<T> { val cappedSampleSize = if (sampleSize > size) size else sampleSize return (0..Int.MAX_VALUE).asSequence().map { ThreadLocalRandom.current().nextInt(0,size) }.take(cappedSampleSize) .map { this[it] } .toList() } /** * Simulates a weighted TRUE/FALSE coin flip, with a percentage of probability towards TRUE * * In other words, this is a Probability Density Function (PDF) for discrete TRUE/FALSE values */ class WeightedCoin(val trueProbability: Double) { fun flip() = ThreadLocalRandom.current().nextDouble(0.0,1.0) <= trueProbability } /** * Simulates a weighted TRUE/FALSE coin flip, with a percentage of probability towards TRUE * * In other words, this is a Probability Density Function (PDF) for discrete TRUE/FALSE values */ fun weightedCoinFlip(trueProbability: Double) = ThreadLocalRandom.current().nextDouble(0.0,1.0) <= trueProbability /** * Assigns a probabilty to each distinct `T` item, and randomly selects `T` values given those probabilities. * * In other words, this is a Probability Density Function (PDF) for discrete `T` values */ class WeightedDice<T>(val probabilities: Map<T,Double>) { constructor(vararg values: Pair<T, Double>): this( values.toMap() ) private val sum = probabilities.values.sum() val rangedDistribution = probabilities.let { var binStart = 0.0 it.asSequence().sortedBy { it.value } .map { it.key to OpenDoubleRange(binStart, it.value + binStart) } .onEach { binStart = it.second.endExclusive } .toMap() } /** * Randomly selects a `T` value with probability */ fun roll() = ThreadLocalRandom.current().nextDouble(0.0, sum).let { rangedDistribution.asIterable().first { rng -> it in rng.value }.key } }
15
Kotlin
48
840
17f64bae2a3cea2e85f05c08172d19a290561e3b
3,911
kotlin-statistics
Apache License 2.0
src/Day04.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): Int = input.map { pairs -> pairs.getAssignments() } .count { (a, b, c, d) -> a in c..d && b in c..d || c in a..b && d in a..b } fun part2(input: List<String>): Int = input.map { pairs -> pairs.getAssignments() } .count { (a, b, c, d) -> (a..b).intersect(c..d).isNotEmpty() } val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun String.getAssignments(): Assignment = replace(",", "-").split("-") .let { elements -> Assignment(elements[0].toInt(), elements[1].toInt(), elements[2].toInt(), elements[3].toInt()) } data class Assignment(val a: Int, val b: Int, val c: Int, val d: Int)
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
752
aoc-2022
Apache License 2.0
src/test/kotlin/amb/aoc2020/day18.kt
andreasmuellerbluemlein
318,221,589
false
null
package amb.aoc2020 import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day18 : TestBase() { class Number(var number: String) : Operand { override fun getValue(): Long { return number.toLong() } } interface Operand { fun getValue(): Long } class CalcOperation( operand1: Operand, operand2: Operand, var operation: Char ) : Operation(operand1, operand2) { override fun getValue(): Long { return if (operation == '+') operand1.getValue() + operand2.getValue() else operand1.getValue() * operand2.getValue() } } abstract class Operation( var operand1: Operand, var operand2: Operand, ) : Operand fun parse(input: String): Operand { if (input.contains('(')) { val regex = """\(([0-9\s+*]*)\)""".toRegex() val match = regex.find(input)!! return parse(input.replace(match.value, parse(match.value.drop(1).dropLast(1)).getValue().toString())) } if (input.last().isDigit()) { val numberString = input.takeLastWhile { it.isDigit() } if (input.count() > numberString.count()) { val operator = input.dropLast(numberString.count() + 1).last() return CalcOperation(parse(input.dropLast(numberString.count() + 3)), Number(numberString), operator) } else ( return Number(numberString) ) } throw NotImplementedError() } fun parse2(input: String): Operand { //find opening brackets, calc inner result and textreplace result into original if (input.contains('(')) { val regex = """\(([0-9\s+*]*)\)""".toRegex() val match = regex.find(input)!! return parse2(input.replace(match.value, parse2(match.value.drop(1).dropLast(1)).getValue().toString())) } //find simple sum equation, calc result and textreplace into original var regex = """([0-9]+\s[+]\s[0-9]+)""".toRegex() var match = regex.find(input) if(match != null) { val operands = match.value.split(" + ") val result = operands[0].toLong() + operands[1].toLong() return parse2(input.replace(match.value, result.toString())) } //find simple multiply equation, calc result and textreplace into original regex = """([0-9]+\s[*]\s[0-9]+)""".toRegex() match = regex.find(input) if(match != null) { val operands = match.value.split(" * ") val result = operands[0].toLong() * operands[1].toLong() return parse2(input.replace(match.value, result.toString())) } return Number(input) } @Test fun task1() { var sum = getTestData("input18") .filter { it.isNotEmpty() } .map { line -> parse(line).getValue() }.sum() logger.info { "sum is $sum" } } @Test fun task2() { var sum = getTestData("input18") .filter { it.isNotEmpty() } .map { line -> val result = parse2(line).getValue() logger.info { "$line = $result" } result }.sum() logger.info { "sum is $sum" } } @Test fun subTest(){ assertEquals(51L, parse2("1 + (2 * 3) + (4 * (5 + 6))").getValue()) assertEquals(46L, parse2("2 * 3 + (4 * 5)").getValue()) assertEquals(1445L, parse2("5 + (8 * 3 + 9 + 3 * 4 * 3)").getValue()) assertEquals(669060L, parse2("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))").getValue()) assertEquals(23340L, parse2("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2").getValue()) } }
1
Kotlin
0
0
dad1fa57c2b11bf05a51e5fa183775206cf055cf
3,825
aoc2020
MIT License
src/2023/Day04.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import java.io.File import java.util.* fun main() { Day04().solve() } class Day04 { val input1 = """ Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 """.trimIndent() val input2 = """ """.trimIndent() fun solve() { val f = File("src/2023/inputs/day04.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = 0 var sum1 = 0 var lineix = 0 val winnums = mutableListOf<Int>() while (s.hasNextLine()) { val line = s.nextLine().trim() if (line.isEmpty()) { continue } lineix++ val s1 = line.split(Regex("[:|]")) val numbers = s1[1].trim().split(Regex("[ ]+")).map { it.toInt() }.toSet() val winners = s1[2].trim().split(Regex("[ ]+")).map { it.toInt() }.toSet() val winningNumbers = numbers.intersect(winners) val p = if (winningNumbers.size > 0) { var p1 = 1 winningNumbers.forEach { p1 *= 2 } p1/2 } else {0} sum += p winnums.add(winningNumbers.size) } val cards = winnums.map { 1 }.toMutableList() for (i in 0 until lineix) { for (j in 1 .. winnums[i]) { if (i + j < cards.size) { cards[i + j] += cards[i] } else { break } } sum1 += cards[i] } print("$sum $sum1\n") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
1,906
advent-of-code
Apache License 2.0
keywordsearch/src/main/kotlin/com/ikbalabki/keywordsearch/model/TernarySearchTrie.kt
ikbalkaya
655,813,368
false
null
package com.ikbalabki.keywordsearch.model /*** This class implements ternary search tree (https://en.wikipedia.org/wiki/Ternary_search_tree) Which is similar to a binary tree with exception of nodes having 3 child nodes instead of one This data structure is memory efficient and can be used for large data sets. * */ internal class TernarySearchTrie<T : Searchable>(private val caseSensitive: Boolean) { private var root: Node<T>? = null private var size = 0L /** * Add an object to be searchable for later. * * @param searchable object to be searchable * **/ fun add(searchable: T) { //recursively add node using ternary object and character index root = add(root, searchable, 0) size++ } /** * Number of searchable objects in the tree. * */ fun size() = size private fun add(givenNode: Node<T>?, searchable: T, charIndex: Int): Node<T>? { val char = if (caseSensitive) searchable.text[charIndex] else searchable.text[charIndex].lowercaseChar() var node = givenNode //if deos not already exist create it if (givenNode == null) { //only add the object to the tree if it's the terminal character reached var searchableObject: T? = null if (searchable.text.length == (charIndex + 1)) { searchableObject = searchable } node = Node( searchableObject, char = char, left = null, middle = null, right = null ) if (root == null) root = node } //recursively add left/ right nodes, right and left nodes in ternary tree //if given char exist in mid node continue with middle link and finish middle link when // terminal character is reached node?.let { tNode -> when { char < tNode.char -> { tNode.left = add(tNode.left, searchable, charIndex) } char > tNode.char -> { tNode.right = add(tNode.right, searchable, charIndex) } charIndex < searchable.text.length - 1 -> { //follow with next middle node tNode.middle = add(node.middle, searchable, charIndex + 1) } else -> tNode.searchable = searchable } } return node } /** * Find objects that matches the start of the keyword. * * @param prefix prefix to be searched * * @return list of objects that matches the prefix * */ fun itemsWithPrefix(prefix: String): List<T> { require(prefix.isNotEmpty()) val items = mutableListOf<T>() findItemsWithPrefix(root, if (caseSensitive) prefix else prefix.lowercase(), items) return items } private fun findItemsWithPrefix(node: Node<T>?, prefix: String, foundObjects: MutableList<T>) { if (node == null) return when { prefix.first() < node.char -> { findItemsWithPrefix(node.left, prefix, foundObjects) } prefix.first() > node.char -> { findItemsWithPrefix(node.right, prefix, foundObjects) } prefix.first() == node.char -> { if (prefix.length > 1) { //last character not reached yet //if keyword is 'lon' - and 'l' is found, remove first char from keyword and // continue search for 'on' val newKeyword = prefix.substring(1, prefix.length) findItemsWithPrefix(node.middle, newKeyword, foundObjects) } else { //we have reached to the end of keyword, now we should add // remaining objects sorted using pre-order traversal to get items // sorted //add the keyword itself if it's also a ternary object node.searchable?.let { foundObjects.add(it) } //add all objects traversing from the middle node traverseAdd(node.middle, foundObjects) } } } } private fun traverseAdd(node: Node<T>?, objectList: MutableList<T>) { if (node == null) { return } traverseAdd(node.left, objectList) node.searchable?.let { objectList.add(it) } traverseAdd(node.middle, objectList) traverseAdd(node.right, objectList) } /** * Check if the tree contains the searchable object. * * @param searchable object to be searched * * @return true if the object is found, false otherwise * */ fun contains(searchable: T): Boolean { itemsWithPrefix(searchable.text).let { return it.contains(searchable) } } } data class Node<T : Searchable>( var searchable: T?, var char: Char, var left: Node<T>?, var middle: Node<T>?, var right: Node<T>? )
0
Kotlin
0
0
99bb35ca5f73d2775b395cb2ae9e9221329f6178
5,211
KeywordSearch
Apache License 2.0
src/questions/PascalTriangle.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Given an integer numRows, return the first numRows of Pascal's triangle. * In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: * * <img src="https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif" height="150" width="150"/> * [Source](https://leetcode.com/problems/pascals-triangle/) */ @UseCommentAsDocumentation private fun pascalTriangle(numRows: Int): List<List<Int>> { if (numRows == 1) { return listOf(listOf(1)) } val result = mutableListOf<List<Int>>() result.add(listOf(1)) generateTriangle(1, maxRows = numRows, previous = listOf(1), result = result) return result } private fun generateTriangle(current: Int, maxRows: Int, previous: List<Int>, result: MutableList<List<Int>>) { if (current == maxRows) { return } val currentRow = MutableList(current + 1) { 1 } for (i in 1..current) { // 0 and lastIndex is always 1 // sum of the two numbers directly above it currentRow[i] = (previous.getOrNull(i - 1) ?: 0) + (previous.getOrNull(i) ?: 0) } result.add(currentRow) generateTriangle(current + 1, maxRows, currentRow, result) } fun main() { pascalTriangle(numRows = 5) shouldBe listOf( listOf(1), listOf(1, 1), listOf(1, 2, 1), listOf(1, 3, 3, 1), listOf(1, 4, 6, 4, 1) ) pascalTriangle(numRows = 1) shouldBe listOf( listOf(1), ) pascalTriangle(numRows = 2) shouldBe listOf( listOf(1), listOf(1, 1), ) pascalTriangle(numRows = 3) shouldBe listOf( listOf(1), listOf(1, 1), listOf(1, 2, 1), ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,774
algorithms
MIT License
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/AdjacencyMatrixWeightedGraph.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.* fun main() { val adjacencyMatrixWeightedGraph = AdjacencyMatrixWeightedGraph(6) adjacencyMatrixWeightedGraph.accept(Scanner(System.`in`)) adjacencyMatrixWeightedGraph.display() } class AdjacencyMatrixWeightedGraph(val vertCount: Int) { var matrix = Array(vertCount) { Array(vertCount) { Int.MAX_VALUE } } fun accept(sc: Scanner) { println("Enter the edge count:") val edgeCount = sc.nextInt() println("Enter number of " + edgeCount + "src - - dst --- weight") for (i in 0..edgeCount) { val src = sc.nextInt() val dst = sc.nextInt() val weight = sc.nextInt() matrix[src][dst] = weight matrix[dst][src] = weight } } fun display() { for ((i, element) in matrix.withIndex()) { println() for (j in element.indices) { if (matrix[i][j] == Int.MAX_VALUE) { print("\t#") } else { print("\t${matrix[i][j]}") } } println() } } } /* 7 0 1 7 0 2 4 0 3 8 1 2 9 1 4 5 3 4 6 3 5 2 */
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,227
DS_Algo_Kotlin
MIT License
src/main/kotlin/g1201_1300/s1203_sort_items_by_groups_respecting_dependencies/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1201_1300.s1203_sort_items_by_groups_respecting_dependencies // #Hard #Depth_First_Search #Breadth_First_Search #Graph #Topological_Sort // #2023_06_09_Time_503_ms_(100.00%)_Space_56.8_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { fun sortItems(n: Int, m: Int, group: IntArray, beforeItems: List<List<Int>>): IntArray { var totalGroups = m val indexGroupMap: MutableMap<Int, MutableList<Int>> = HashMap() for (i in 0 until n) { if (group[i] == -1) { group[i] = totalGroups indexGroupMap[totalGroups] = ArrayList() indexGroupMap[totalGroups]!!.add(i) totalGroups++ } else { indexGroupMap.putIfAbsent(group[i], ArrayList()) indexGroupMap[group[i]]!!.add(i) } } val externalInMap = IntArray(totalGroups) val internalInMap = IntArray(n) val externalGraph: MutableMap<Int, MutableList<Int>> = HashMap() val internalGraph: MutableMap<Int, MutableList<Int>> = HashMap() for (i in beforeItems.indices) { if (beforeItems[i].isNotEmpty()) { val groupNumber = group[i] for (j in beforeItems[i].indices) { val prevItem = beforeItems[i][j] val prevGroupNumber = group[prevItem] if (groupNumber == prevGroupNumber) { internalGraph.putIfAbsent(prevItem, ArrayList()) internalGraph[prevItem]!!.add(i) internalInMap[i]++ } else { externalGraph.putIfAbsent(prevGroupNumber, ArrayList()) externalGraph[prevGroupNumber]!!.add(groupNumber) externalInMap[groupNumber]++ } } } } val externalQueue: Queue<Int> = LinkedList() for (i in 0 until totalGroups) { if (externalInMap[i] == 0) { externalQueue.offer(i) } } val res = IntArray(n) var resIndex = 0 while (externalQueue.isNotEmpty()) { val curGroup = externalQueue.poll() val internalQueue: Queue<Int> = LinkedList() if (indexGroupMap.containsKey(curGroup)) { for (item in indexGroupMap[curGroup]!!) { if (internalInMap[item] == 0) { internalQueue.offer(item) } } } while (internalQueue.isNotEmpty()) { val curItem = internalQueue.poll() res[resIndex] = curItem resIndex++ if (internalGraph.containsKey(curItem)) { for (nextItemInGroup in internalGraph[curItem]!!) { internalInMap[nextItemInGroup]-- if (internalInMap[nextItemInGroup] == 0) { internalQueue.offer(nextItemInGroup) } } } } if (externalGraph.containsKey(curGroup)) { for (nextGroup in externalGraph[curGroup]!!) { externalInMap[nextGroup]-- if (externalInMap[nextGroup] == 0) { externalQueue.offer(nextGroup) } } } } return if (resIndex == n) res else intArrayOf() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,578
LeetCode-in-Kotlin
MIT License
src/org/mjurisic/aoc2020/day12/Day12.kt
mjurisic
318,555,615
false
null
package org.mjurisic.aoc2020.day12 import java.io.File import kotlin.math.abs class Day12 { companion object { @JvmStatic fun main(args: Array<String>) = try { val ship = Ship(0, 0) val waypoint = Waypoint(10, -1) File(ClassLoader.getSystemResource("resources/input12.txt").file).forEachLine { val command = it.first() val value = it.substring(1, it.length).toInt() moveWaypointInDirection(command, waypoint, value) if (command == 'F') { moveShipForward(ship, waypoint, value) } else if (command == 'R' || command == 'L') { rotateWaypoint(command, ship, waypoint, value) } } val manhattan = abs(ship.x) + abs(ship.y) println(manhattan) } catch (e: Exception) { e.printStackTrace() } private fun moveShipForward(ship: Ship, waypoint: Waypoint, value: Int) { val dx = waypoint.x - ship.x val dy = waypoint.y - ship.y repeat(value) { ship.x += dx ship.y += dy } waypoint.x = ship.x + dx waypoint.y = ship.y + dy } private fun rotateWaypoint(direction: Char, ship: Ship, waypoint: Waypoint, value: Int) { val dx = waypoint.x - ship.x val dy = waypoint.y - ship.y if (direction == 'L' && value == 90 || direction == 'R' && value == 270) { waypoint.y = ship.y - dx waypoint.x = ship.x + dy } else if (direction == 'R' && value == 90 || direction == 'L' && value == 270) { waypoint.y = ship.y + dx waypoint.x = ship.x - dy } else if (value == 180) { waypoint.y = ship.y - dy waypoint.x = ship.x - dx } } private fun moveWaypointInDirection(dir: Char, waypoint: Waypoint, value: Int) { when (dir) { 'N' -> waypoint.y = waypoint.y - value 'S' -> waypoint.y = waypoint.y + value 'E' -> waypoint.x = waypoint.x + value 'W' -> waypoint.x = waypoint.x - value } } } } class Ship(var x: Int, var y: Int) { override fun toString(): String { return "Ship(x=$x, y=$y)" } } class Waypoint(var x: Int, var y: Int) { override fun toString(): String { return "Waypoint(x=$x, y=$y)" } }
0
Kotlin
0
0
9fabcd6f1daa35198aaf91084de3b5240e31b968
2,583
advent-of-code-2020
Apache License 2.0
src/main/kotlin/aoc2022/Day10.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import readInput fun main() { fun part1(input: List<String>): Int { var register = 1 var cycle = 1 var signalStrenght = 0 val calculateSignalStrengh = { if ((cycle - 20) % 40 == 0) { signalStrenght += register * cycle } } input.forEach { cycle++ calculateSignalStrengh() if (it != "noop") { val delta = it.split(" ").last().toInt() register += delta cycle++ calculateSignalStrengh() } } return signalStrenght } fun part2(input: List<String>) { var spritePosition = 0..2 var cycle = 1 var register = 1 val lines = Array((input.size * 2) / 40) { Array(40) { '.' } } val drawPixel = { val row = cycle / 40 val pixelPosition = (cycle - 1) % 40 if (pixelPosition in spritePosition) { lines[row][pixelPosition] = '#' } } input.forEach { drawPixel() cycle++ drawPixel() if (it != "noop") { val delta = it.split(" ").last().toInt() register += delta cycle++ spritePosition = register - 1..register + 1 } } for (line in lines) { println(line.joinToString("") { it.toString() }) } } val testInput = readInput("Day10_test", 2022) check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10", 2022) println(part1(input)) part2(input) // FZBPBFZF }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
1,713
adventOfCode
Apache License 2.0
src/main/kotlin/days/Day04.kt
poqueque
430,806,840
false
{"Kotlin": 101024}
package days import util.Coor class Day04 : Day(4) { override fun partOne(): Any { val data = inputList[0].split(",").map { it.toInt() }.toList() var i = 2 val boards = mutableListOf<MutableMap<Coor,Int>>() while (i<inputList.size) { val map = mutableMapOf<Coor,Int>() for (j in 0..4){ val n = inputList[i].split("[\\s]+".toRegex()).filter { it != ""} val nums = n.map{ it.toInt() }.toList() map[Coor(j,0)] = nums[0] map[Coor(j,1)] = nums[1] map[Coor(j,2)] = nums[2] map[Coor(j,3)] = nums[3] map[Coor(j,4)] = nums[4] i++ } i++ boards.add(map) } val appeared = mutableListOf<Int>() for (k in data.indices) { appeared.add(data[k]) for (b in boards) { //columns for (row in 0..4) { var a = 0 for (col in 0..4) { if (appeared.contains(b[Coor(row,col)])) a++ } if (a == 5) { var sum = 0 for (d in b.values) if (!appeared.contains(d)) sum += d println("Column found in $k steps") println(appeared) for (col in 0..4) print("${b[Coor(row,col)]} ") println() println(sum) println(appeared.last()) return sum * appeared.last() } } //rows for (col in 0..4) { var a = 0 for (row in 0..4) { if (appeared.contains(b[Coor(row,col)])) a++ } if (a == 5) { var sum = 0 for (d in b.values) if (!appeared.contains(d)) sum += d println("Row found in $k steps") for (row in 0..4) print("${b[Coor(row,col)]} ") println() return sum * appeared.last() } } } } return 0 } override fun partTwo(): Any { val data = inputList[0].split(",").map { it.toInt() }.toList() var i = 2 val boards = mutableListOf<MutableMap<Coor,Int>>() while (i<inputList.size) { val map = mutableMapOf<Coor,Int>() for (j in 0..4){ val n = inputList[i].split("[\\s]+".toRegex()).filter { it != ""} val nums = n.map{ it.toInt() }.toList() map[Coor(j,0)] = nums[0] map[Coor(j,1)] = nums[1] map[Coor(j,2)] = nums[2] map[Coor(j,3)] = nums[3] map[Coor(j,4)] = nums[4] i++ } i++ boards.add(map) } val appeared = mutableListOf<Int>() var score = 0 for (k in data.indices) { appeared.add(data[k]) for (b in boards.toList()) { //columns for (row in 0..4) { var a = 0 for (col in 0..4) { if (appeared.contains(b[Coor(row,col)])) a++ } if (a == 5) { var sum = 0 for (d in b.values) if (!appeared.contains(d)) sum += d println("Column found in $k steps") println(appeared) for (col in 0..4) print("${b[Coor(row,col)]} ") println() println(sum) println(appeared.last()) score = sum * appeared.last() boards.remove(b) } } //rows for (col in 0..4) { var a = 0 for (row in 0..4) { if (appeared.contains(b[Coor(row,col)])) a++ } if (a == 5) { var sum = 0 for (d in b.values) if (!appeared.contains(d)) sum += d println("Row found in $k steps") for (row in 0..4) print("${b[Coor(row,col)]} ") println() score = sum * appeared.last() boards.remove(b) } } } } return score } }
0
Kotlin
0
0
4fa363be46ca5cfcfb271a37564af15233f2a141
5,008
adventofcode2021
MIT License
src/day22/d22_1.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
import java.util.TreeSet val initMana = 500 val initHp = 50 val missileMana = 53 val missileDmg = 4 val drainMana = 73 val drainDelta = 2 val shieldMana = 113 val shieldTurns = 6 val shieldArmor = 7 val poisonMana = 173 val poisonTurns = 6 val poisonDmg = 3 val rechargeMana = 229 val rechargeTurns = 5 val rechargeRegen = 101 fun main() { val input = "" val bossStats = input.lines().map { it.split(" ").last().toInt() }.let { it[0] to it[1] } val initState = State(initHp, initMana, bossStats.first, bossStats.second, 0, 0, 0).also { it.label = "Initial state" } val queue = TreeSet<State>() queue.add(initState) while (!queue.isEmpty()) { val state = queue.pollFirst() if (state.bossHp <= 0) { println(state.manaSpent) break } if (state.mana >= missileMana) { enqueue(state.action("Magic Missile", manaD = -missileMana, bossHpD = -missileDmg), queue) } if (state.mana >= drainMana) { enqueue(state.action("Drain", hpD = drainDelta, manaD = -drainMana, bossHpD = -drainDelta), queue) } if (state.shieldTimer == 0 && state.mana >= shieldMana) { enqueue(state.action("Shield", manaD = -shieldMana, shieldTimerD = shieldTurns), queue) } if (state.poisonTimer == 0 && state.mana >= poisonMana) { enqueue(state.action("Poison", manaD = -poisonMana, poisonTimerD = poisonTurns), queue) } if (state.rechargeTimer == 0 && state.mana >= rechargeMana) { enqueue(state.action("Recharge", manaD = -rechargeMana, rechargeTimerD = rechargeTurns), queue) } } } fun enqueue(newState: State?, queue: TreeSet<State>) { if (newState != null) { val prevQueued = queue.lower(newState) if (prevQueued == null || prevQueued != newState || prevQueued.manaSpent > newState.manaSpent) { queue.remove(newState) queue.add(newState) } } } data class State(val hp: Int, val mana: Int, val bossHp: Int, val bossDmg: Int, val shieldTimer: Int, val poisonTimer: Int, val rechargeTimer: Int): Comparable<State> { var manaSpent = 0 var label: String = "" var parent: State? = null override fun compareTo(other: State): Int = manaSpent.compareTo(other.manaSpent) fun action(label: String, hpD: Int = 0, manaD: Int = 0, bossHpD: Int = 0, shieldTimerD: Int = 0, poisonTimerD: Int = 0, rechargeTimerD: Int = 0): State? { // apply action var newHp = hp + hpD if (newHp <= 0) return null var newMana = mana + manaD var newBossHp = bossHp + bossHpD if (newBossHp <= 0) return copy(bossHp = 0).initialize(label, manaD, this) // apply effects var newShieldTimer = shieldTimer + shieldTimerD val shield = if (newShieldTimer-- > 0) shieldArmor else 0 var newPoisonTimer = poisonTimer + poisonTimerD newBossHp -= if (newPoisonTimer-- > 0) poisonDmg else 0 if (newBossHp <= 0) return copy(bossHp = 0).initialize(label, manaD, this) var newRechargeTimer = rechargeTimer + rechargeTimerD newMana += if (newRechargeTimer-- > 0) rechargeRegen else 0 // apply boss move newHp -= Math.max(bossDmg - shield, 0) if (newHp <= 0) return null // apply effects newShieldTimer-- newBossHp -= if (newPoisonTimer-- > 0) poisonDmg else 0 if (newBossHp <= 0) return copy(bossHp = 0).initialize(label, manaD, this) newMana += if (newRechargeTimer-- > 0) rechargeRegen else 0 return State(newHp, newMana, newBossHp, bossDmg, Math.max(newShieldTimer, 0), Math.max(newPoisonTimer, 0), Math.max(newRechargeTimer, 0)).initialize(label, manaD, this) } fun initialize(label: String, manaDelta: Int, parent: State): State { this.label = label this.manaSpent = parent.manaSpent - manaDelta this.parent = parent return this } fun toStringWithMetadata(): String = "[$label @$manaSpent] ${toString()}" fun formatPath(): String = parent.let { if (it == null) toStringWithMetadata() else it.formatPath() + " -> " + toStringWithMetadata() } }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
4,385
aoc2015
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[387]字符串中的第一个唯一字符.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 // // // // 示例: // // s = "leetcode" //返回 0 // //s = "loveleetcode" //返回 2 // // // // // 提示:你可以假定该字符串只包含小写字母。 // Related Topics 哈希表 字符串 // 👍 332 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun firstUniqChar(s: String): Int { if(s.isEmpty()) return -1 //使用 HashMap 保存每个字符个数 val map = HashMap<Char,Int>() for (i in s.indices){ if (map.containsKey(s[i])){ map[s[i]] = map[s[i]]!!+1 }else{ map[s[i]] = 1 } } var res = -1 for (i in s.indices){ if (map[s[i]]!! < 2){ res = i break } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,041
MyLeetCode
Apache License 2.0
Lab 5/src/main/kotlin/QuickHull.kt
knu-3-tochanenko
273,874,096
false
null
import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 class QuickHull { companion object { private var result = mutableListOf<Dot>() fun calculate(dots: List<Dot>): List<Dot> { assert(dots.size > 2) var minX = 0 var maxX = 0 // Find most left and right dots for (i in dots.indices) { if (dots[i].x < dots[minX].x) minX = i if (dots[i].x > dots[maxX].x) maxX = i } quickHull(dots, Line(dots[minX], dots[maxX]), 1) quickHull(dots, Line(dots[minX], dots[maxX]), -1) sortByAngle() return result } private fun quickHull(dots: List<Dot>, line: Line, side: Int) { val furthest = furthestDotIndex(dots, line, side) if (furthest == -1) { result.add(line.start) result.add(line.end) return } quickHull( dots, Line(dots[furthest], line.start), -side(Line(dots[furthest], line.start), line.end) ) quickHull( dots, Line(dots[furthest], line.end), -side(Line(dots[furthest], line.end), line.start) ) } private fun furthestDotIndex(dots: List<Dot>, line: Line, side: Int): Int { var furthest = -1 var maxDistance = 0.0 for (i in dots.indices) { val temp = dotToLineDistance(line, dots[i]) if (side(line, dots[i]) == side && temp > maxDistance) { furthest = i maxDistance = temp } } return furthest } private fun side(line: Line, dot: Dot): Int { val sub = (dot.y - line.start.y) * (line.end.x - line.start.x) - (line.end.y - line.start.y) * (dot.x - line.start.x) return when { sub == 0.0 -> 0 sub > 0 -> 1 else -> -1 } } private fun dotToLineDistance(line: Line, dot: Dot): Double { return abs( (dot.y - line.start.y) * (line.end.x - line.start.x) - (line.end.y - line.start.y) * (dot.x - line.start.x) ) } private fun sortByAngle() { val center = Dot(0.0, 0.0) for (dot in result) { center.x += dot.x / result.size center.y += dot.y / result.size } result.map { it.angle = atan2(it.y - center.y, it.x - center.x) * 180 / PI } result.sortBy { it.angle } result.add(result[0]) } } }
0
Kotlin
0
0
d33c5e03ccec496ffa6400c7824780886a46b1ba
2,855
ComputerGraphics
MIT License
src/main/kotlin/io/github/carlomicieli/data/Fraction.kt
CarloMicieli
92,217,015
false
null
/* * Copyright 2017 <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 io.github.carlomicieli.data /** * A number that can be represented in the form a/b, where a and b are * both Int and b is not zero. * * @author <NAME> * @since 1.0.0 */ class Fraction(n: Int, d: Int) { /** * The numerator value */ val numerator: Int /** * The denominator value */ val denominator: Int init { require (d != 0) { "Denominator must be != 0" } val g = gcd(n, d) this.numerator = Math.abs(n / g) * sign(n, d) this.denominator = Math.abs(d / g) } private fun sign(n: Int, d: Int) = if (n < 0 || d < 0) -1 else 1 /** * A new [Fraction] for a whole number. * @param n the numerator value */ constructor(n: Int) : this(n, 1) /** * Sum two [Fraction] values * @param that the second fraction value * @return their sum */ operator fun plus(that: Fraction): Fraction { val (a, b) = this val (c, d) = that return Fraction(a * d + c * b, b * d) } operator fun unaryMinus(): Fraction = Fraction(-numerator, denominator) /** * Difference between two fractions */ operator fun minus(that: Fraction): Fraction = this + (-that) operator fun times(that: Fraction): Fraction { val (a, b) = this val (c, d) = that return Fraction(a * c, b * d) } operator fun div(that: Fraction): Fraction { require (that.numerator != 0) { "Numerator for the second fraction must be != 0" } val (a, b) = this val (c, d) = that return Fraction(a * d, b * c) } infix fun max(other: Fraction) = if (this > other) this else other infix fun min(other: Fraction) = if (this > other) other else this operator fun component1(): Int = numerator operator fun component2(): Int = denominator operator fun compareTo(that: Fraction): Int { if (this == that) return 0 val (a, b) = this val (c, d) = that if (a * d > c * b) return 1 else return -1 } override fun equals(other: Any?): Boolean = when (other) { is Fraction -> areEquals(this, other) else -> false } override fun toString(): String { return "$numerator/$denominator" } private fun areEquals(f1: Fraction, f2: Fraction) = f1.numerator == f2.numerator && f1.denominator == f2.denominator } // Greatest common divisor (https://en.wikipedia.org/wiki/Euclidean_algorithm) tailrec fun gcd(x: Int, y: Int): Int { if (y == 0) return x else { return gcd(y, Math.floorMod(x, y)) } } val Int.fr: Fraction get() = Fraction(this, 1)
0
Kotlin
0
0
339d19062be2ea7b062b76e9a14ba63badd56413
3,327
the-wrath-of-kotlin
Apache License 2.0
fd-applet-server/src/main/kotlin/io/github/haruhisa_enomoto/backend/utils/ListWithLeq.kt
haruhisa-enomoto
628,298,470
false
null
package io.github.haruhisa_enomoto.backend.utils import io.github.haruhisa_enomoto.backend.quiver.Arrow import io.github.haruhisa_enomoto.backend.quiver.Quiver /** * A data class representing a list of elements and a binary relation [leqs], denoted as `<=`. * * @param T The type for elements. * @property elements The list of elements. * @property leqs The binary relation represented as `Set<Pair<T, T>>`. * For example, if `a to b in leq`, it is interpreted as `a <= b`. */ data class ListWithLeq<T>( val elements: List<T>, val leqs: Set<Pair<T, T>>, val alwaysPoset: Boolean = true ) : List<T> by elements { fun leq(x: T, y: T): Boolean { return x to y in leqs } fun geq(x: T, y: T): Boolean { return y to x in leqs } /** * Returns the set of elements <= [x]. */ fun down(x: T): List<T> { require(x in elements) return elements.filter { leq(it, x) } } /** * Returns the set of elements <= [x]. */ fun up(x: T): List<T> { require(x in elements) return elements.filter { geq(it, x) } } /** * Returns whether this order gives a poset structure: * reflexive, transitive, and antisymmetric. */ fun isPoset(): Boolean { for (x in elements) { if (!leq(x, x)) return false for (y in down(x)) {// y <= x if (leq(x, y) && x != y) return false for (z in down(y)) {// z <= y if (!leq(z, x)) { return false } } } } return true } /** * Returns the Hasse quiver of the order: * Vertices are [elements], * and draw `x -> y` if x > y and there is no z with x > z > y. * This method does not check that the order is a poset if [alwaysPoset] is true. */ fun hasseQuiver(): Quiver<T, Nothing> { require(alwaysPoset || isPoset()) { "This is not a poset!" } val arrows = mutableListOf<Arrow<T, Nothing>>() for (x in elements) { for (y in down(x)) {// y <= x if (x === y) continue // y < x val mid = elements.filter { leq(y, it) && leq(it, x) } if (mid.size != 2) continue arrows.add(Arrow(null, x, y)) } } return Quiver(elements, arrows) } } fun <T, U : Collection<T>> List<U>.toListWithLeq(): ListWithLeq<U> { val leqs = this.flatMap { c1 -> this.filter { c2 -> c2.containsAll(c1) }.map { c2 -> c1 to c2 } }.toSet() return ListWithLeq(this, leqs) }
0
Kotlin
0
0
8ec1afe14e9f0d6330d02652c1cd782a68fca5db
2,652
fd-applet
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/GetDescentPeriods.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 /** * 2110. Number of Smooth Descent Periods of a Stock * @see <a href="https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/">Source</a> */ fun interface GetDescentPeriods { operator fun invoke(prices: IntArray): Long } /** * O(N) Space */ class GetDescentPeriodsOnePass : GetDescentPeriods { override operator fun invoke(prices: IntArray): Long { val dp = LongArray(prices.size) dp[0] = 1 var ans: Long = 1 for (i in 1 until prices.size) { if (prices[i] == prices[i - 1] - 1) { dp[i] = dp[i - 1] + 1 } else { dp[i] = 1 } ans += dp[i] } return ans } } /** * O(1) Space */ class GetDescentPeriodsSimple : GetDescentPeriods { override operator fun invoke(prices: IntArray): Long { var dp: Long = 1 var ans: Long = 1 for (i in 1 until prices.size) { if (prices[i] == prices[i - 1] - 1) { dp++ } else { dp = 1 } ans += dp } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,776
kotlab
Apache License 2.0
src/Day09.kt
JohannaGudmandsen
573,090,573
false
{"Kotlin": 19316}
import java.io.File import kotlin.collections.* class Position(var X:Int, var Y:Int) fun moveTail(head:Position, tail:Position){ if (head.X > tail.X + 1){ tail.X++ if (head.Y > tail.Y){ tail.Y++ } else if (head.Y < tail.Y){ tail.Y-- } } else if (head.X < tail.X - 1){ tail.X-- if (head.Y > tail.Y){ tail.Y++ } else if (head.Y < tail.Y){ tail.Y-- } } else if (head.Y > tail.Y + 1){ tail.Y++ if (head.X > tail.X){ tail.X++ } else if (head.X < tail.X){ tail.X-- } } else if (head.Y < tail.Y - 1 ){ tail.Y-- if (head.X > tail.X){ tail.X++ } else if (head.X < tail.X){ tail.X-- } } } fun Day09() { val input = File("src/input/day09.txt").readLines() var head = Position(500,500) var tailTask1 = Position(500,500) var tailsTask2 = ArrayList<Position>() tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) var visitedPositionsTask1 = ArrayList<String>() var visitedPositionsTask2 = ArrayList<String>() for(line in input){ var instruction = line.split(" ") var direction = instruction[0] var times = instruction[1].toInt() for(i in 0..times-1 step 1){ if (direction == "R"){ head.X++ } else if (direction == "L"){ head.X-- } else if (direction == "U"){ head.Y++ } else { // "D" head.Y-- } moveTail(head, tailTask1) visitedPositionsTask1.add(tailTask1.X.toString() + tailTask1.Y.toString()) var prevTail = head for(tailTask2 in tailsTask2){ moveTail(prevTail, tailTask2) prevTail = tailTask2 } visitedPositionsTask2.add(tailsTask2.last().X.toString() + tailsTask2.last().Y.toString()) } } var task1 = visitedPositionsTask1.distinct().count() var task2 = visitedPositionsTask2.distinct().count() println("Day 9 Task 1: $task1") // 6563 println("Day 9 Task 2: $task2") // 2653 }
0
Kotlin
0
1
21daaa4415bd20c14d67132e615971519211ab16
2,723
aoc-2022
Apache License 2.0
year2020/src/main/kotlin/net/olegg/aoc/year2020/day8/Day8.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2020.day8 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2020.DayOf2020 /** * See [Year 2020, Day 8](https://adventofcode.com/2020/day/8) */ object Day8 : DayOf2020(8) { override fun first(): Any? { val program = lines .map { it.split(" ").toPair() } .map { it.first to it.second.toInt() } var position = 0 var acc = 0 val visited = mutableSetOf<Int>() while (position !in visited) { visited += position val (op, add) = program[position] when (op) { "nop" -> position++ "acc" -> { acc += add position++ } "jmp" -> position += add } } return acc } override fun second(): Any? { val program = lines .map { it.split(" ").toPair() } .map { it.first to it.second.toInt() } program.forEachIndexed { line, (op, add) -> if (op != "acc") { val newOp = if (op == "jmp") "nop" else "jmp" val newPair = newOp to add val newProgram = program.mapIndexed { index, pair -> if (index == line) newPair else pair } var position = 0 var acc = 0 val visited = mutableSetOf<Int>() while (position !in visited && position in newProgram.indices) { visited += position val (currOp, currAdd) = newProgram[position] when (currOp) { "nop" -> position++ "acc" -> { acc += currAdd position++ } "jmp" -> position += currAdd } } if (position !in newProgram.indices) { return acc } } } return 0 } } fun main() = SomeDay.mainify(Day8)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,758
adventofcode
MIT License
src/main/kotlin/Problem19.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
/** * You are given the following information, but you may prefer to do some research for yourself. * - 1 Jan 1900 was a Monday. * - Thirty days has September, * April, June and November. * All the rest have thirty-one, * Saving February alone, * Which has twenty-eight, rain or shine. * And on leap years, twenty-nine. * - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. * How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? * * https://projecteuler.net/problem=19 */ fun main() { println( countMondaysFirstOfMonth( MyDate(day = 1, month = 1, year = 1901), MyDate(day = 31, month = 12, year = 2000) ) ) } fun countMondaysFirstOfMonth(from: MyDate, to: MyDate): Int { var date = MyDate(day = 31, month = 12, year = 1899) var count = 0 while (date <= to) { if (date >= from && date.day == 1) { count++ } date = date.nextSunday() } return count } private fun MyDate.nextSunday(): MyDate { var nextDay = day + 7 var nextMonth = month var nextYear = year if (nextDay > daysOfMonth[month]) { nextDay %= daysOfMonth[month] nextMonth++ if (nextMonth > 12) { nextMonth = 1 nextYear++ updateLeapYear(nextYear) } } return MyDate(nextDay, nextMonth, nextYear) } private fun updateLeapYear(year: Int) { val days = when { year % 400 == 0 -> 29 year % 100 == 0 -> 28 year % 4 == 0 -> 29 else -> 28 } daysOfMonth[2] = days } data class MyDate(val day: Int, val month: Int, val year: Int) private operator fun MyDate.compareTo(other: MyDate): Int { val y = year.compareTo(other.year) if (y != 0) { return y } val m = month.compareTo(other.month) if (m != 0) { return m } return day.compareTo(other.day) } private val daysOfMonth = arrayOf( 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, )
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
2,155
project-euler
MIT License
src/main/kotlin/kr/co/programmers/P67256.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import kotlin.math.abs // https://programmers.co.kr/learn/courses/30/lessons/67256 class P67256 { fun solution(numbers: IntArray, hand: String): String { var answer = "" val prev = arrayOf(intArrayOf(3, 0), intArrayOf(3, 2)) // 초기 위치 for (n in numbers) { // 키패드 -> 인덱스 var idx = n - 1 if (idx == -1) idx = 10 // 인덱스 -> 2차원 배열 val p = intArrayOf(idx / 3, idx % 3) if (p[1] == 0) { // 왼손 answer += "L" prev[0] = p } else if (p[1] == 2) { // 오른손 answer += "R" prev[1] = p } else { // 왼손으로부터의 거리 val diffLeft = abs(prev[0][0] - p[0]) + abs(prev[0][1] - p[1]) // 오른손으로부터의 거리 val diffRight = abs(prev[1][0] - p[0]) + abs(prev[1][1] - p[1]) if (diffLeft < diffRight) { answer += "L" prev[0] = p } else if (diffLeft > diffRight) { answer += "R" prev[1] = p } else { if (hand == "left") { answer += "L" prev[0] = p } else { answer += "R" prev[1] = p } } } } return answer } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,561
algorithm
MIT License
src/test/kotlin/org/nield/kotlinstatistics/DoubleStatisticsTest.kt
thomasnield
84,361,977
false
null
package org.nield.kotlinstatistics import org.junit.Assert import org.junit.Test class DoubleStatisticsTest { val doubleVector = sequenceOf(0.0, 1.0, 3.0, 5.0, 11.0) val groups = sequenceOf("A", "B","B","C", "C") @Test fun sumBy() { val r = mapOf("A" to 0.0, "B" to 4.0, "C" to 16.0) groups.zip(doubleVector).sumBy().let { Assert.assertTrue(it["A"] == r["A"] && it["B"] == r["B"] && it["C"] == r["C"]) } groups.zip(doubleVector).sumBy( keySelector = {it.first}, doubleSelector = {it.second} ).let { Assert.assertTrue(it["A"] == r["A"] && it["B"] == r["B"]) } } @Test fun averageBy() { val r = mapOf("A" to 0.0, "B" to 2.0, "C" to 8.0) groups.zip(doubleVector).averageBy( keySelector = {it.first}, doubleSelector = {it.second} ).let { Assert.assertTrue(it == r ) } } @Test fun binTest() { val binned = sequenceOf( doubleVector, doubleVector.map { it + 100.0 }, doubleVector.map { it + 200.0 } ).flatMap { it } .zip(groups.repeat()) .binByDouble( binSize = 100.0, valueSelector = {it.first}, rangeStart = 0.0 ) Assert.assertTrue(binned.bins.size == 3) println(binned.bins) Assert.assertTrue(binned[5.0]!!.range.let { it.lowerBound == 0.0 && it.upperBound == 100.0 }) Assert.assertTrue(binned[105.0]!!.range.let { it.lowerBound == 100.0 && it.upperBound == 200.0 }) Assert.assertTrue(binned[205.0]!!.range.let { it.lowerBound == 200.0 && it.upperBound == 300.0 }) } private fun <T> Sequence<T>.repeat() : Sequence<T> = sequence { while(true) yieldAll(this@repeat) } }
15
Kotlin
48
840
17f64bae2a3cea2e85f05c08172d19a290561e3b
1,879
kotlin-statistics
Apache License 2.0
code/day_12/src/jvm8Main/kotlin/task2.kt
dhakehurst
725,945,024
false
{"Kotlin": 105846}
package day_12 import korlibs.io.lang.substr import kotlin.math.min class BitString( val value: ULong ) : Iterable<Boolean> { val groups: List<Int> by lazy { val g = mutableListOf<Int>() var grp = 0 for (b in this.reversed()) { if (b) { grp++ } else { if (0 != grp) g.add(grp) grp = 0 } } if (0 != grp) g.add(grp) g } fun setBit(n: Int): BitString = BitString(value or 2UL.pow(n)) fun get(n: Int): Boolean = (value and 2UL.pow(n)) != 0UL fun matchesOr(other: BitString) = (this.value or other.value) == this.value fun matchesInvOr(other: BitString) = (this.value.inv() or other.value) == this.value.inv() override fun iterator(): Iterator<Boolean> = object : AbstractIterator<Boolean>() { var v = value override fun computeNext() { when { 0UL == v -> done() else -> { setNext((v and 1UL) == 1UL) v = v.shr(1) } } } } override fun hashCode(): Int = value.hashCode() override fun equals(other: Any?): Boolean = when { other !is BitString -> false this.value != other.value -> false else -> true } override fun toString(): String = value.toString(2) } val List<Int>.toBitString get() = BitString(this.foldIndexed(0UL) { x, a, i -> when (i) { 0 -> a.shl(1) else -> a.shl(1).inc() } }) fun genStr(opt: List<Int>, groups: List<Int>): String { var str = ".".repeat(opt[0]) for (i in 0 until groups.size - 1) { val grpLen = groups[i] val optLen = opt[i + 1] str += "#".repeat(grpLen) + ".".repeat(optLen + 1) } return str + "#".repeat(groups.last()) + ".".repeat(opt.last()) } fun genLong(opt: List<Int>, groups: List<Int>): ULong { var v = 0UL//".".repeat(opt[0]) for (i in 0 until groups.size - 1) { val grpLen = groups[i] val optLen = opt[i + 1] val grpVal = 2UL.pow(grpLen) - 1u //"#".repeat(groups[i]) val shGrpVal = grpVal.shl(optLen + 1) //".".repeat(opt[i + 1]+1) v = v.shl(grpLen + optLen + 1) v += shGrpVal } v = v.shl(groups.last()) v += 2UL.pow(groups.last()) - 1u v = v.shl(opt.last()) return v } fun distribute(balls: Int, boxes: Int, distribution: List<Int> = emptyList()): List<List<Int>> { return if (boxes == 1) { println((distribution + balls).joinToString()) listOf(distribution + balls) } else { val result = mutableListOf<List<Int>>() for (i in 0..min(1, balls)) { result += distribute(balls - i, boxes - 1, distribution + i) } result } } data class PatternAsLongs( val str: String, val groups: List<Int>, val expect: Expect ) { val hashes = BitString(str.asBinaryULong("#")) val dots = BitString(str.asBinaryULong(".")) val blanks = BitString(str.asBinaryULong("?")) fun matches(other: BitString) = other.matchesOr(hashes) && other.matchesInvOr(dots) && other.groups == groups fun fillBlanksWith(dist: BitString): BitString { var filled = BitString(hashes.value) var d = 0 blanks.forEachIndexed { x, i -> if (i) { if (dist.get(d)) { filled = BitString(filled.value or 2UL.pow(x)) } else { // } d++ } else { // } } return filled } } data class CacheKey( val c1: String, val c2: List<Int>, val c3:Expect ) val cache3 = mutableMapOf<CacheKey, Long>() fun submatch(str: String, wanted: List<Int>): Long { val curGrps = BitString(str.asBinaryULong("#")).groups return if (curGrps == wanted) 1 else 0 } fun dgroupDiff(gMain: List<Int>, grp: Int?): List<Int> { return when { gMain.isEmpty() -> gMain 0 == gMain.first() -> gMain.drop(1) else -> gMain } } fun hgroupDiff(gMain: List<Int>, grp: Int?): List<Int> { return when { null == grp -> gMain gMain.isEmpty() -> gMain //grp == gMain.first() -> gMain.drop(1) else -> { val gf = gMain.first() listOf(gf - 1) + gMain.drop(1) } } } fun countMatchDistribute3(start: Int, pattern: PatternAsLongs, balls: Int, boxes: Int): Long { val key = CacheKey(pattern.str, pattern.groups, pattern.expect) val cached = cache3[key] return if (null == cached) { val v = when { pattern.str.length == 0 -> when { 0 == pattern.groups.sum() -> 1L else -> 0L } 0 == boxes -> { val ch = pattern.str[0] val ng = when (ch) { '.' -> dgroupDiff(pattern.groups, 1) '#' -> pattern.groups else -> error("") } submatch(pattern.str, ng) } pattern.groups.isEmpty() -> { submatch(pattern.str, emptyList()) } // 0 == balls -> when { // 0 == pattern.groups.sum() -> 1L // else -> 0L // } else -> { val ch = pattern.str[0] val rhs = pattern.str.substr(1) when (ch) { '.' -> when { pattern.expect == Expect.HASH -> 0L else -> { val ng = dgroupDiff(pattern.groups, 1) val nx = when { else -> Expect.ANY } countMatchDistribute3(start + 1, PatternAsLongs(rhs, ng, nx), balls, boxes) } } '#' -> when { pattern.expect == Expect.DOT -> 0L pattern.groups.first() == 0 -> 0L //end of group should be a'.' else -> { val ng = hgroupDiff(pattern.groups, 1) val nx = when { pattern.groups.first()==1 -> Expect.DOT else -> Expect.HASH } countMatchDistribute3(start + 1, PatternAsLongs(rhs, ng, nx), balls, boxes) } } '?' -> { var count = 0L // first try '.' val dc = when { pattern.expect == Expect.HASH -> 0L else -> { val dgroupsDiff = dgroupDiff(pattern.groups, 1) val nx = when { else -> Expect.ANY } countMatchDistribute3(start + 1, PatternAsLongs(rhs, dgroupsDiff, nx), balls, boxes - 1) } } count += dc // then '#' val hc = when { pattern.expect == Expect.DOT -> 0L pattern.groups.first() == 0 -> 0L else -> { val ng = hgroupDiff(pattern.groups, 1) val nx = when { pattern.groups.first()==1 -> Expect.DOT else -> Expect.HASH } countMatchDistribute3(start + 1, PatternAsLongs(rhs, ng, nx), balls - 1, boxes - 1) } } count += hc count } else -> error("") } } } cache3[key] = v v } else { cached } } enum class Expect { ANY, DOT, HASH } fun countMatchesHashesIntoGaps(groups: List<Int>, record: String): Long { val gaps = record.count { it == '?' } val neededHashes = groups.sum() - record.count { it == '#' } // println("$record, $groups") // println("len: ${record.length}") // println("groups: ${groups.size}") // println("neededHashes: $neededHashes into: $gaps") val p = PatternAsLongs(record, groups, Expect.ANY) cache3.clear() //distribute( neededHashes, gaps) val count = countMatchDistribute3(0, p, neededHashes, gaps) return count } val memo = mutableMapOf<Pair<Int, Int>, ULong>() fun combination(n: Int, m: Int): ULong { if (m == 0 || m == n) return 1u if (m == 1) return n.toULong() if (memo.containsKey(Pair(n, m))) { return memo[Pair(n, m)]!! } val result = combination(n - 1, m - 1) + combination(n - 1, m) memo[Pair(n, m)] = result return result } fun task2(lines: List<String>): Long { var total = 0L //distribute(2,3) for (line in lines) { val record = line.substringBefore(" ") val record2 = "$record?$record?$record?$record?$record" val groupSizes = line.substringAfter(" ").split(",").map { it.trim().toInt() } val groupSizes2 = groupSizes + groupSizes + groupSizes + groupSizes + groupSizes //val regEx = toRegEx(groupSizes2) //val alternativeCount = countMatchesOptionsFromGroups(groupSizes2, record2) val alternativeCount = countMatchesHashesIntoGaps(groupSizes2, record2) //println("ways: $alternativeCount") total += alternativeCount } return total }
0
Kotlin
0
0
be416bd89ac375d49649e7fce68c074f8c4e912e
9,909
advent-of-code
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[628]三个数的最大乘积.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.math.max //给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 // // 示例 1: // // //输入: [1,2,3] //输出: 6 // // // 示例 2: // // //输入: [1,2,3,4] //输出: 24 // // // 注意: // // // 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。 // 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。 // // Related Topics 数组 数学 // 👍 261 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun maximumProduct(nums: IntArray): Int { //如果数组中全是非负数,则排序后最大的三个数相乘即为最大乘积;如果全是非正数,则最大的三个数相乘同样也为最大乘积。 //如果数组中有正数有负数,则最大乘积既可能是三个最大正数的乘积,也可能是两个最小负数(即绝对值最大)与最大正数的乘积。 //线性扫描得出最大 第二段 第三大 最小 第二小的数 // //排序 时间复杂度 O(nlogn) // Arrays.sort(nums) // val len = nums.size // return Math.max(nums[len-1]*nums[len-2]*nums[len-3],nums[0]*nums[1]*nums[len-1]) //方法二 线性扫描 // 最小的和第二小的 var min1 = Int.MAX_VALUE var min2 = Int.MAX_VALUE // 最大的、第二大的和第三大的 var max1 = Int.MIN_VALUE var max2 = Int.MIN_VALUE var max3 = Int.MIN_VALUE nums.forEach { //找最小和第二小 if(it < min1){ min2 = min1 min1 = it }else if(it < min2){ min2 = it } if(it > max1){ max3 = max2 max2 = max1 max1 = it }else if (it > max2){ max3 = max2 max2 = it }else if(it > max3){ max3 = it } } return Math.max(max1*max2*max3,min1*min2*max1) } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,222
MyLeetCode
Apache License 2.0
src/Day01.kt
woainikk
572,944,262
false
{"Kotlin": 1515}
fun main() { fun calculateSnacks(input: List<String>): MutableList<Int>{ val reindeers: MutableList<Int> = mutableListOf() var sum = 0 for (i in input) { if(i.isEmpty()){ reindeers.add(sum) sum = 0 continue } else{ sum += i.toInt() } } return reindeers } fun part1(input: List<String>): Int { return calculateSnacks(input).max() } fun part2(input: List<String>): Int { return calculateSnacks(input).sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc06fb37a78d929308d61f562e2003696cad0305
874
adventOfCode
Apache License 2.0
src/main/java/it/smartphonecombo/uecapabilityparser/query/ComboValue.kt
HandyMenny
539,436,833
false
{"Kotlin": 572976, "Dockerfile": 1718, "CSS": 45, "JavaScript": 19}
package it.smartphonecombo.uecapabilityparser.query import it.smartphonecombo.uecapabilityparser.io.IOUtils.echoSafe import it.smartphonecombo.uecapabilityparser.model.combo.ICombo import it.smartphonecombo.uecapabilityparser.model.component.IComponent import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed interface IComboValue { fun matches(combo: ICombo): Boolean fun matchesAny(list: List<ICombo>): Boolean = list.any { matches(it) } } @Serializable @SerialName("simple") data class ComboValue( @SerialName("dl") val dlComponents: List<IComponentValue>, @SerialName("ul") val ulComponents: List<IComponentValue> ) : IComboValue { override fun matches(combo: ICombo): Boolean { val components = combo.masterComponents val res = componentsCheck(components, dlComponents, ulComponents) if (res) echoSafe("Matched: " + combo.toCompactStr()) return res } } @Serializable @SerialName("mrdc") data class ComboMrDcValue( @SerialName("dlMaster") val dlMasterComponents: List<IComponentValue>, @SerialName("ulMaster") val ulMasterComponents: List<IComponentValue>, @SerialName("dlSecondary") val dlSecondaryComponents: List<IComponentValue>, @SerialName("ulSecondary") val ulSecondaryComponents: List<IComponentValue> ) : IComboValue { override fun matches(combo: ICombo): Boolean { val masterComponents = combo.masterComponents val secondaryComponents = combo.secondaryComponents val res = componentsCheck(masterComponents, dlMasterComponents, ulMasterComponents) && componentsCheck(secondaryComponents, dlSecondaryComponents, ulSecondaryComponents) if (res) echoSafe("Matched: " + combo.toCompactStr()) return res } } internal fun componentsCheck( components: List<IComponent>, dlCriteria: List<IComponentValue>, ulCriteria: List<IComponentValue> ): Boolean { return if (components.size < ulCriteria.size || components.size < dlCriteria.size) { false } else { meetsCriteriaReduced(ulCriteria, components) && meetsCriteriaReduced(dlCriteria, components) } } internal fun meetsCriteriaReduced( criteria: List<IComponentValue>, components: List<IComponent> ): Boolean { val indexes = criteria.map { val res = it.allIndexes(components) if (res.isEmpty()) return false res } return reducedResult(indexes) } // Return true if all sublist have at least one unique value. // To maximize lists that have unique values, this function eliminates duplicates (values that // appears in // multiple sub-lists) using a greedy-like algorithm. internal fun reducedResult(list: List<List<Int>>): Boolean { val allValues = list.flatten() val distinctValues = allValues.distinct() // Simple case val simpleCase = when { // Empty input list.isEmpty() -> true // At least one sublist is empty list.any { it.isEmpty() } -> false // No duplicate case allValues.size == distinctValues.size -> distinctValues.size >= list.size // Not enough distinct values case distinctValues.size < list.size -> false else -> null } if (simpleCase != null) return simpleCase // - General -- expensive -- case // Add a weight to each value. weight = number of sub-lists containing that value val valueWeights = distinctValues.associateWith { index -> list.count { it.contains(index) } } // List sorted by sum of all weights val sortedList = list.sortedBy { subList -> subList.sumOf { value -> valueWeights[value]!! } } // store values already taken val valuesTaken = mutableSetOf<Int>() for (subList in sortedList) { val int = subList.subtract(valuesTaken).minByOrNull { valueWeights[it]!! } // found an empty sublist if (int == null) break valuesTaken.add(int) } return valuesTaken.size == list.size }
2
Kotlin
8
13
30c02e3eb8c36beb5aca6c6683286170caf33841
4,095
uecapabilityparser
MIT License
src/leetcodeProblem/leetcode/editor/en/ReverseLinkedList.kt
faniabdullah
382,893,751
false
null
//Given the head of a singly linked list, reverse the list, and return the //reversed list. // // // Example 1: // // //Input: head = [1,2,3,4,5] //Output: [5,4,3,2,1] // // // Example 2: // // //Input: head = [1,2] //Output: [2,1] // // // Example 3: // // //Input: head = [] //Output: [] // // // // Constraints: // // // The number of nodes in the list is the range [0, 5000]. // -5000 <= Node.val <= 5000 // // // // Follow up: A linked list can be reversed either iteratively or recursively. //Could you implement both? // Related Topics Linked List Recursion 👍 8776 👎 153 package leetcodeProblem.leetcode.editor.en import leetcode_study_badge.data_structure.ListNode class ReverseLinkedList { fun solution() { } //below code is used to auto submit to leetcode.com (using ide plugin) //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 reverseList(head: ListNode?): ListNode? { if (head == null) return head return recurReverseList(head, null) } private fun recurReverseList(p: ListNode?, l: ListNode?): ListNode? { if (p == null) return l val n = p.next p.next = l return recurReverseList(n, p) } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,603
dsa-kotlin
MIT License
src/main/kotlin/me/peckb/aoc/_2017/calendar/day24/Day24.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2017.calendar.day24 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day24 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::day24) { input -> val components = input.mapIndexed { index, component -> component.apply { id = index } }.toList() buildBridges(components).maxOf { it.second } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::day24) { input -> val components = input.mapIndexed { index, component -> component.apply { id = index } }.toList() buildBridges(components).groupBy { it.first }.maxByOrNull { it.key }?.value?.maxOf { it.second } } private fun buildBridges(components: List<Component>): List<Pair<Int, Int>> { return buildBridges(0, mutableSetOf(), components) } private fun buildBridges(endValue: Int, currentBridgeComponents: MutableSet<Component>, allComponents: List<Component>): List<Pair<Int, Int>> { val nextPieces = allComponents.filter { (it.a == endValue || it.b == endValue) && !currentBridgeComponents.contains(it) } if (nextPieces.isEmpty()) return listOf(currentBridgeComponents.size to currentBridgeComponents.strength()) return nextPieces.flatMap { component -> currentBridgeComponents.add(component) (if (component.b == endValue) { buildBridges(component.a, currentBridgeComponents, allComponents) } else { buildBridges(component.b, currentBridgeComponents, allComponents) }).also { currentBridgeComponents.remove(component) } } } private fun day24(line: String): Component { val (a, b) = line.split("/").map { it.toInt() } return Component(null, a, b) } data class Component(var id: Int?, val a: Int, val b: Int) { val strength = a + b } private fun Set<Component>.strength() = sumOf { it.strength } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
1,983
advent-of-code
MIT License
src/main/kotlin/me/alejandrorm/klosure/sparql/algebra/operators/LeftJoin.kt
alejandrorm
512,041,126
false
{"Kotlin": 196720, "Ruby": 28544, "HTML": 25737}
package me.alejandrorm.klosure.sparql.algebra.operators import me.alejandrorm.klosure.model.Graph import me.alejandrorm.klosure.model.Graphs import me.alejandrorm.klosure.sparql.SolutionMapping import me.alejandrorm.klosure.sparql.algebra.filters.Expression import me.alejandrorm.klosure.sparql.algebra.filters.getEffectiveBooleanValue import me.alejandrorm.klosure.sparql.algebra.filters.operators.AndExpression class FakeLeftJoin(val operator: AlgebraOperator) : AlgebraOperator { override fun eval( solutions: Sequence<SolutionMapping>, activeGraph: Graph, graphs: Graphs ): Sequence<SolutionMapping> { throw IllegalStateException("This operator should not be actually called, create a LeftJoin instead") } override fun hasFilter(): Boolean { throw IllegalStateException("This operator should not be actually called, create a LeftJoin instead") } } class LeftJoin(val left: AlgebraOperator, val right: AlgebraOperator) : AlgebraOperator { private val nonFilterOperator: AlgebraOperator private val filterExpression: Expression? init { when (right) { is Join -> { val nonFilterOperations = right.operators.filter { it !is Filter } nonFilterOperator = when (nonFilterOperations.size) { 0 -> Identity() 1 -> nonFilterOperations[0] else -> Join(nonFilterOperations) } val filters = right.operators.filterIsInstance<Filter>() filterExpression = when (filters.size) { 0 -> null 1 -> filters[0].expression else -> filters.map { it.expression }.reduce { acc, filter -> AndExpression(acc, filter) } } } is Filter -> { nonFilterOperator = Identity() filterExpression = right.expression } else -> { nonFilterOperator = right filterExpression = null } } } override fun toString(): String = "LeftJoin($left, $nonFilterOperator, ${filterExpression ?: "true"})" override fun eval( solutions: Sequence<SolutionMapping>, activeGraph: Graph, graphs: Graphs ): Sequence<SolutionMapping> { return join(solutions, activeGraph, graphs) } private fun join( solutions: Sequence<SolutionMapping>, activeGraph: Graph, graphs: Graphs ): Sequence<SolutionMapping> = sequence { val l1 = left.eval(solutions, activeGraph, graphs) val l2 = if (nonFilterOperator is GraphGraphPattern) { nonFilterOperator.specialEval( solutions, sequenceOf(SolutionMapping.EmptySolutionMapping), graphs ).toList() } else { nonFilterOperator.eval(sequenceOf(SolutionMapping.EmptySolutionMapping), activeGraph, graphs).toList() } for (solution1 in l1) { var yielded = false for (solution2 in l2) { if (solution1.isCompatible(solution2)) { val mergedSolution = solution1.merge(solution2) if (filterExpression == null || getEffectiveBooleanValue( filterExpression.eval( mergedSolution, activeGraph, graphs ) ) == true ) { yielded = true yield(mergedSolution) } } } if (!yielded) { yield(solution1) } } } override fun hasFilter(): Boolean { return filterExpression != null } }
0
Kotlin
0
0
14abf426f3cad162c021ffae750038e25b8cb271
4,105
klosure
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1160/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1160 /** * LeetCode page: [1160. Find Words That Can Be Formed by Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/); */ class Solution { /* Complexity: * Time O(N+M) and Space O(1) where N is the flattened length of words * and N is the length of chars; */ fun countCharacters(words: Array<String>, chars: String): Int { val availableChars = chars.eachCount() return words.sumOf { word -> if (word.canBeFormedBy(availableChars)) { word.length } else { 0 } } } private fun String.eachCount(): List<Int> { return this.fold(MutableList(26) { 0 }) { acc, c -> acc[c - 'a']++ acc } } private fun String.canBeFormedBy(availableChars: List<Int>): Boolean { val remainingChars = availableChars.toMutableList() for (c in this) { remainingChars[c - 'a']-- if (remainingChars[c - 'a'] < 0) { return false } } return true } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,154
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2021/calendar/day22/Day22.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2021.calendar.day22 import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import org.apache.commons.geometry.euclidean.threed.Bounds3D import org.apache.commons.geometry.euclidean.threed.Vector3D import javax.inject.Inject class Day22 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun initializationArea(fileName: String) = generatorFactory.forFile(fileName).readAs(::instruction) { input -> calculateOverlappingCuboidArea(input.take(20)).toLong() } fun fullReactorArea(fileName: String) = generatorFactory.forFile(fileName).readAs(::instruction) { input -> calculateOverlappingCuboidArea(input).toLong() } private fun calculateOverlappingCuboidArea(instructions: Sequence<Instruction>): Double { val everyOverlapInstruction = mutableListOf<Instruction>() instructions.forEach { instruction -> val newOverlapInstructions = mutableListOf(instruction) val (_, newCube) = instruction everyOverlapInstruction.forEach { (overlapActivation, overlapCube) -> val intersectionCube: Bounds3D? = newCube.intersection(overlapCube) intersectionCube?.let { newOverlapInstructions.add(Instruction(overlapActivation.invert(), it)) } } everyOverlapInstruction.addAll(newOverlapInstructions) } return everyOverlapInstruction.sumOf { it.cube.area() * it.activation.areaModifier } } private fun Bounds3D.area() = (max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1) private fun instruction(line: String): Instruction { val activation = Activation.from(line.split(" ").first()) val (xData, yData, zData) = line.split(",").map { it .substringAfter("=") .split("..") .map(String::toDouble) } val minVector = Vector3D.of(xData.first(), yData.first(), zData.first()) val maxVector = Vector3D.of(xData.last(), yData.last(), zData.last()) return Instruction(activation, Bounds3D.from(minVector, maxVector)) } data class Instruction(val activation: Activation, val cube: Bounds3D) enum class Activation(var areaModifier: Int) { ENABLE(1), DISABLE(0), OVERAGE_FIXER(-1); fun invert() = when (this) { ENABLE -> OVERAGE_FIXER DISABLE -> DISABLE OVERAGE_FIXER -> ENABLE } companion object { fun from(activationString: String) = if (activationString == "on") ENABLE else DISABLE } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,464
advent-of-code
MIT License
src/commonMain/kotlin/urbanistic.transform/AnyToXY.kt
Monkey-Maestro
363,166,892
false
{"Kotlin": 334900}
package urbanistic.transform import kotlin.math.sqrt class Point3(var x: Double = 0.0, var y: Double = 0.0, var z: Double = 0.0) { fun set(x: Double, y: Double, z: Double) { this.x = x this.y = y this.z = z } operator fun minus(v2: Point3): Point3 { return Point3(x - v2.x, y - v2.y, z - v2.z) } operator fun plus(v2: Point3): Point3 { return Point3(v2.x + x, v2.y + y, v2.z + z) } operator fun times(sc: Double): Point3 { return Point3(x * sc, y * sc, z * sc) } operator fun div(sc: Double): Point3 { return Point3(x / sc, y / sc, z / sc) } fun normalize() { val d = sqrt(x * x + y * y + z * z) if (d != 0.0) { x /= d y /= d z /= d } } fun cross(b: Point3): Point3 { return Point3( y * b.z - b.y * z, z * b.x - b.z * x, x * b.y - b.x * y ) } } fun normal(vertices: DoubleArray): DoubleArray { val ccw = true // counterclockwise normal direction val points = arrayListOf<Point3>() for (i in 0 until (vertices.size / 3)) { points.add(Point3(vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2])) } var m3: Point3 = points[points.size - 2] var m2 = points[points.size - 1] var c123 = Point3() var v32: Point3 var v12: Point3 for (i in points.indices) { val m1 = points[i] v32 = m3 - m2 v12 = m1 - m2 c123 = if (!ccw) { c123 + v32.cross(v12) } else { c123 + v12.cross(v32) } m3 = m2 m2 = m1 } c123.normalize() return doubleArrayOf(c123.x, c123.y, c123.z) } class AnyToXYTransform(nx: Double, ny: Double, nz: Double) { protected var m00 = 0.0 protected var m01 = 0.0 protected var m02 = 0.0 protected var m10 = 0.0 protected var m11 = 0.0 protected var m12 = 0.0 protected var m20 = 0.0 protected var m21 = 0.0 protected var m22 = 0.0 /** * normal must be normalized * * @param nx * @param ny * @param nz */ fun setSourceNormal(nx: Double, ny: Double, nz: Double) { val h: Double val f: Double val hvx: Double val vx: Double = -ny val vy: Double = nx val c: Double = nz h = (1 - c) / (1 - c * c) hvx = h * vx f = if (c < 0) -c else c if (f < 1.0 - 1.0E-4) { m00 = c + hvx * vx m01 = hvx * vy m02 = -vy m10 = hvx * vy m11 = c + h * vy * vy m12 = vx m20 = vy m21 = -vx m22 = c } else { // if "from" and "to" vectors are nearly parallel m00 = 1.0 m01 = 0.0 m02 = 0.0 m10 = 0.0 m11 = 1.0 m12 = 0.0 m20 = 0.0 m21 = 0.0 m22 = if (c > 0) { 1.0 } else { -1.0 } } } /** * Assumes source normal is normalized */ init { setSourceNormal(nx, ny, nz) } fun transform(p: Point3) { val px: Double = p.x val py: Double = p.y val pz: Double = p.z p.set( m00 * px + m01 * py + m02 * pz, m10 * px + m11 * py + m12 * pz, m20 * px + m21 * py + m22 * pz ) } fun transform(data: DoubleArray) { for (i in 0 until (data.size / 3)) { val point = Point3(data[i * 3], data[i * 3 + 1], data[i * 3 + 2]) transform(point) data[i * 3] = point.x data[i * 3 + 1] = point.y data[i * 3 + 2] = point.z } } }
0
Kotlin
0
0
51396cdd4557480232f42a5649de42caa29d963c
3,823
earcut-kotlin-multiplatform
MIT License
src/main/kotlin/day21.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
fun day21 (lines: List<String>) { part1(lines) part2(lines) } fun part1(lines: List<String>) { val start = findStartPosition(lines) val currentPositions = mutableSetOf(start) val maxX = lines[0].indices.last val maxY = lines.indices.last for (i in 1..64) { takeAllPossibleSteps(lines, currentPositions, maxX, maxY) } println("Day 21 part 1: ${currentPositions.size}") } fun part2(lines: List<String>) { val extendedMap = extendMap(lines) //printGarden(extendedMap, mutableSetOf()) val start = findStartPosition(extendedMap) println(start) val currentPositions = mutableSetOf(start) val maxX = extendedMap[0].indices.last val maxY = extendedMap.indices.last //Repeats at 65 + 131 * n for (i in 1..65) { takeAllPossibleSteps(extendedMap, currentPositions, maxX, maxY) //println("${currentPositions.size}") } //No of clustered rocks contained can be given by formula: (4 * n * n) - (4 * n) + 1 printGarden(extendedMap, currentPositions) println("Day 21 part 2: ${currentPositions.size}") println() } fun takeAllPossibleSteps(lines: List<String>, currentPositions: MutableSet<Pos>, maxX: Int, maxY: Int) { val newPositions = mutableSetOf<Pos>() while (currentPositions.isNotEmpty()) { val position = currentPositions.first() currentPositions.remove(position) addPositionIfValid(Pos(position.x + 1, position.y), lines, newPositions, maxX, maxY) addPositionIfValid(Pos(position.x - 1, position.y), lines, newPositions, maxX, maxY) addPositionIfValid(Pos(position.x, position.y + 1), lines, newPositions, maxX, maxY) addPositionIfValid(Pos(position.x, position.y - 1), lines, newPositions, maxX, maxY) } currentPositions.addAll(newPositions) } fun addPositionIfValid(position: Pos, lines: List<String>, newPositions: MutableSet<Pos>, maxX: Int, maxY: Int) { if (position.x in 0..maxX && position.y in 0..maxY/* && lines[position.y][position.x] != '#'*/) { newPositions.add(position) } } fun printGarden(lines: List<String>, currentPositions: MutableSet<Pos>) { for (y in lines.indices) { for (x in lines[0].indices) { if (currentPositions.contains(Pos(x, y))) { print('O') } else { print(lines[y][x]) } } println() } } fun extendMap(lines: List<String>): List<String> { val newMap = mutableListOf<String>() var newLine = "" for (i in 1..9) { lines.forEach { line -> for (j in 1..9) { line.forEach{ cell -> newLine += if (cell == 'S' && (i != 5 || j != 5)) { '.' } else { cell } } } newMap.add(newLine) newLine = "" } } return newMap } fun findStartPosition(lines: List<String>): Pos { lines.forEachIndexed { y, line -> line.forEachIndexed { x, cell -> if (cell == 'S') { return Pos(x, y) } } } return Pos(0, 0) }
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
3,247
advent_of_code_2023
MIT License
src/main/kotlin/g0701_0800/s0792_number_of_matching_subsequences/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0701_0800.s0792_number_of_matching_subsequences // #Medium #String #Hash_Table #Sorting #Trie // #2023_03_13_Time_346_ms_(100.00%)_Space_41.7_MB_(40.00%) class Solution { fun numMatchingSubseq(s: String, words: Array<String>): Int { val buckets: Array<MutableList<Node>?> = arrayOfNulls(26) for (i in buckets.indices) { buckets[i] = ArrayList() } for (word in words) { val start = word[0] buckets[start.code - 'a'.code]?.add(Node(word, 0)) } var result = 0 for (c in s.toCharArray()) { val currBucket: MutableList<Node>? = buckets[c.code - 'a'.code] buckets[c.code - 'a'.code] = ArrayList() for (node in currBucket!!) { node.index++ if (node.index == node.word.length) { result++ } else { val start = node.word[node.index] buckets[start.code - 'a'.code]?.add(node) } } } return result } private class Node(var word: String, var index: Int) }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,146
LeetCode-in-Kotlin
MIT License
bot/engine/src/main/kotlin/admin/bot/ArtifactVersion.kt
theopenconversationkit
84,538,053
false
{"Kotlin": 5672130, "TypeScript": 1097149, "HTML": 464445, "CSS": 143185, "SCSS": 74060, "Shell": 10923, "JavaScript": 5496}
/* * Copyright (C) 2017/2021 e-voyageurs technologies * * 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 ai.tock.bot.admin.bot import kotlin.math.abs /** * An artifact version number. */ data class ArtifactVersion( val major: String, val minor: String, val iteration: String ) { companion object { /** * The "unknown" artifact version number. */ val UNKNOWN: ArtifactVersion = ArtifactVersion("NONE", "NONE", "NONE") private fun distance(v1: String, v2: String): Long { return if (v1 == v2) { 0 } else if (v1.toLongOrNull() != null && v2.toLongOrNull() != null) { abs(v1.toLong() - v2.toLong()) } else { levenshtein(v1, v2).toLong() } } private fun levenshtein( s: String, t: String, charScore: (Char, Char) -> Int = { c1, c2 -> if (c1 == c2) 0 else 1 } ): Int { // Special cases if (s == t) return 0 if (s == "") return t.length if (t == "") return s.length val initialRow: List<Int> = (0 until t.length + 1).map { it }.toList() return (0 until s.length).fold( initialRow, { previous, u -> (0 until t.length).fold( mutableListOf(u + 1), { row, v -> row.add( listOf( row.last() + 1, previous[v + 1] + 1, previous[v] + charScore(s[u], t[v]) ).minOrNull()!! ) row } ) } ).last() } } internal fun distanceFrom(version: ArtifactVersion): Long { return distance(major, version.major) * 100 + distance(minor, version.minor) * 10 + distance(iteration, version.iteration) } }
147
Kotlin
119
435
aa697c247870de83ada91b342164cc1a525fdfa7
2,637
tock
Apache License 2.0
src/Day11.kt
erwinw
572,913,172
false
{"Kotlin": 87621}
@file:Suppress("MagicNumber") private const val DAY = "11" private const val PART1_CHECK = 10605L private const val PART2_CHECK = 2713310158L fun main() { data class Monkey( val id: Int, var items: MutableList<Long>, val operation: (Long) -> Long, val divisor: Long, val trueTargetMonkey: Int, val falseTargetMonkey: Int, var inspectedCount: Long = 0L, ) { fun inspectAndThrowAll(monkeys: List<Monkey>, relief: Int, commonDivisor: Long = 1) { inspectedCount += items.size // println(" Items: ${items.size}") items.removeAll { item -> true.also { val inspectionResult = operation(item) val postRelief = if (relief != 1) { inspectionResult / relief } else { inspectionResult % commonDivisor } val targetMonkeyId = if (postRelief % divisor == 0L) trueTargetMonkey else falseTargetMonkey // println(" Item: $item -> $inspectionResult -> $postRelief; thrown to $targetMonkeyId") val targetMonkey = monkeys[targetMonkeyId] targetMonkey.items.add(postRelief) } } } } fun parseOperation(opString: String): (Long) -> Long = when { opString == "* old" -> ({ it * it }) opString.first() == '*' -> { val operand = opString.drop(2).toLong() ({ it * operand }) } opString.first() == '+' -> { val operand = opString.drop(2).toLong() ({ it + operand }) } else -> throw IllegalArgumentException("Unsupported opString: $opString") } fun parseMonkey(input: List<String>) = Monkey( id = input[0].drop(7).dropLast(1).toInt(), items = input[1].drop(18).split(", ").map(String::toLong).toMutableList(), operation = parseOperation(input[2].drop(23)), divisor = input[3].drop(21).toLong(), trueTargetMonkey = input[4].drop(29).toInt(), falseTargetMonkey = input[5].drop(30).toInt(), ) fun part1(input: List<String>): Long { val monkeys = input.chunked(7).map(::parseMonkey) val commonDivisor = monkeys.map { it.divisor }.reduce { acc, i -> acc * i } repeat(20) { round -> println("\nStarting round $round\n========") monkeys.forEach { monkey -> // println("Monkey ${monkey.id}:") monkey.inspectAndThrowAll(monkeys, 3) } println("After round ${round + 1}, the monkeys are holding items with these worry levels:") monkeys.forEach { println("Monkey ${it.id}: ${it.items.joinToString()}") } println("") } monkeys.forEach { println("Monkey ${it.id} inspected items ${it.inspectedCount} times.") } return monkeys.map { it.inspectedCount }.sortedDescending().take(2).reduce { acc, i -> acc * i } } fun part2(input: List<String>): Long { val monkeys = input.chunked(7).map(::parseMonkey) val commonDivisor = monkeys.map { it.divisor }.reduce { acc, i -> acc * i } val printIf = listOf( 0, 19, 999, 1999, 2999, 3999, 4999, 5999, 6999, 7999, 8999, 9999, ) repeat(10_000) { round -> // if (round % 100 == 0) { // println("Round: $round") // } // println("\nStarting round $round\n========") monkeys.forEach { monkey -> // println("Monkey ${monkey.id}:") monkey.inspectAndThrowAll(monkeys, 1, commonDivisor) } if (round in printIf) { println("") println("After round ${round + 1}, the monkeys are holding items with these worry levels:") monkeys.forEach { println("Monkey ${it.id}: ${it.items.joinToString()}") } println("") monkeys.forEach { println("Monkey ${it.id} inspected items ${it.inspectedCount} times.") } println("") } } monkeys.forEach { println("Monkey ${it.id} inspected items ${it.inspectedCount} times.") } return monkeys.map { it.inspectedCount }.sortedDescending().take(2).reduce { acc, i -> acc * i } } println("Day $DAY") // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") check(part1(testInput).also { println("Part1 output: $it") } == PART1_CHECK) check(part2(testInput).also { println("Part2 output: $it") } == PART2_CHECK) val input = readInput("Day$DAY") println("Part1 final output: ${part1(input)}") println("Part2 final output: ${part2(input)}") }
0
Kotlin
0
0
57cba37265a3c63dea741c187095eff24d0b5381
5,097
adventofcode2022
Apache License 2.0
src/main/kotlin/y2023/day10/Day10.kt
niedrist
726,105,019
false
{"Kotlin": 19919}
package y2023.day10 import BasicDay import util.FileReader val d = FileReader.asStrings("2023/day10.txt").map { it.toCharArray() }.toCoordinates().toMutableList() fun main() = Day09.run() object Day09 : BasicDay() { override fun part1(): Int { val start = d.first { it.pipe == 'S' } val updatedStartPipe = start.copy(pipe = getStartDirection(start)) d.remove(start) d.add(updatedStartPipe) var currentPipe = updatedStartPipe val visited = mutableSetOf<Coordinate>() while (currentPipe != updatedStartPipe || visited.isEmpty()) { visited.add(currentPipe) val surroundings = currentPipe.surroundings() for (it in surroundings) { if (currentPipe.isConnectedWith(it, 0) && (it !in visited || it == updatedStartPipe)) { currentPipe = it break } } } return visited.size / 2 } override fun part2() = 2 // TODO } private fun getStartDirection(start: Coordinate): Char { val surroundings = start.surroundings() for (tryPipe in listOf('|', '-', 'L', 'J', '7', 'F')) { val countConnected = surroundings.count { start.copy(pipe = tryPipe).isConnectedWith(it, 0) } if (countConnected == 2) return tryPipe } throw IllegalStateException("Start pipe is not properly connected") } private fun Coordinate.surroundings(): List<Coordinate> = buildList { d.forEach { if ([email protected] - it.x in listOf(-1, 0, 1) && [email protected] - it.y in listOf(-1, 0, 1) && this@surroundings != it ) { add(it) } } } private fun Coordinate.isConnectedWith(other: Coordinate, countTries: Int): Boolean { if (this.x - other.x !in listOf(-1, 0, 1) || this.y - other.y !in listOf(-1, 0, 1) || countTries > 1) return false return when (this.pipe) { '|' -> when { other.pipe == '|' && this.x == other.x && this.y - other.y in listOf(-1, 1) -> true other.pipe == 'L' && this.x == other.x && this.y == other.y - 1 -> true other.pipe == 'J' && this.x == other.x && this.y == other.y - 1 -> true other.pipe == '7' && this.x == other.x && this.y == other.y + 1 -> true other.pipe == 'F' && this.x == other.x && this.y == other.y + 1 -> true else -> other.isConnectedWith(this, countTries + 1) } '-' -> when { other.pipe == '-' && this.y == other.y && this.x - other.x in listOf(-1, 1) -> true other.pipe == 'J' && this.y == other.y && this.x == other.x - 1 -> true other.pipe == '7' && this.y == other.y && this.x == other.x - 1 -> true other.pipe == 'L' && this.y == other.y && this.x == other.x + 1 -> true other.pipe == 'F' && this.y == other.y && this.x == other.x + 1 -> true else -> other.isConnectedWith(this, countTries + 1) } 'L' -> when { other.pipe == 'J' && this.y == other.y && this.x == other.x - 1 -> true other.pipe == '7' && ( (this.y == other.y && this.x == other.x - 1) || (this.x == other.x && this.y == other.y + 1) ) -> true other.pipe == 'F' && this.x == other.x && this.y == other.y + 1 -> true else -> other.isConnectedWith(this, countTries + 1) } 'J' -> when { other.pipe == 'F' && ( (this.y == other.y && this.x == other.x + 1) || (this.x == other.x && this.y == other.y + 1) ) -> true other.pipe == '7' && this.x == other.x && this.y == other.y + 1 -> true else -> other.isConnectedWith(this, countTries + 1) } 'F' -> when { other.pipe == '7' && this.y == other.y && this.x == other.x - 1 -> true else -> other.isConnectedWith(this, countTries + 1) } '.' -> false else -> other.isConnectedWith(this, countTries + 1) } } data class Coordinate(val x: Int, val y: Int, val pipe: Char) fun List<CharArray>.toCoordinates() = buildList { [email protected] { y, chars -> chars.forEachIndexed { x, c -> add(Coordinate(x, y, c)) } } }
0
Kotlin
0
1
37e38176d0ee52bef05f093b73b74e47b9011e24
4,395
advent-of-code
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day06.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 /** * AoC 2017, Day 6 * * Problem Description: http://adventofcode.com/2017/day/6 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day6/ */ typealias AnswerFunction = (Map<String, Int>, String) -> Int class Day06(stringInput: String) { private val input: IntArray = stringInput.split(Constants.WHITESPACE).map { it.toInt() }.toIntArray() fun solvePart1(): Int = reallocate(input) { map, _ -> map.size } fun solvePart2(): Int = reallocate(input) { map, key -> (map.size) - map.getValue(key) } tailrec private fun reallocate(memory: IntArray, seen: Map<String, Int> = mutableMapOf(), answer: AnswerFunction): Int { val hash = memory.joinToString() return if (hash in seen) answer(seen, hash) else { val (index, amount) = memory.withIndex().maxBy { it.value }!! memory[index] = 0 repeat(amount) { i -> val idx = (index + i + 1) % memory.size memory[idx] += 1 } reallocate(memory, seen + (hash to seen.size), answer) } } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,306
advent-2017-kotlin
MIT License
src/main/kotlin/probability/independence.kt
jpgagnebmc
625,129,199
false
null
package probability import bayesian.Markov import bayesian.Node import logic.braced interface I { val X: List<Node> val Z: List<Node> val Y: List<Node> } fun I(X: List<Node>, Z: List<Node>, Y: List<Node>): I = IImpl(X, Z, Y) val I.iString: String get() = "I(${X.s}, ${Z.s}, ${Y.s})" private val List<Node>.s: String get() = when { size > 1 -> sortedBy { it.letter }.joinToString(", ") { it.letter }.braced size == 1 -> first().letter else -> "∅" } data class IImpl(override val X: List<Node>, override val Z: List<Node>, override val Y: List<Node>) : I { override fun toString(): String = iString } fun List<I>.conditionallyIndependent(I: I): Boolean = I.Z.none { z -> allParents(I.X).contains(z) } fun List<I>.allParents(nodes: List<Node>): List<Node> = nodes.flatMap { allParents(it) } fun List<I>.allParents(node: Node): List<Node> = filter { it.X.contains(node) }.flatMap { it.Z + it.Z.flatMap { allParents(it) } } fun List<I>.marginallyIndependent(I: I): Boolean = I.Z.none { z -> any { it.X.contains(z) } } fun Probability.removeIndependencies(markov: List<Markov>) = copy( given = given.filterNot { g -> g in query.flatMap { n -> markov.first { it.node == n }.nonDescendants } } )
0
Kotlin
0
0
087bcc0f908fb71da2e3f0e03fe8066f44797643
1,269
homework
Apache License 2.0
src/main/kotlin/days/day7/Day7.kt
Stenz123
694,797,878
false
{"Kotlin": 27460}
package days.day7 import days.Day class Day7:Day() { override fun partOne(): Any { return getValidBagCunt("shiny gold", readInput()).count() } fun getValidBagCunt(bag: String, input: List<String>): Set<String> { val validBags = input.filter{it.substringAfter(" ").contains(bag)} if (validBags.isEmpty()) { return setOf() } val result = validBags.map{it.substringBefore(" bags")}.toSet().toMutableSet() for (validBag in validBags) { result += getValidBagCunt(validBag.substringBefore(" bags"), input) } return result } fun countBagsInGOldBag(bag: String , input: List<String>): Int{ val validBags = input.filter{it.substringBefore(" contain").contains(bag)} val containedBags = validBags.map { it.substringAfter("contain ").split(", ").map{it.replace(".","")} }.flatten() var result = 1 for (containedBag in containedBags) { val numberOfBags = containedBag.substringBefore(" ").toIntOrNull() ?: return 1 result += numberOfBags * countBagsInGOldBag(containedBag.substringAfter(" "), input) } return result } override fun partTwo(): Any { return countBagsInGOldBag("shiny gold", readInput())-1 } }
0
Kotlin
0
0
3e5ee86cd723c293ec44b1be314697ccf5cdaab7
1,301
advent-of-code-2020
The Unlicense