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/com/ncorti/aoc2023/Day14.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 fun main() { fun parseInput() = getInputAsText("14") { split("\n").filter(String::isNotBlank).map { it.toCharArray() }.toTypedArray() } fun computeWeight(input: Array<CharArray>): Long { var total = 0L for (i in input.indices) { for (j in input[i].indices) { if (input[i][j] == 'O') { total += input.size - i } } } return total } fun moveNorth(input: Array<CharArray>) { for (i in 1..<input.size) { for (j in input[i].indices) { if (input[i][j] == 'O') { // Move up for (k in i - 1 downTo 0) { if (input[k][j] == '.') { input[k][j] = 'O' input[k + 1][j] = '.' } else { break } } } } } } fun moveSouth(input: Array<CharArray>) { for (i in input.size - 1 downTo 0) { for (j in input[i].size - 1 downTo 0) { if (input[i][j] == 'O') { for (k in i + 1 until input.size) { if (input[k][j] == '.') { input[k][j] = 'O' input[k - 1][j] = '.' } else { break } } } } } } fun moveWest(input: Array<CharArray>) { for (i in 0..<input[0].size) { for (j in input.indices) { if (input[i][j] == 'O') { // Move left for (k in j - 1 downTo 0) { if (input[i][k] == '.') { input[i][k] = 'O' input[i][k + 1] = '.' } else { break } } } } } } fun moveEast(input: Array<CharArray>) { for (i in input[0].size - 1 downTo 0) { for (j in input.size - 1 downTo 0) { if (input[i][j] == 'O') { // Move right for (k in j + 1 until input[0].size) { if (input[i][k] == '.') { input[i][k] = 'O' input[i][k - 1] = '.' } else { break } } } } } } fun part1(): Long { val input = parseInput() moveNorth(input) return computeWeight(input) } fun part2(): Long { val input = parseInput() var step = 0 val seen = mutableMapOf<String, Int>() var loopSize = -1 while (true) { moveNorth(input) moveWest(input) moveSouth(input) moveEast(input) val mapString = input.joinToString("") { it.joinToString("") } if (mapString !in seen) { seen[mapString] = step } else { loopSize = step - seen[mapString]!! break } step++ } val loopingTimes = (1000000000 / loopSize) - 10 step += ((loopingTimes) * (loopSize)) while (step < 1000000000 - 1) { moveNorth(input) moveWest(input) moveSouth(input) moveEast(input) step++ } return computeWeight(input) } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
3,832
adventofcode-2023
MIT License
versions/Kotlin/src/simulator/SimulatorBase.kt
qiskit-community
198,048,454
false
null
package simulator import model.ComplexNumber import model.QuantumCircuit import util.MathConstants import kotlin.math.pow abstract class SimulatorBase { open fun simulate(circuit: QuantumCircuit): List<ComplexNumber> { val sum = circuit.probabilitySum() return if (sum > MathConstants.Eps) { if (sum < 1 - MathConstants.Eps || sum > 1 + MathConstants.Eps) circuit.normalize(sum) val amplitudes = arrayListOf<ComplexNumber>() circuit.amplitudes.forEach { amplitudes.add(it) } amplitudes } else { val amplitudes = arrayListOf<ComplexNumber>() for (i in 0 until circuit.amplitudeLength) { amplitudes.add(ComplexNumber(0.0, 0.0)) } amplitudes.first().real = 1.0 amplitudes } } open fun simulateInPlace(circuit: QuantumCircuit): List<ComplexNumber> { val localAmplitudes = arrayListOf<ComplexNumber>() val sum = circuit.probabilitySum() if (sum > MathConstants.Eps) { if (sum < 1 - MathConstants.Eps || sum > 1 + MathConstants.Eps) { circuit.normalize(sum) } circuit.amplitudes.forEach { localAmplitudes.add(it) } } else { circuit.amplitudes.forEach { _ -> localAmplitudes.add(ComplexNumber(0.0, 0.0)) } localAmplitudes.first().real = 1.0 } return localAmplitudes } open fun getProbabilities(circuit: QuantumCircuit): List<Double> { val probabilities = arrayListOf<Double>() val length = 2.0.pow(circuit.numberOfQubits).toInt() for (i in 0 until length) probabilities.add(0.0) return probabilities } open fun getProbabilities(amplitudes: List<ComplexNumber>): List<Double> = amplitudes.map { it.real.pow(2) + it.complex.pow(2) } open fun calculateProbabilities(amplitudes: List<ComplexNumber>, probabilities: List<Double>): List<Double> { val localProbabilities = arrayListOf<Double>() amplitudes.forEach { _ -> localProbabilities.add(0.0) } localProbabilities.mapIndexed { index, _ -> amplitudes[index].real.pow(2) + amplitudes[index].complex.pow(2) } return localProbabilities } }
8
Jupyter Notebook
23
42
4e5d67708f248c0c4be949ce27ea8d449b07d216
2,318
MicroQiskit
Apache License 2.0
src/chapter4/section1/ex24.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter4.section1 import edu.princeton.cs.algs4.Queue import edu.princeton.cs.algs4.Stack import edu.princeton.cs.algs4.StdIn import extensions.inputPrompt import extensions.readLine import java.util.* import java.util.regex.Pattern /** * 修改DegreesOfSeparation,从命令行接受一个整型参数y,忽略上映年数超过y的电影 * * 解:重写[DegreesOfSeparation]类,通过传入筛选条件[filter],忽略不符合条件的顶点 */ class FilterDegreesOfSeparation(stream: String, sp: String, val name: String, val filter: (String) -> Boolean) { private val sg = SymbolGraph(stream, sp) private val graph = sg.G() init { require(sg.contains(name)) require(filter(name)) { "The starting point should meet the filter criteria." } } private val marked = BooleanArray(graph.V) private val edgeTo = IntArray(graph.V) private val distTo = IntArray(graph.V) { -1 } init { val s = sg.index(name) val queue = Queue<Int>() marked[s] = true distTo[s] = 0 queue.enqueue(s) while (!queue.isEmpty) { val v = queue.dequeue() graph.adj(v).forEach { w -> if (!marked[w] && filter(sg.name(w))) { marked[w] = true edgeTo[w] = v distTo[w] = distTo[v] + 1 queue.enqueue(w) } } } } fun degrees(s: String): Int { // 不相连的人用最大的Int值表示(无穷大只能用浮点型数据表示) if (!sg.contains(s)) return Int.MAX_VALUE // 需要注意,路径长度除以2才是真正的间隔度数 return if (marked[sg.index(s)]) distTo[sg.index(s)] / 2 else Int.MAX_VALUE } fun pathTo(s: String): Iterable<String>? { if (!sg.contains(s) || !marked[sg.index(s)]) return null val stack = Stack<String>() var w = sg.index(s) val index = sg.index(name) while (w != index) { stack.push(sg.name(w)) w = edgeTo[w] } stack.push(name) return stack } fun printPath(s: String) { val degrees = degrees(s) println(if (degrees == Int.MAX_VALUE) "Not connected" else "degrees: $degrees") val iterator = pathTo(s)?.iterator() ?: return while (iterator.hasNext()) { println(" ${iterator.next()}") } } } fun main() { inputPrompt() // 通过正则表达式匹配电影上映年份 val pattern = Pattern.compile("\\((\\d+)\\)") // 获取当前的年份信息 val currentYear = Calendar.getInstance().get(Calendar.YEAR) // 忽略y年之前上映的电影 val y = readLine("y: ").toInt() val degreesOfSeparation = FilterDegreesOfSeparation("./data/movies.txt", "/", "<NAME>") { var result = true val matcher = pattern.matcher(it) // 电影名称可以匹配正则,演员名称不会匹配正则 if (matcher.find()) { val year = matcher.group(1).toInt() if (currentYear - year > y) { result = false } } result } while (StdIn.hasNextLine()) { val line = StdIn.readLine() degreesOfSeparation.printPath(line) } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
3,341
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/days/Day7.kt
andilau
429,557,457
false
{"Kotlin": 103829}
package days import days.Day7.Instruction.* @AdventOfCodePuzzle( name = "Some Assembly Required", url = "https://adventofcode.com/2015/day/7", date = Date(day = 7, year = 2015) ) class Day7(instructions: List<String>) : Puzzle { private val wires: Map<String, Instruction> = instructions.parseInstructions() override fun partOne(): Int = wires.solveSignalFor("a") override fun partTwo(): Int = wires .toMutableMap() .apply { this["b"] = Literal(partOne()) } .solveSignalFor("a") internal fun solveSignalFor(variable: String) = wires.solveSignalFor(variable) private fun List<String>.parseInstructions() = associate { it.split(" -> ", limit = 2) .let { (instruction, identifier) -> identifier to Instruction.from(instruction) } } private fun Map<String, Instruction>.solveSignalFor(wire: String): Int { val memo: MutableMap<String, Int> = mutableMapOf() fun Map<String, Instruction>.solve(wire: String): Int { return memo[wire] ?: wire.toIntOrNull() ?: when (val expression = this[wire]) { is Literal -> expression.value is Equals -> solve(expression.op) is And -> solve(expression.op1) and solve(expression.op2) is Or -> solve(expression.op1) or solve(expression.op2) is Lshift -> solve(expression.op) shl expression.amount is Rshift -> solve(expression.op) shr expression.amount is Not -> solve(expression.op).inv() and 0xFFFF else -> error("Unknown expression ($expression) for signal to wire $wire ") } .also { memo[wire] = it } } return solve(wire) } sealed interface Instruction { data class Literal(val value: Int) : Instruction data class Equals(val op: String) : Instruction data class And(val op1: String, val op2: String) : Instruction data class Or(val op1: String, val op2: String) : Instruction data class Lshift(val op: String, val amount: Int) : Instruction data class Rshift(val op: String, val amount: Int) : Instruction data class Not(val op: String) : Instruction companion object { private val number = """\d+""".toRegex() private val identifier = """[a-z]+""".toRegex() fun from(line: String): Instruction = with(line) { when { matches(number) -> Literal(toInt()) matches(identifier) -> Equals(this) contains(" AND ") -> split(" AND ").let { And(it.first(), it.last()) } contains(" OR ") -> split(" OR ").let { Or(it.first(), it.last()) } contains(" LSHIFT ") -> split(" LSHIFT ").let { Lshift(it.first(), it.last().toInt()) } contains(" RSHIFT ") -> split(" RSHIFT ").let { Rshift(it.first(), it.last().toInt()) } startsWith("NOT ") -> Not(substringAfter("NOT ")) else -> error("Unknown configuration: $line") } } } } }
0
Kotlin
0
0
55932fb63d6a13a1aa8c8df127593d38b760a34c
3,376
advent-of-code-2015
Creative Commons Zero v1.0 Universal
src/day08/Day08.kt
apeinte
574,487,528
false
{"Kotlin": 47438}
package day08 import readDayInput //Don't forget to fill this constant. const val RESULT_EXAMPLE_PART_ONE = 21 const val RESULT_EXAMPLE_PART_TWO = 8 const val VALUE_OF_THE_DAY = 8 fun main() { fun getNumberOfTreeVisibleLeftOrRight( treesOnTheDirection: List<Char>, treeHeight: Int, includedTallerTree: Boolean = false ): Int { var counterTreeVisibleBeforeTallerTree = 0 for ((i:Int, treeOnTheDirection)in treesOnTheDirection.withIndex()) { if (treeOnTheDirection.toString().toInt() >= treeHeight) { break } else { if (i + 1 == treesOnTheDirection.size) { break } counterTreeVisibleBeforeTallerTree++ } } if (includedTallerTree) { counterTreeVisibleBeforeTallerTree++ } return counterTreeVisibleBeforeTallerTree } fun getNumberOfTreeVisibleTopOrBottom( treesOnTheDirection: List<String>, treePosition: Int, treeHeight: Int, includedTallerTree: Boolean = false ): Int { var counterTreeVisibleBeforeTallerTree = 0 for ((i: Int, treeOnTop) in treesOnTheDirection.withIndex()) { val treeOnTopOnTheSameColumn = treeOnTop.toList()[treePosition].toString().toInt() if (treeOnTopOnTheSameColumn >= treeHeight) { break } else { if (i + 1 == treesOnTheDirection.size) { break } counterTreeVisibleBeforeTallerTree++ } } if (includedTallerTree) { counterTreeVisibleBeforeTallerTree++ } return counterTreeVisibleBeforeTallerTree } fun countLeft(lineOfTrees: String, treePosition: Int, treeHeight: Int): Int { val treesOnLeft = lineOfTrees.toList().subList(0, treePosition) return getNumberOfTreeVisibleLeftOrRight(treesOnLeft.reversed(), treeHeight, true) } fun countRight(lineOfTrees: String, treePosition: Int, treeHeight: Int): Int { val treesOnRight = lineOfTrees.toList().subList(treePosition + 1, lineOfTrees.lastIndex + 1) return getNumberOfTreeVisibleLeftOrRight(treesOnRight, treeHeight, true) } fun countTop(input: List<String>, currentIndex: Int, treePosition: Int, treeHeight: Int): Int { val treesOnTop = input.subList(0, currentIndex) return getNumberOfTreeVisibleTopOrBottom(treesOnTop.reversed(), treePosition, treeHeight, true) } fun countBottom( input: List<String>, currentIndex: Int, treePosition: Int, treeHeight: Int ): Int { val treesOnBottom = input.subList(currentIndex + 1, input.lastIndex + 1) return getNumberOfTreeVisibleTopOrBottom(treesOnBottom, treePosition, treeHeight, true) } fun checkLeft(lineOfTrees: String, treePosition: Int, treeHeight: Int): Boolean { val treesOnLeft = lineOfTrees.toList().subList(0, treePosition) return getNumberOfTreeVisibleLeftOrRight(treesOnLeft, treeHeight) == treesOnLeft.size } fun checkRight(lineOfTrees: String, treePosition: Int, treeHeight: Int): Boolean { val treesOnRight = lineOfTrees.toList().subList(treePosition + 1, lineOfTrees.lastIndex + 1) return getNumberOfTreeVisibleLeftOrRight(treesOnRight, treeHeight) == treesOnRight.size } fun checkTop( input: List<String>, currentIndex: Int, treePosition: Int, treeHeight: Int ): Boolean { val treesOnTop = input.subList(0, currentIndex) return getNumberOfTreeVisibleTopOrBottom( treesOnTop, treePosition, treeHeight ) == treesOnTop.size } fun checkBottom( input: List<String>, currentIndex: Int, treePosition: Int, treeHeight: Int ): Boolean { val treesOnBottom = input.subList(currentIndex + 1, input.lastIndex + 1) return getNumberOfTreeVisibleTopOrBottom( treesOnBottom, treePosition, treeHeight ) == treesOnBottom.size } fun thisTreeIsVisibleOnTheColumn( input: List<String>, currentIndex: Int, treePosition: Int, treeHeight: Int ): Boolean { return checkTop(input, currentIndex, treePosition, treeHeight) || checkBottom(input, currentIndex, treePosition, treeHeight) } fun thisTreeIsVisibleOnTheRaw( lineOfTrees: String, treePosition: Int, treeHeight: Int ): Boolean { return checkLeft(lineOfTrees, treePosition, treeHeight) || checkRight(lineOfTrees, treePosition, treeHeight) } fun part1(input: List<String>): Int { var result = 0 input.forEachIndexed { index, lineOfTrees -> when (index) { 0 -> { result += lineOfTrees.length } input.size -> { result += lineOfTrees.length } else -> { lineOfTrees.forEachIndexed { treePosition, tree -> val treeHeight = tree.toString().toInt() when (treePosition) { 0 -> { result++ } lineOfTrees.length - 1 -> { result++ } else -> { if (thisTreeIsVisibleOnTheRaw( lineOfTrees, treePosition, treeHeight ) || thisTreeIsVisibleOnTheColumn( input, index, treePosition, treeHeight ) ) { result++ } } } } } } } return result } fun part2(input: List<String>): Int { var result = 0 input.forEachIndexed { index, lineOfTrees -> lineOfTrees.forEachIndexed { treePosition, tree -> val treeHeight = tree.toString().toInt() val resultLeft = if (treePosition == 0) { 0 } else { countLeft(lineOfTrees, treePosition, treeHeight) } val resultRight = if (treePosition == lineOfTrees.length - 1) { 0 } else { countRight(lineOfTrees, treePosition, treeHeight) } val resultBottom = if (index == input.lastIndex) { 0 } else { countBottom(input, index, treePosition, treeHeight) } val resultTop = if (index == 0) { 0 } else { countTop(input, index, treePosition, treeHeight) } val calculatedTreeSpot = resultTop * resultLeft * resultBottom * resultRight if (calculatedTreeSpot > result) { result = calculatedTreeSpot } } } return result } val inputRead = readDayInput(VALUE_OF_THE_DAY) val inputReadTest = readDayInput(VALUE_OF_THE_DAY, true) var testCheck = part1(inputReadTest) if (testCheck == RESULT_EXAMPLE_PART_ONE) { println("how many trees are visible from outside the grid?\n${part1(inputRead)}") } else { println("Test failed!\n- Required: $RESULT_EXAMPLE_PART_ONE\n- Found: $testCheck") } testCheck = part2(inputReadTest) if (testCheck == RESULT_EXAMPLE_PART_TWO) { println("What is the highest scenic score possible for any tree?\n${part2(inputRead)}") } else { println("Test failed!\n- Required: $RESULT_EXAMPLE_PART_TWO\n- Found: $testCheck") } }
0
Kotlin
0
0
4bb3df5eb017eda769b29c03c6f090ca5cdef5bb
8,422
my-advent-of-code
Apache License 2.0
src/main/java/sortingalgorithms/mergesort/kotlin/MergeSort.kt
ucdevinda123
267,009,882
false
{"Java": 44875, "Kotlin": 10712, "Python": 796}
package sortingalgorithms.mergesort.kotlin import sortingalgorithms.SortingAlgorithm class MergeSort : SortingAlgorithm() { override fun sort(input: IntArray) { val length = input.size if (length < 2) return //Base condition //1.Find the middle and divide the array O(log) var middle = length / 2 var leftArray = IntArray(middle) { 0 } // 0 to middle var rightArray = IntArray(length - middle) { 0 } // middle to end of the array (length) for (i in 0 until middle) { leftArray[i] = input[i] } for (j in middle until length) { //j - middle : make sure to get the right index rightArray[j - middle] = input[j] } //2. We sort both the arrays Recursively sort(leftArray) sort(rightArray) //3. Last step let's merge it merge(leftArray, rightArray, input) } private fun merge(leftArray: IntArray, rightArray: IntArray, inputData: IntArray) { var i = 0 var j = 0 var k = 0 // when both left and right array sizes are equal while (i < leftArray.size && j < rightArray.size) { if (leftArray[i] <= rightArray[j]) { inputData[k++] = leftArray[i++] } else { inputData[k++] = rightArray[j++] } } while (i < leftArray.size) { inputData[k++] = leftArray[i++] } while (j < rightArray.size) { inputData[k++] = rightArray[j++] } } }
0
Java
0
1
c082b07bd687a3cf937b64db3100fb19ccb15340
1,567
data-structures-and-algorithms
MIT License
localization/src/main/java/com/technokratos/compose/localization/plurals.kt
TechnokratosDev
312,540,588
false
null
package com.technokratos.compose.localization import java.util.Locale import kotlin.math.absoluteValue import android.util.Log class PluralRule( val zero: (Double, Long, Long, Int, Int) -> Boolean = { _, _, _, _, _ -> false }, val one: (Double, Long, Long, Int, Int) -> Boolean = { _, _, _, _, _ -> false }, val two: (Double, Long, Long, Int, Int) -> Boolean = { _, _, _, _, _ -> false }, val few: (Double, Long, Long, Int, Int) -> Boolean = { _, _, _, _, _ -> false }, val many: (Double, Long, Long, Int, Int) -> Boolean = { _, _, _, _, _ -> false } ) class Plural( val zero: CharSequence? = null, val one: CharSequence? = null, val two: CharSequence? = null, val few: CharSequence? = null, val many: CharSequence? = null, val other: CharSequence ) fun Plurals( defaultValue: Plural, localeToPlural: Map<Locale, Plural>, name: Int = generateUID() ): Localization.(Double) -> CharSequence { defaultLocalization.plurals[name] = defaultValue for ((locale, value) in localeToPlural.entries) { if (!isLocaleRegistered(locale)) { // TODO issue-9 Log.w( "jcl10n", "There is no plural rule for $locale currently. Plural's 'other = ${value.other}' field can be used only!" ) } val localization = localizationMap[locale] ?: throw RuntimeException("There is no locale $locale") localization.plurals[name] = value } return fun Localization.(quantity: Double): CharSequence { return getPlural(name, quantity) ?: defaultLocalization.getPlural(name, quantity) ?: throw RuntimeException("There is no string called $name in localization $this") } } fun Plurals( name: Any, defaultValue: Plural, localeToPlural: Map<Locale, Plural> ): Localization.(Double) -> CharSequence { return Plurals( defaultValue, localeToPlural, generateUID(name) ) } private fun Localization.getPlural(name: Int, quantity: Double): CharSequence? { val absQuantity = quantity.absoluteValue val (int, frac) = absQuantity.toString().split('.') val integerPart = int.toLong() val fractionPart = frac.trimStart('0').ifEmpty { "0" }.toLong() val fractionPartDigitCount = frac.trimEnd('0').count() return plurals[name]?.let { resolveString( it, locale, absQuantity, integerPart, fractionPart, fractionPartDigitCount, 0 // we don't support String quantity parameter now so exp part is always 0 ) } } private val defaultPluralRule = onlyOther private fun isLocaleRegistered(locale: Locale): Boolean { return localeToPluralRule.containsKey(locale) } private fun resolveString( plural: Plural, locale: Locale, n: Double, i: Long, f: Long, v: Int, e: Int ): CharSequence { val rule = localeToPluralRule[locale] ?: defaultPluralRule return when { rule.zero(n, i, f, v, e) && plural.zero != null -> plural.zero rule.one(n, i, f, v, e) && plural.one != null -> plural.one rule.two(n, i, f, v, e) && plural.two != null -> plural.two rule.few(n, i, f, v, e) && plural.few != null -> plural.few rule.many(n, i, f, v, e) && plural.many != null -> plural.many else -> plural.other } }
9
Kotlin
5
18
6f8e8a2abe8caa9a4a6770d2afa31898413baf9d
3,403
jetpack-compose-localization
MIT License
src/Day06.kt
KarinaCher
572,657,240
false
{"Kotlin": 21749}
fun main() { fun findMarker(windowSize: Int, input: List<String>): Int { var index = windowSize for (line in input) { val windowed = line.toCharArray().toList().windowed(windowSize) for (window in windowed) { if (window.toSet().size == windowSize) { return index } index++ } } return -1 } fun part1(input: List<String>): Int { val windowSize = 4 return findMarker(windowSize, input) } fun part2(input: List<String>): Int { val windowSize = 14 return findMarker(windowSize, input) } 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
17d5fc87e1bcb2a65764067610778141110284b6
879
KotlinAdvent
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/LowestCommonAncestor.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph class LowestCommonAncestor { class AncestralTree(name: Char) { val name = name var ancestor: AncestralTree? = null } fun getYoungestCommonAncestor( topAncestor: AncestralTree, descendantOne: AncestralTree, descendantTwo: AncestralTree ): AncestralTree? { val depthOne = getDepth(descendantOne, topAncestor) val depthTwo = getDepth(descendantTwo, topAncestor) if (depthOne > depthTwo) { return backTrackAncestralTree(descendantOne, descendantTwo, depthOne - depthTwo) } else { return backTrackAncestralTree(descendantTwo, descendantOne, depthTwo - depthOne) } } fun getDepth(start: AncestralTree, topAncestor: AncestralTree): Int { var descendant: AncestralTree? = start var depth = 0 while (descendant != topAncestor) { depth++ descendant = descendant!!.ancestor } return depth } fun backTrackAncestralTree( lowerDescendant: AncestralTree, higherDescendant: AncestralTree, diffStart: Int ): AncestralTree? { var lower: AncestralTree? = lowerDescendant var higher: AncestralTree? = higherDescendant var diff = diffStart while (diff > 0) { lower = lower!!.ancestor diff-- } while (lower != higher) { lower = lower!!.ancestor higher = higher!!.ancestor } return lower } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,567
DS_Algo_Kotlin
MIT License
app/src/main/java/com/themobilecoder/adventofcode/day2/DayTwo.kt
themobilecoder
726,690,255
false
{"Kotlin": 323477}
package com.themobilecoder.adventofcode.day2 import com.themobilecoder.adventofcode.splitByNewLine class DayTwo { fun solveDayTwoPartOne(input: String): Int { val lines = input.splitByNewLine() var sum = 0 lines.forEach { line -> val score = line.getGameIdAsScore() val rgbSetsAsList = line.parseInputToRgbSetsAsList() var isValid = true rgbSetsAsList.forEach rgbSetsLoop@ { rgbSet -> val map = rgbSet.parseRgbToMap() if ( map.isGameImpossible( maxRed = MAX_RED, maxGreen = MAX_GREEN, maxBlue = MAX_BLUE ) ) { isValid = false return@rgbSetsLoop } } if (isValid) { sum += score } } return sum } fun solveDayTwoPartTwo(input: String): Int { val lines = input.splitByNewLine() var sum = 0 lines.forEach { line -> val rgbSetsAsList = line.parseInputToRgbSetsAsList() var maxRed = Int.MIN_VALUE var maxGreen = Int.MIN_VALUE var maxBlue = Int.MIN_VALUE rgbSetsAsList.forEach { rgbSet -> val map = rgbSet.parseRgbToMap() val redValue = map.getRedValue() if (redValue > maxRed) { maxRed = redValue } val greenValue = map.getGreenValue() if (greenValue > maxGreen) { maxGreen = greenValue } val blueValue = map.getBlueValue() if (blueValue > maxBlue) { maxBlue = blueValue } } sum += (maxRed * maxGreen * maxBlue) } return sum } companion object { private const val MAX_RED = 12 private const val MAX_GREEN = 13 private const val MAX_BLUE = 14 } }
0
Kotlin
0
0
b7770e1f912f52d7a6b0d13871f934096cf8e1aa
2,093
Advent-of-Code-2023
MIT License
src/Day05.kt
coolcut69
572,865,721
false
{"Kotlin": 36853}
fun main() { fun parseAction(actionString: String): Action { val fromPosition = actionString.indexOf("from") val movePosition = actionString.indexOf("move") val toPosition = actionString.indexOf("to") val numberOfCrates = actionString.substring(movePosition + 5, fromPosition - 1).toInt() val source = actionString.substring(fromPosition + 5, toPosition - 1).toInt() val destination = actionString.substring(toPosition + 3).toInt() return Action(numberOfCrates, source, destination) } fun part1(inputs: List<String>, stacks: MutableMap<Int, ArrayDeque<String>>): String { for (actionString in inputs) { val action = parseAction(actionString) val sourceStack = stacks[action.source] val destinationStack = stacks[action.destination] repeat(action.numberOfCrates) { destinationStack?.addLast(sourceStack?.removeLast()!!) } } return stacks.map { it.value.last() }.joinToString("") } fun part2(inputs: List<String>, stacks: MutableMap<Int, ArrayDeque<String>>): String { for (actionString in inputs) { val action = parseAction(actionString) val sourceStack = stacks[action.source] val destinationStack = stacks[action.destination] val moved = mutableListOf<String>() repeat(action.numberOfCrates) { sourceStack?.removeLast()?.let { it1 -> moved.add(it1) } } moved.reverse() moved.forEach { destinationStack?.addLast(it) } } return stacks.map { it.value.last() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val stacks = mutableMapOf<Int, ArrayDeque<String>>() stacks[1] = ArrayDeque(listOf("Z", "N")) stacks[2] = ArrayDeque(listOf("M", "C", "D")) stacks[3] = ArrayDeque(listOf("P")) check(part1(testInput, stacks) == "CMZ") stacks[1] = ArrayDeque(listOf("Z", "N")) stacks[2] = ArrayDeque(listOf("M", "C", "D")) stacks[3] = ArrayDeque(listOf("P")) check(part2(testInput, stacks) == "MCD") val input = readInput("Day05") stacks[1] = ArrayDeque(listOf("T", "D", "W", "Z", "V", "P")) stacks[2] = ArrayDeque(listOf("L", "S", "W", "V", "F", "J", "D")) stacks[3] = ArrayDeque(listOf("Z", "M", "L", "S", "V", "T", "B", "H")) stacks[4] = ArrayDeque(listOf("R", "S", "J")) stacks[5] = ArrayDeque(listOf("C", "Z", "B", "G", "F", "M", "L", "W")) stacks[6] = ArrayDeque(listOf("Q", "W", "V", "H", "Z", "R", "G", "B")) stacks[7] = ArrayDeque(listOf("V", "J", "P", "C", "B", "D", "N")) stacks[8] = ArrayDeque(listOf("P", "T", "B", "Q")) stacks[9] = ArrayDeque(listOf("H", "G", "Z", "R", "C")) // println(part1(input, stacks)) check(part1(input, stacks) == "TLFGBZHCN") stacks[1] = ArrayDeque(listOf("T", "D", "W", "Z", "V", "P")) stacks[2] = ArrayDeque(listOf("L", "S", "W", "V", "F", "J", "D")) stacks[3] = ArrayDeque(listOf("Z", "M", "L", "S", "V", "T", "B", "H")) stacks[4] = ArrayDeque(listOf("R", "S", "J")) stacks[5] = ArrayDeque(listOf("C", "Z", "B", "G", "F", "M", "L", "W")) stacks[6] = ArrayDeque(listOf("Q", "W", "V", "H", "Z", "R", "G", "B")) stacks[7] = ArrayDeque(listOf("V", "J", "P", "C", "B", "D", "N")) stacks[8] = ArrayDeque(listOf("P", "T", "B", "Q")) stacks[9] = ArrayDeque(listOf("H", "G", "Z", "R", "C")) // println(part2(input, stacks)) check(part2(input, stacks) == "QRQFHFWCL") } data class Action( val numberOfCrates: Int, val source: Int, val destination: Int )
0
Kotlin
0
0
031301607c2e1c21a6d4658b1e96685c4135fd44
3,757
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/manalili/advent/Day05.kt
maines-pet
162,116,190
false
null
package com.manalili.advent class Day05(val input: String) { fun react(polymerInput: String = input): Int { var polymer = polymerInput var index = 0 while (true) { if (index >= polymer.length - 1) break if (polymer[index] same polymer[index + 1]) { polymer = polymer.removeRange(index..index + 1) if (index != 0) index-- } else { index++ } } return polymer.length } fun fullyReact(): Int{ val units = input.toCharArray().distinctBy { it.toLowerCase() } return units.map { testUnit -> input.filterNot { testUnit.toLowerCase() == it || testUnit.toUpperCase() == it } } .map { react(it) } .min()!! } private infix fun Char.same(other: Char) : Boolean { return when { this.isLowerCase() -> this.toUpperCase() == other this.isUpperCase() -> this.toLowerCase() == other else -> false } } }
0
Kotlin
0
0
25a01e13b0e3374c4abb6d00cd9b8d7873ea6c25
1,046
adventOfCode2018
MIT License
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/VersionRequirementsParser.kt
spinnaker
19,836,152
false
{"Java": 1483624, "Kotlin": 592931, "Groovy": 116064, "Shell": 969, "JavaScript": 595, "HTML": 394}
/* * Copyright 2020 Netflix, Inc. * * 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.netflix.spinnaker.kork.plugins import com.github.zafarkhaja.semver.ParseException import com.github.zafarkhaja.semver.Version import com.netflix.spinnaker.kork.exceptions.UserException import java.util.regex.Pattern /** * Provides utility methods for parsing version requirements values from and to [VersionRequirements]. * * Version requirements are in the format of "{service}{constraint}", where: * * - `service` is the service name that is supported by a plugin * - `constraint` is a semVer expression to be constrained ( >=1.5.0 , >=1.0.0 & <2.0.0) * */ object VersionRequirementsParser { private val SUPPORTS_PATTERN = Pattern.compile( "^(?<service>[\\w\\-]+)(?<constraint>.*[><=]{1,2}[0-9]+\\.[0-9]+\\.[0-9]+.*)$" ) private val CONSTRAINT_VALIDATOR = Version.valueOf("0.0.0") private const val SUPPORTS_PATTERN_SERVICE_GROUP = "service" private const val SUPPORTS_PATTERN_CONSTRAINT_GROUP = "constraint" /** * Parse a single version. */ fun parse(version: String): VersionRequirements { return SUPPORTS_PATTERN.matcher(version) .also { if (!it.matches()) { throw InvalidPluginVersionRequirementException(version) } // we use semver to validate that the constraint is valid. try { CONSTRAINT_VALIDATOR.satisfies(it.group(SUPPORTS_PATTERN_CONSTRAINT_GROUP)) } catch (e: ParseException) { throw InvalidPluginVersionRequirementException(version) } } .let { VersionRequirements( service = it.group(SUPPORTS_PATTERN_SERVICE_GROUP), constraint = it.group(SUPPORTS_PATTERN_CONSTRAINT_GROUP) ) } } /** * Parse a list of comma-delimited versions. */ fun parseAll(version: String): List<VersionRequirements> = version.split(',').map { parse(it.trim()) } /** * Convert a list of [VersionRequirements] into a string. */ fun stringify(requirements: List<VersionRequirements>): String = requirements.joinToString(",") { it.toString() } /** * Version constraint requirements for a plugin release. * * @param service The service that this requirement is for * @param constraint The SemVer constraint expression */ data class VersionRequirements( val service: String, val constraint: String ) { override fun toString(): String = "$service$constraint" } /** * Thrown when a given version requirement is invalid. */ class InvalidPluginVersionRequirementException(version: String) : UserException( "The provided version requirement '$version' is not valid: It must conform a valid semantic version expression" ) }
18
Java
172
38
a24bcbe15b13213e42a293658fce2cb5b1949835
3,271
kork
Apache License 2.0
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D10.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2015 import io.github.pshegger.aoc.common.BaseSolver class Y2015D10 : BaseSolver() { override val year = 2015 override val day = 10 override fun part1(): Int = solve(ITERATION_COUNT1) override fun part2(): Int = solve(ITERATION_COUNT2) private fun solve(iterationCount: Int): Int { var result = PUZZLE_INPUT.convertToList() repeat(iterationCount - 1) { result = result.lookAndSay() } return result.size * 2 } private fun List<Pair<Int, Int>>.lookAndSay(): List<Pair<Int, Int>> { val result = mutableListOf<Pair<Int, Int>>() forEach { c -> if (result.isEmpty() || result.last().second != c.first) { if (c.first == c.second) { result.add(Pair(2, c.first)) } else { result.add(Pair(1, c.first)) result.add(Pair(1, c.second)) } } else { if (c.first == c.second) { val prev = result.removeLast() result.add(Pair(prev.first + 2, prev.second)) } else { val prev = result.removeLast() result.add(Pair(prev.first + 1, prev.second)) result.add(Pair(1, c.second)) } } } return result } private fun Int.convertToList() = toString() .fold(emptyList<Pair<Int, Int>>()) { counts, c -> val code: Int = c - '0' if (counts.isEmpty() || counts.last().second != code) { counts + Pair(1, code) } else { val currentCount = counts.last().first counts.dropLast(1) + Pair(currentCount + 1, code) } } companion object { private const val PUZZLE_INPUT = 1113222113 private const val ITERATION_COUNT1 = 40 private const val ITERATION_COUNT2 = 50 } }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
2,011
advent-of-code
MIT License
src/main/kotlin/days/Solution06.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt object Solution06 : Solution<PairOf<List<String>>>(AOC_YEAR, 6) { override fun getInput(handler: InputHandler) = handler.getInput("\n") .map { it.substringAfter(": ") } .map { it.split(' ').filter(String::isNotBlank) } .let { it[0] to it[1] } private fun List<String>.toLong() = this.joinToString("").toLong() private fun winCount(time: Long, distance: Long): Long { val discriminant = sqrt((time * time - 4 * distance).toDouble()) val a = (time - discriminant) / 2 val b = (time + discriminant) / 2 return ceil(b).toLong() - floor(a).toLong() - 1 } override fun solve(input: PairOf<List<String>>): PairOf<Long> { val ans1 = input.first.map(String::toLong) .zip(input.second.map(String::toLong)) .map { winCount(it.first, it.second) } .reduce(Long::times) val ans2 = winCount(input.first.toLong(), input.second.toLong()) return ans1 to ans2 } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
1,170
Advent-of-Code-2023
MIT License
y2017/src/main/kotlin/adventofcode/y2017/Day23.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day23 : AdventSolution(2017, 23, "Coprocessor Conflagration") { override fun solvePartOne(input: String): String { val instructions = parseInstructions(input) val context = ExecutionContext() var ip = 0 var mulCount = 0 while (ip in instructions.indices) { val (operator, x, y) = instructions[ip] when (operator) { "set" -> context[x] = context[y] "sub" -> context[x] -= context[y] "mul" -> { context[x] *= context[y] mulCount++ } "jnz" -> if (context[x] != 0L) ip += context[y].toInt() - 1 } ip++ } return mulCount.toString() } override fun solvePartTwo(input: String): String = (106700..123700 step 17) .count(this::isComposite) .toString() private fun isComposite(n: Int) = (2 until n).any { n % it == 0 } private fun parseInstructions(input: String) = input.lines() .map { row -> row.split(" ") + "" } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
958
advent-of-code
MIT License
src/Day06.kt
emersonf
572,870,317
false
{"Kotlin": 17689}
fun main() { fun findMarkers(input: List<String>, windowSize: Int): List<Int> = input.map { line -> var windows = 0 line.windowedSequence(windowSize) { window -> windows++ window.toSet().size } .first { uniqueSize -> uniqueSize == windowSize } windowSize + windows - 1; } fun part1(input: List<String>): List<Int> = findMarkers(input, windowSize = 4) fun part2(input: List<String>): List<Int> = findMarkers(input, windowSize = 14) // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0e97351ec1954364648ec74c557e18ccce058ae6
842
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/nl/meine/aoc/_2023/Day1.kt
mtoonen
158,697,380
false
{"Kotlin": 201978, "Java": 138385}
package nl.meine.aoc._2023 class Day1 { fun one(input: String):Int{ val lines=input.split("\n") var counter=0 for (line in lines){ val first = line; var result = line.filter { it.isDigit() } val num = ""+result.first()+ result.last() counter += num.toInt() } return counter; } val nums = listOf( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" ) fun two(input: String):Int{ val lines=input.split("\n") var counter=0 for (line in lines){ val result = line.filter { it.isDigit() } var indexFirst= 999999999; var indexSecond=-1 var first = "" var second="" if(result != ""){ first = result.first().toString() second= result.last().toString() indexFirst = line.indexOf(first) indexSecond= line.lastIndexOf(second) } val realFirst = hasRealWordBefore(line, indexFirst) val realSecond = hasRealWordAfter(line, indexSecond) val num1 = if (realFirst == -1 ) first else realFirst val num2 = if (realSecond == -1 ) second else realSecond val num =""+ num1 + num2 counter += num.toInt() } return counter; } fun hasRealWordBefore(line : String, before : Int ):Int{ var curMin = before; var curNum = -1 for (num in nums){ val index = line.indexOf(num) if(index !=-1 &&index < curMin){ curNum=( nums.indexOf(num )+1) curMin=index } } return curNum } fun hasRealWordAfter(line : String, after : Int ):Int{ var curMin = after; var curNum = -1 for (num in nums){ val index = line.lastIndexOf(num) if(index !=-1&& index >= curMin){ curNum=( nums.indexOf(num )+1) curMin=index } } return curNum } } fun main() { val ins = Day1(); println(ins.two(inp)) } val inp ="""eighttkbtzjz6nineeight 5knjbxgvhktvfcq89onefive hnjcrxeightonejnlvm4hstmcsevensix trsdgcxcseven39dpmzs oneninesixtwo26 dppthreeh32twobhrqzks 1cxklgfbvhsnccfive4 foursgjsevenseven5five19 nrrk87 63ntkjbvcv3ntdcptmvheight78 7xv3one 3tzjcrfbvhtqctfmqmdcbjhxln9eightnqbcqztmxcthree sevensszlgdrlrhnptonethree3qvrxkbgfxtthree 3nckzkpkjsvztqkgvm99 fourthreeonesevencqdv2gnvblhr 528ksdcbx six342 3twozrfrtljql9eightgcqrgmbzz7dlcr5 6five2threesevenone65 4onejrg23sevensxfive fourthreecszzvhzfsevensix916 spqzvdxxjeightninejzbpzone7 cfivesevensix332lfpcffmld ninesevenhrdvmzj24bcxxz6 khpn3fourvhqmntjxfhsvrlnvc bfzxhzftwo2czsrv mmblpnnineseven4gtfvqscghfour 1zjgqlz five1ninetjjtfxqpdkgrxtgxrcsevenkfdzlh s8twoned 8fiveone53nineeightthree7 926xrfcjzvpd7 3sevenqnzjsqh6fnssjdsbv3nine rjbbsevenvzkghzsixsbjchs59 221fsnxtbstone1 seven9fourpdseven1four2eight two1nine4nine7 9seven7 fourcjmdgjsfive2l twokvhrdldggn15twoxfivenine mmjtldgmvq157hchsnvpbjvrvtvnineeight cgzeight3sjmhdcvlnthree5vkgfmx 8sevenfourgnxdpp62xx5 jgdk3z7mmkkjkm 9xrdltttpqznsljbvcdvtz 62zthreethree6 sjbxq9ptsvjhpzmxfoureightmdbnlsckfqlqr 91xrnsbxxsvk6brxfftpttsevencszfhsnrfive two9ljdfskpfive 1seven384 xbfkhfvlts8dhtnxhxgn93three7one1 3xkjrnqnqhgcfgjvfmxhghp15 nine9844 5onepczqjfcgfrbmtstbqbktphkvqcmbbvhpld eightsixhnsbnine1twonevrs eightcmbm2zbxsixone34 five99qccjbklfivevqskhpxzd seven9four2kzkjbrp ttdbhd4gqzdlqldnm 9cqcztfourrsfskdjf njttzmcrchfd4 r414tzqnfddrbf 4tzbfcjksjsn7eightonelvkjzkch ls7four 6eightsixrtkcrcbmqq6eight3nine onesix5five7six1 dvrqseven5ninegqthree4two9 fourgdkmbrlgc8 three7nine sixqrpzqvxd7xnbkftn5seven oneonerbpgk5ljpqh5threevtpkpfxtsv2 ljttxthreefour3three4gxzgsfm sixttjvhdggbk357 eightlb4 fourtwo4twonekzb 8one2cdsnrbfxbsixztcfour1 ldveight19lg seventpd84dscfmxj one34flpg6eight76 cfninepkscscc5 flqv5v6twooneprlprlkcbk qsqlrvmkq5457ninetwosevenm xlvvtxgspct4gmrgeight hpbbkqthree4gzbq768five 5dqfsixeightonenine seven4nfshmhvgqm4 rhfgvzxtfckbtmxtt9rqms9one 3gsgfbrnkhqrjddvlx59four2jfz fdl4two 9sevennine158 five9eight49 3mfsixnkxdbpdxqdgfdqnk six9fivefive fourjdmvlvkrp5seventhreejnqncmktwonev 8cjfqkkgtzlnine 3nnsevenjdbjfp1 ghthree1mhgtklfqdkqthree7seven4 4mqsstftj sixprblqsevendsxvqnk5 four45one dxhvj23188xz4 dcmnr2 xfoneightsixnine6fiveseven 6cxbbxkrxphsix 5ckkzlzjngvssfx 223zgb six4qsf hfxgsfhfhpjlvb329eightone 9zjkckhxoneightbnj xsdp23seven3four7 8five53eightthreenljbtgcnfive fnjn36 eightkpkxrvssix2lhctc 6ninebqcksevensevenhk 2one98rrtlncrxhllbgthreelgvkdf sixzdnlfrvvd4 lltjs8sixqbblmfdhctwo 6twonclq98sscjn six3niners7eightwokjj sixeighttwo1onerxrvvbfxxqmxnq9 conetfpbsrm81sixsgkfqk8six jbqs5277 kjbncjlqthxzlznld89bgqgkxfzpqsptwo onefive1 pchlnspk52one4sgqj zd3 43fsfplhgxtjthree7gs4npllqvll eight8sixeightone6onexr six6hqltskzpkgbggjktlzlpktdqhzdbnine9 eightnpfbmfninevgpjsleightxh3mz rninenine7nine fourbbjnjrbzdvshfeight62 3hzpfsfsdm 2vzhjbv6 27bpninejhbcjrmz7zfqf4 ppflreightpmztvhvonetnjmrxdd31one threeseven7 srf5hcxvhsmn5five onersvqvqgkfiveeightqxgrjgfcqj5ntgdzxp3zxdcmbsjqn mcb643fivetwo onermbkvmkc9pfvlpdhkzj 3oneeight64 qtnptg5two36nine2tprkbtb 15lbhtcqfnj1qgjk eightkzrnlrrnlltdmxlbxfourpbpghtgkb9nvlvsm 26kmmkz jhnldxdtpseven46oneightnb 4lfftjtbzvppxsix17nxpgvjkxd vszsbxdzjfourhlxldrthdzpqg6slnj8four nineone2njsfpcb 5sevenone6five jrmdhdvrb53onelgvlkd29seven qqqg7eightseven sevenm9 3dfcfcdb9twoqbvxjgt56six xq88jjmv83pspctxthree 38five5 six7rbrvjb eightlvqn335nine rgmfflzxzd9hs3foureight5 qm6qvmrone4 fournine8 two688qqdtdfbmzn5 8joneonefourljvbjntkngtskcgfnszpgxt ninethree5pjzcvntl984five mfgqzcjbglx7 ninemxnfcqrbjonek1nineggj 8dcfkfdtwo 4cltttbrlzpgzbdbqsevendtwosspqk 8eight9klmcbninetwozdcznsv six85pjqldfbqvclntpnqgv 1dgprzx53 4sixthreeh3fjqpggtjzq fourone8fiveseven4kgbs7 seven64npxthreeonefour xvntvgxv9twotlgcsbgsix4 hcqtdzthfour2xvqmnmgrncjt51 qhlpksvnntjq8 3rtmfngqccktwovpppqfqdlxmk2 sixfoureight9tqpdln3eightbjnqfldblnine eight2sixthree 3plpm 6two3two2 1cfszpnxgtk5fivefive8one lxrdvls2 sevenfqszrfhone5dxcqsq 42 3dmpsix9nhgzhbmknfour19oneightlng six2dfglxszbjone eightone88 9hffzxl7five4 seven8fknjk fivefoursevenllljzrvjf7 eightmsxfkbszh2 6fiveqhkttbsthreefghn4 3eight98vsnzbkvzcjfive spmzsdztzgcfbhvbzqlv5 fourtwozlsst9sevenjjmbmqk4 jtmlgrjcpkone2twockgc5four one35five4 four8tltpxqfour 57sevenbmhceightbhttrzxfvt qlvrrlnxgvjgnine1four2two sixoneseven3sevenm fivejxfghfp81two rkp3zbzfnrrqfour4eight eightnine7tpflkbqpz 28fourlmxlhdzctxkrsix 2fiveeightnineninexhfourseven7 mnlrszkr18tfive7l 3eight639 gqpbkntddpeight22lxqjqqone txxrdbx4bvsfxd 343nsctfvndmp93four2 9lqjvtjcrrtthree bsffrmtwo2fivesix qltdtgl3eighttwo91mjq rh4rddsfr fourfive7seven pbqmx7twoqdk 6onesixclklzfzsq992 kzxkxvqzjffourdtm4onefive6xoneightsnl k4snine4three39 sevenone2xcnscqhcdplnonekcxmgt seven7ninepmeighthqr8 xpspdx3twoqpc3881 5two5four8eightfive sevenseven2bcbsf 1sevenrjstpdxfiveseven 2zsxfivefivesix43 eightone5j99nhvbfqhzbvrv5 onefive35m 2kfnqftkkcxtskj twoeight8 1one8bzzsmgvj2kmqcnqjrz4 1one4sixsixbzbcglm fiveqqhbmnjgz5ninerlrxkl2seven 4eight4two1xgkb91fdzgxlp nine8onefive5scxlfrf gbrqllhnine9 1fouronesixfiveseven95 7qjrprpseightshfzfxvn 2vkbbxfrthreenineeight 58three4 lmfsgdzxnqfdbxtjsnp9 zlbqglfseventprsqvsmt1one9 fmksmtlc8dvhbtdvpfgdz 3six1 mkdthree67jkprftqhdzvjxxftthree8 bstlpptcfghsrrnine7bz 5m1qfscxncvkqgtf 62four16threeoneightg twoxlrhpc8n9nine q5sixfour ninesix2ninepzvxxlpcbxsfpz28hxtccfzmdq sevenccq4npgpkkb k79four9fp ssqptjqvld1pjfdjnkvsevenkjdzks 2bgpbgqfournine614 16threeeightwot five68jnhzdfqp2qlqbmnjmjdtfbj vplnzg4545seven two3two zcbhzsvc68cnppjpqhfl5 nine68seventwo8pfzgfzbsh onethreethreeknngnmzhpmlnsd7 46two sixhdg748blmlkbdtjbtwobgpzzlhzqrbvl 2smcthmql84seveneighthnmdkmfg 5fourrpscd3 sppzzjbckgsixone1sixfour ltkzb3v3ltwo four61nineeightdkgtcjfvds eightd5nfcvvdxhkkddhb four6q7thbpnz 5rknhshlhgnzz7sixone1six 327rkthreesixeight cnbqtvptwo1qnsevenpzqh threeqthreepmhgcqhseven2sevenggmpjcldz ninedlvlgnglqf3 4two993ninetwo eightzpfournine72oneseven7 ninejdfkznz62kflbvgpblcgchpzz 448 6rktvxxjpfpqtntbsonefive 6lngttwodshgtworkvvsrnfhjmvpvvbseven eight43gpssneight 6seven3threefourninesevenrnxx three22rblfvqjr1four5six6 xtdsqqbv43cxxvfpvtwoklhnqgjlkrrg threevpvxgddmhl576 3cxccdsevenmvzhqvpfn3btldbhbmfg kklcmgptl931threenineeight vj42ntvkrcjtq7sk6 llsvqthreefive5 xspgshknq3kpld2lfour6mhzrzvqf 4bfl38onesix9 seven1vjzjmcrrvnh 7sixsevensix gqnkgzmvpsnnzcvldlftrzhnpcbq6hzvbqbmnqvsix 5jvbldxsh jrmvplfive7mfpbsmklzfivefivelsm 8seven5nppxjfjsevenbxrmzmdjnine seveneightnrkconeqgjfkxjr532 m9seven7 vdn5hdghzvphfour cpceightwo3 sixtdxhninesevenmmzrpdqcp24 tghjrkhltwojgrcnnbbq1 cfrqlvsevengkthnsbtwo4twovffpv5six two6pcxj4eightgbctk71 five93nrqpshmxpbdnzssb2 jnxjdzm2xcfhnzkxxz948twonejv sixfive4four5nkdxzvd twoqvnxzgcg883fivejgvltjq4 7mzsqvrxlf6kpfjgvdpvj tzhkjn813six7 5qjbtklseven rddmfnjgdlnkx5fourzkxlttqdfourrrjfdd qtr2qrrqvhrkvmtqgbkdq five56ninesschfzxone lkb3 3zmbbqdqqnineeightlvlfqqxleighttloneightv 7threetwofive168 njxgnsqcpnine2 zthreerfnvvone7 three4one8 8ppmjj983seveneight9 p4 8tshsgmkb516three6four 7seven8 twosixthreenine6three gvqz9 n89ninethreesix8 ptqrhhvztxsjbxfour81lncqpkjt 8flvhqljqpmlf6fivenine28 zhbsl7seightwoczd four1pspgxdvtbzdcd7vsbkzmt fourj9sdnqtwotwonine3ftzrbzckqk 1fourkkfnndsdxnklrl zpcdvrszc4ggjcpngkqeight 6twonxhgzcsrgxtwosixvblddxgfmsmqtfcthree 6pltsptthreefive5jjqtzncslmxrmbv7 sixfourqfxtfour9onefivehsgdvpmdsfive ksevensevenonebdxdxffive5threeeight zztvdjzlnqtbrfccctsknppmx5seventhree9 soneight716 1fqnntfjhcj2threekmcpzqnbzlqps twopcftkx8twofourcsixfour 8six2sixgxzzhpkv four9nine4tgq htfmtchrx634four5zsmkmdv 45dltlvdvv dtl848three36 nine7sixonetwo8vsix twobxctmqvdnt96mnljbpxtsptjpznrjctgtwooneightqv peightwosixeightseven4 1seven8ds4five6pone zjftdkvpkpfrhzj97nine56 4sdcdr53beightwocjc onezxmtfive7ttbbttjeighttwo rlcjone3sixonezvbmzcgpk4eightwotnm 5ddmcsfzhntpnzntlllthreevqvct twoeight9 tfhmxsbf2foursqrrfourmfrzjffive6 dhhnlbkjmfourthree6 dxtkbxjlphpqcbmhpdfpqlmreight775bh sixklvmtjgsevennine33qgvplfourb gkjmcxsmhtwopkcszlrjd1onesevenseven 8xxvzzqvzszcn1onevmdfsrrtbbjgeighttgpmhh eightpndprhrf7 three7fpxtxghx fivenssevengrrlntzldl87 484sixjsxcmmtvbftrfive t8onesevenvqsfc2k sevenoneoneeightsevenfive71 sevennvnvbtzsnqggrsrgq35sevenfive7 feightfive12 twoc846cf 1mtvlxhhxlsdbphgltlgzpl xddrlslrdl9 fiveqvfjvcqlcfour27 9fjqp9rrkqbtpv3 23fqccxsvsix94tkzsqmrhsg 6lvrsqnz 9four7hvlfl9 gbgsnmkrxjxpgnj828 56grzmb6onekf9six 87bjn4 sjdzmqkrlkbsmxzsmn3 seven91eightsix svhfnxzdzqczc2 vbnz92chjjfqftxfourqzzxseven seventwofour5jbqvlmqknbznfbhtonefour dqdmntkfsnbmjqxxgmkvm6vqpgpnnreight one1431 1five4 twoone8thtxlrrdxbone qftpltmjd1zpxckthreeeight 9xg pjpdjrkltnrkkmd9five75rdctppdhjtghrffczdx mtvbhnpzjfive7nine thlzdgxcqvsknczrdslsh7 eighteight4kkt7four5 71ninekzfntxtjthreeone3 gzseven2fssqrgmbj 52j nsv16seven stwone1 twodbqgfivegsrrvxvone3 jckhqbdlvgbgn7vtx3vggrdm ntzftfhfeighteight2 48eight6 flzfqonezvskbf1668one6 sevensix864eightfour3 dnsdrsxvcxnsevengxrszqxfnd4fmnine tjjngfourhdfzpfkh24 foursmgvlqjxsqmz8ninekthktdhz three435 tkfqhpz8zjmcqbxcb46 mmvstlmln3kxnkvjcmxtrdxp4seven rmfour13vkgnnmbzbzgd three6nnbljchmzthreeg 68onep9five1one2 rbvzvgmkbmdrnmvone7kqtxtrtbone three13six4 qksfrmvgztsfournnvp66nine 34three 11fourpzkmqnfmjqkdgrlgqbsixsixcqtgdggbdx nineone2seven4twoninesix ninez6qpnnbpmcdhcr sixbdbkhgntpsevencpn3 1fivehvlrzpninemkfbfgtvfivesix3 7kpeightzlvqsgkfjznpfpfsseven66 c7hxrgkglfivebfctxk 5rfdxgshzmnzqscpqzlbnrhbg9strxdthree8kntkhdpdll 4gfzcjcjsm63fvxpvflv nine8526 6scslfpnrveight1seven5bdllknjj seven94hnxddjv26s two48seven3four58four fourseven1smh5 1zzdzmbjpjfzlhsvzgxf61gvtnklgx6 ninefour63 nine3nrfzn gthreeseventwonine1eights sdonejzdmtxtpl9onerzztvqr8 eight15kqnjrggpblhsbdz1 lkkxnzjrgsixsixthreeeighteight4twonem d17two44 6seveneight1fourthreesevenbdpvg cjgchvhq4386five8 1threefive426rsxmthree8 sixnztppjtn9twossfjrdkzkrldztfbbv threesevenlqrdmvzdcphmqj3four5three fivethreepcfxdxmc3vdbprghd5sevenszprlbzrbn threethree88xcgdmrcssevenrlflv39 eightonezchscllpfone9 zreight6sevennine fmrhqrxr7 sixnlqccjchpxpqg86five5 sdpxjrxtk4sevenfivetmddbpqgtqffive2 hrvrgjgvxt7vrsr 2zj8 35fourspthreeseven3zgddrmbxmsz four8kkxmtsscf 4six98 five9four four5one7pjbninefourbmss 4sixsixt138seven fourxsevenseveneighthsgmmpdx5 tonexhgcjxbjn8 chbkd2183 six8fivefourglszgngfgqthree pghkzrftwo6 fourpfx572 62zfvzp sixsixnzvtxdgsixzxsgmpz1zvtwo4oneightpg 425twothreebv4twoxbx 8nineeight55eightflkpggltsr4spl seven45clkrkrxj 65six594twofive 4ktvpfjeight nnslpmkqc5five5four nineonetzmft8jcxqzrk fivefivethree99 2l2 4mhdj 3eight7fivejqhvrszgh3 5four7mbfz8 one8sevenmltbgqcbq22 1zgfnfvt9seven 2lhbfrndhmfiveone fivekzgch424zbpgxhtkbjdljxkxvnz 1vd6vpmzjmnhhn vlqcbhskb5onerqbql6 six3tplqcxthreethreefoureightzldgvgxrthree 4fourtwo4 cvznvxbxlszjpxvzbqn7gt2fjtxddzmjv kjqthree67twosixfour4nine dmjrhflfzslhkjmthreemfgqvzcpm9bcnfbpz nfpcsevenone3two58 eight4kdqczz96five1four 1mzfour 57tdcmtmns4 bdxeightrjvkrddrm3nftmzxlftthree 2three2kvfourgrtvxmrzgdninecseven threemxpfnthree5onehjdxfntvtzlxhr 8onelqtjpkmtwotwoseven91 rzhzg1fouronecqkdpfkgdkkftsixhllvphvtjv vxgrlptk48one14two kqncz3znmkppxs3hlggbmsfj81 ddrp3 three8hjdccgthrtbd6lvhnbfivemzh twomptzvkqmssix7bjvpsix6nine phrdjxmzj3xxkmfour7dsix 5threeshtmlsjbmfzgdq 96eight three6rqqxgzthreejphvs 69seven52kmnpbqmjdhtjvxcnlxfgldbs veightwozbbcmqrdxv6hxxpdknf nxbtwone1vktdvlbbhnfour 4five864 2dn1fiveeightthree two4twofoureight43 1eight51 71fourhjrnqssxqvf sevenqxkccdxndfgqhctsfsx6 xqgsjvdmnb31sixfourtksqshz5 4ghkqfzxceighteight2eightfiveeightwotf ninelsnldgslfxfqfsrc24six 3seven3ctbf9eightmshd mbqpfourfive44sixbnmqrmkgxt flgdrvjj4dks oneqslfbjgfx8 jmmssm2 hjfbzsix1 bvjdxseven8 fivenhfccvg9 four5sevengkvslppponerhlvfms b9one 89znlhgbnkmmxsix3two sixsqtjcdfbs87ninejvznvmeightfvst1 sevenktnzdkcsrzzdqtb9jnbtwotgxsptxcd5 6mqvbhsddnmb21sixskg8 threenb2four74five1lcmdzrvq ftvone7 5msevenpdqgzncvzxeight foursixpshnbrpm64 six2twotwordzf nine7lbnxsfjtbb1seven4ggt4 zlnfkkconept36 9sevenfqlxjmts94xpcxqseven foursevenseven15ninedqff1kmzfgvnks xktjdhb115 threeeightcnlpzrb8 91six 376kkgmlblrcbthree7jgxvgfcdv 9xpz3 rrcvpkgtwo2one6vjfone24 sevenhfour3three pxfvzltqrg9twotwogqdtzbp lrgseveneight5pmxvppjdhtwoone 97six four8bjdhpmszdeightprkgone mb6lfcdkcn 8fbvxnjone z9vdthreethreesbsrkzgnsxp8 sevengftjmm1onegqhpninesnr3 f4fourrbbngrdm37five ninerbmdqfvkfx9eightone8eight2 rxdvclfr714 oneggchmt2dgh7 tvbfour9four four474fourgmdtm nffourpbxtlcs7ninethree3 bpjlrztwo2sdttcghc hfflhmdc18 4ninepsrmtbqrfeightk3xxxf 433hdvcggkr1xjcntvtnvsc 7nine2nine6 9zctwo 9vvfjvctgtzpjh7jtdjcrh qrtgcd5six31khd5 fourbjshrq845zg ghconeight35jljdqgtg4fjdtxtsfiveone4 one7kxscgcxnsx 43threethree54four vmninetwo2onetqgblrsgcpfkrreightwokg threefour38 fivesixeights26three jtmzzxvmxone2four9jgtxjrvpcthree fdqgczkq8sevenvcnhpseven8three88 7ninezone3 frj4eighttwobgx1threesjckzsvvxlone oneseven2cspzhqfsix4 ljmnbbcnxffkmdn5 tmzlnl8oneseven86ninelbrzjgqn fthree3seven6sixtwo34 6two8fivexteight 89seven5twosix63 63pzsjcjzvbhseven msqvppsgnfbjrjmdrrhbfxrjqdlkpfourjbrjks3dthree eight6twoklkdfgvxzteighttctqz 4gjpfmqs233six onefourninenxcnkgfour8rmmrzln 1sptlpstqb6eightqgfhzzgpgp24 eightlrjlhqfoureightjvj937 595oneighthpt 44five two2sevenbtwo 7fivefivepxonebbrlthreefive klxnlfjlsrgjcd7eightninefive threeqzpptnzhjnkqfsixpvk3xxlrpl mqkhsdtbqqzgjb7149ninesix 1dbrrvjsx34cbdxhqpzbfhtgpm9three 3onesix6eight five34 6qcv9nzngtsjv 9lttthreegttzjstt four47 95onetwoftdzmhsfmhbnblnine chcsqhnp72qjdqtjxzc8fourfourfour fourfive28 81eighttwoqdjkmnleightdbmzz vzzqpjx8 qq1six qbktqgrjcqq75 772 njvnhnzdz6threefivetwonelt pcfzzjfhqkxhfpztpv7 fivemztfourqjrtngrkpcbfc3qq bfjhbm6ghtdpsmlvb86eight 94883 6onegbxmcqmdfive sevenonesixcngsrgcz9 sevenzhxktd22fourgnr9 tdxpzvggnlpdxxrcpsp3threexjrldrkmp 34kjtbsxppmxfoursixlbzgqxbltv fivethreezfive2 7seven1seven 4fhvxbg58eighteightone 631gqtwosix xqn1chrcjjrqxp4threezjcd jtssvppxlnsix49rfvjdzntwoone sevencmpmdnczcfdprgfdbjnzzkgnine26 hkbnggqfk7mfmfsone68sxpdmf fourtlhsmksvzg4foursixseven pprkj3sixseven kzxjpdczxhxckxtgbbtwothreethree5dztmdfrlfivedgcfmmrt hjvrdhnckspl5eight3three9 74two95eightfourdkzzlkxszm one7tbfour1cpjtrxsqgvbjtpbcct2 fivefour4hsix8hjsxrmpqqxnkhmjseven nine8fivehvmnxsfour7four75 sjfrjr2ds fivefourqt95vbndnzns665 sixssbznthreethree6f8lnzcgpprl ninepfbpfnflrfnpzhq9 nh9fvrldpkjmq7six5p 75zsixnqbhrcbpmddshjfqthtq sevennine377fourfrtvpqrseven6 97eightnine 52fiveonetrq5 threehgjqt7rvfsljtzkfour tjkxc1 jthreerqbpzpzmeightntjlrhdmfour2 fourmgv2three4one four91 9bone oneseven1sevenpdvdqhlq xlhbqxcpfp7 twothreefive43 1ctjmfn9one2 htfivesixcdkjrjbr45eightseven onefour8rrhltfl897 37ljvmcnjhonevxkqpjk 3891sevencfgjhh45 twoone5tbznkdmv1fourpltvnnsvk19 55bcnzbfggd2 17zpskbgeight2dx3 vbdshtdkxllttwo65 tzvmcmltfphztpplrxjxpbnine3qvktlctfrpxncb 1sixppzlfvkbnm eight1gdvlzrfkc four74fivefseven hlzlvnjrp9312jxeightnine1 sixsevenkjpbz5sevencksb2 9rtvlgdpfnmgzdzcjggsq7sevendxglftncmbninefive eight8gxkrbkgcvbxbbxlonefivesevenjnffhjsk 99twobdmcnfthreevr sevenlpjbbthree58 eightthree32 14fhxsqshmjbngrhdzvxvvhxgvqnlxnnvrsgsheightninenine 6twotwo kr573eightseven78 9six18 2seven8six1qdvf ones9three1lcqj2 sixbfour6gbd tfpvtbbjtwormxz6 49eighttwoonesixeighteight fcrhntggdvseventhreeeight9foureightxjxqvtb oneone3rnngppxj8fzpsncjmzn 9fiveonejjdpthreetwo9 sixsixjzckvmbbszsl1nrrfphj5 zgjvnttth7sbmtxczggxbbqpzq467 3mhslltk 9six16three79three fxprlhbm3zljzd49gdsrtt 6eightoneseveneightfourrfive fourfive11six 6gmrfxnsmnnljf8ninenlctx seven5threehninecnhbkgbnvqbsfx pxzccjqz8 xgzpzljnfour7threethrxskjlz9 fourseveneight292eightone 5bjpzjseven21four xbtf88nine 6nfjllxh4 67five4c8 1qbzdkvmlrzgj3rzqczz4 mjjzblg3 x3five jrpxsrqgr9hqsddmscmsrsbhkdc63eightxfscd 6eightsixone 5dggfbgclz7htvpcx1 onethree46psdlfpgbsix lqbnine978 7nrrdzfksbtjlnbgfxttzfourstqkd mtfptwo9six23hctpbrxtbx eightfznvmmp7cllpkggknttwoxbbv rggdrlsgcm2hdljxzjhjrfour83 vhtmhvjdzzkzmzqgr7fourfourfourgzbqqpz dfjctmlnkqzzjhhltpvhfmhsixvclfive7vgm9 nine642sevenseven9mblrhxxktfhdhbcztvx 4rzrdfmtvlpthree86 qkdoneighttwo1one3 dnnvkvpcmn2cltbzc6five59s sixsnzpnfplrn38hthhbfive4 tsrxkzfxcdgckxrgzkmrctqvrngfnvdscnpc6jgszldglnhsg vvtfhtgxjbdgznjjzqjjclfg1lvpdcpjsevenseven3 xrhbrpg8zb8 4nine5qfxlhmvzsjsbznmklseven lffl2six733jtrfrs3 7nbvpkdpzjtc8qckhbqfsqqgz cfljnthreecninedt2xldzbgl5six nrggf7four hbkpxrxonetwo969fivethreegspmzcfr jjpmzlzfvqbvbzqcz2eightninepfqjkjrkfivebzcthgrpqx xsccsbmcninefive4kkrvrht sgnzzschtwotwofzjt9seven 8tworpzncglnmninenjmf368 2one1zjtgllvsone 7nine4nqqxnvvnsbsevenvddcvfdr three117 shcjhvrfourpthree12 1zxcxninegpdfrfhzlbzg 7eight9gkkfbdhplnmjkksbqzp6htmbhg sixeight76sixfive 5twonemt three86 4three52psgzhnlhgvgcsbzbleight5oneightkj cnztwone1 six9sgx 79clrpmeightninepkh39 rmfplpsixsixlvrdbqgpljgl5onetwo3 7ninelznqjxjgtwohhk6five 1659two7onefive rskpnrmfbbghttvklkg773fourczdqeight xftwo4 2nine5ccrgsmfcseven9seven52 8sixseven k33threehgqtljcdqxkl hfgdvngttzfivecflmcc31three eightninethreensjxxlzhgk9b51x ninejktfhnnphkkgm2dms5dpxrbcd eight7skzllgxgmkd1three4thhdpsjtvnq 7ninehhhdngbxjvvxldvbrhzrbvntl2 pxgsixone75llslx 31tgrvtvvlbhnshjfgnqc knzgkjfckf2sevendfive bmxcnznineeight9dvkbngzmxz gzqdjfsxq9pbseven 212 h3 9sixfourbrfsfivekttxzhrmdsppps 3vxtbtrzqzxfhgsksbvqd 9lbxdjmckrhfgjqlnsrrfzqxktqkrmmjshfnine 7pjmmxdcffxgspeightgpdcftjtdxjgdrfthree t84ninefive4 fgfour63sevendmtrrc9 64three btjnc3g6f3one pm9 threefourvjmsx5four 14one2rtcccqc jhcckpv84xntpzdn rpjrhgddzfvrzpqnfg5twoseven3threehvcmnkreightwotl 74one six4ninesnbxlonesix5three kfxjzjone76xppxgddstgfhxphpffrjlone sixthreedsdccpqff4 4951 zszgqjxbx7 three4pqqvfzf622 vc77threetd sixlbglxqhn52 1sgktgvxp bdsonekxsevenpgssslcq3fgp7 pvnxnhdjmndnhthreefive49 kgvkszsixone4 3mjvqjpglzhphg67ninehnnine one6xvvnvkxp4dfcxv eightfour7threesevenp 7ggdl1 ztwonethree427ninetnmzntj4 fttwone258seventwotwo 75sixseven59 7kmfzqgjpqkpdhthjlseven674xdgmphfk eighttwo6five7 3eightwoxg 22434five khjmcpzvfpr9 3rrzqzlrljgcvdnxj6four8six 63qrgqklszpgthreefkpzx 574htclbtzfivetwo jtwofqfpkflzt9 xnjzxpmmdln4lzlmlk41 6jdzjjmz7jt7seven8fourkgttztbsktwoneps 72s166zpslq5 3553lhkdcxvhqbddrfdbc5two 4gktbmone fouronefives3qhglmzttwoeightone one87rxkkhfrjfrpdjjt485 one437nine 119one 5lseven87nmxxqvhmn pphfmcfhxlsevensqdmtvtpvq1 18eightfivefour three98 4onephzhtq4qc5four 26zglkpjvz3twoeight 7mxkdrbpnk29 ppeight15 9jnprvtmscsixbbpsixfivecktgvdpf5 lbftvcngvkvxf5cmmrqljjb471 eight3knrvtwo one6pvbpkqkpdsixbv eight2onethree6eight 5rztcbtfjkb2twoeight39hxppvpxqg 8threemlllncmfourthree vhtsmncssixbmlpggvmlzdxbczgc1fxrgvsbhsrbs ninebnpv7575three 4mthree fourtwo1qrbfourjrjmlxjr 3jbkcsrqznc8 pcgrxgf4eight54 seven5mjk ninenine6vmcmlxmcrbvq1nine8 sixone2ninesixrdqfgpxddzthreetcheight 899lfbzhgn151 46nineone 7one2qthree nine2hjnfourninesixvblnqbgctwoeight qkggsnnthrxnrccbgs583 351zkxqtmbd9sixthreegjjxt zrchlhmqcthreeninesmxz9 219fivejrxgbjvvcxkjtwoseven 8threebzzsxdx nine249ninefmlhj8rfour 16zfljhfdcmkthree 7sixjvdqgpvhmndpmhhzsphceight two2zjqc4nfd6732 41threeseven1fourseven 296fourgnq7three tbzdhbhs7ntshptcgrbkjspjdz 55qcrmclmcck9 25mhmtb3dscmjbhgv3four bjmhkxsffourhnxkxv1 jvntlbn5fivegjdcjl 7gndbbbneight 357623chktvtfzvf 169plhsshseven nhgsrxcdfktpbzf9vpppxzkznine9 xrdnlbmtdeightone3threeeighttwo bnnqzcfoneeight2hhdfkrrqzt 342tlmjgtfcnine 47rvtfqlzgmjlqbqthree 7gnmxplrjbvfour6 mcgbldbhlh1eightnine two9eightxnpdj61kzcdpnpnpfgsdrbcflh 6541fourpkdplksnkpvkjxpdnvfttlfdflz kfour7 x4tpbnnvnjlseven 55nineninesevenzttsztwo9nlcqjq 1drhjrzsbvpl mpknzhj9vmqckrpznqthreesj9 211zqgpdlmpn 4jxzrztg5onehnzvdbtcqdtsnkqtdvsd1fournine bvcrcz5four4 4nineninecfhgtdphone9 zbkjgbshqqkrcb3qmtfmdrdcckcsxshjb2 1eightrblhbhljvkpshmrxc5 hjcrrdsvnbqktxrgmq9nqgcztbv 6lzsixl5one twofivesevenfivesixonenine5seven fourmldkgnzb8djlsdmjnzxbmmvpf59seven 8hnfkknnsrhm three2krtqmmxqzs4jbrnrtrxzxsllblbkjmthcrlxxkdlh mglfmvvnthreefour1 onehxz4fourhqcfvdlhg zrzqdgs5jsttkrone sevenrdmhnldsmdnineqfrgjhmhnnqkztxzm7 63seven 2seven3mrsltqb17 fdbtvthmmrb5gbxvcmtwosixt5five eightlzglvxfone5five7dlqpmseven5 dmzdkbfive98onefivehhbljrnz eight8ninefour 24nvmftwofive seven3onefourrmgkxtcsfour fgpxmqqsfdrk8eight8zhcrzvrzmdxbbfive eightonetwo7ninesjsrlr rrkrrtnkq941sixone threeffspgv3eightfivesix5 lthnrlgfcnine2scdcvnineseven sx86 cxklrckbz5lsqq28 5seven298 933five5cmddfj46 hrhhs76343 one3two4fourst4three nine3three dhtscvgm9foureight81vp btpeightpzbtphdlcm8fiverknbrhthreelxndqcv one96six45tm fourninetkdrvnbznnine22 vxeightwothree5cd3jcnine seven5one4one7ninefive3 nflkr2dlmtsrkrgkfvsixxvznjbvz3btxkhhqcc eightrtz6jslqxsixoneeightnine xmvxn5 tgnlrmjtkjdpbnpmsixbxfnl7sixone htwonezcshpqgsix73qlgdqnkjskjthree nrlkxq6fnfourseven zmrlngjdhc41four4fourptrhddthreenhzv n9twogdrzkcsbk8hph6 436sevens7cnkrrk 6qkdvkhtwo mztkszm39 fourtwo4mqhjkkdzgffhqfktwonine hbthree2hvpbznlgrxfgkthfour8 34prfzlx4three 29zzfdvghll9three6 two83 one982 36hhgdf7 seven6ninednnine9mbtzfm1 one38 seventhree5lsjxknqtdsbtxrkone eightmfctkbc9jlxgdnchlq9one8nine p371b 9ninejszqsnpkfbthree1h5xscpfzvl three9ljd fbbv9 five582 58dctdbhbninesixczhd qp4 6pfqdeight 3onethreekqnnlt m4fgbmdtwo3 twodkrmtqs4 9three6 six1798nineeightsqpvpsmcbmh 9qxxmrmbnine3fivefourfive3four one7sevenone78ninetwozqps 973keight9seventwo keightwothreethreeh6threeeightlnqdzhlt five94 mqlltnfive8eighttwoqhztggvqqkcxgvgmch 2kpnsevenfive6 gtmszpsjmggr3 pm126one3 rvcqbtz9zjtndbxlrdcxzf3 mkninekhmtxzbjpd8threeeight7eight 5274xm636 bleightfive9vdddzjdntthreerxtvdslrvbcvf 9eight4sixdqzrltgpzlpxtcrzxbhmsmdtwothree cpneightwofive3fourtwo one61threejxbjvsltxzpntpv 19581 six2qllhlxhr1foursixz8 6278teight3three 8gstxqdngxzlxvnvphlsznr3kknftvzxcqqbrfteightthree 4jlzjvjfltwo7pv 7dvt blhsm4xcrbrf68ninezvhhtqgphnzxlhl 9dvjvfourtcthree onethreenfkgrvsevenkczctlgkt7"""
0
Kotlin
0
0
a36addef07f61072cbf4c7c71adf2236a53959a5
23,764
advent-code
MIT License
src/main/kotlin/days/Day9.kt
hughjdavey
572,954,098
false
{"Kotlin": 61752}
package days import days.Day9.Direction.DOWN import days.Day9.Direction.LEFT import days.Day9.Direction.RIGHT import days.Day9.Direction.UP import days.Day9.LongRope.Companion.INITIAL_COORDS import xyz.hughjd.aocutils.Coords.Coord class Day9 : Day(9) { private val motions = inputList.map { it.split(" ") } .map { (dir, n) -> Direction.values().find { it.toString()[0] == dir[0] }!! to n.toInt() } override fun partOne(): Any { return motions.fold(listOf<Rope>()) { ropes, (dir, n) -> ropes + (ropes.lastOrNull() ?: Rope.INITIAL).move(dir, n) } .map { it.tail }.toSet().size } override fun partTwo(): Any { return partTwoImpl(motions).first } // expose this for testing fun partTwoTest(input: List<String> = inputList): Pair<Int, List<String>> { val motions = input.map { it.split(" ") } .map { (dir, n) -> Direction.values().find { it.toString()[0] == dir[0] }!! to n.toInt() } return partTwoImpl(motions) } // todo refactor/simplify this method private fun partTwoImpl(motions: List<Pair<Direction, Int>>): Pair<Int, List<String>> { val coordStates = motions.fold(mutableListOf(INITIAL_COORDS)) { coords2, (dir, n) -> (0 until n).forEach { coords2.add(LongRope(coords2.last()).move(dir)) } coords2 } return coordStates.map { it.last() }.toSet().size to coordStates.map { LongRope(it).getPrintableState() } } enum class Direction { UP, DOWN, RIGHT, LEFT } // todo refactor/simplify this class data class LongRope(private val knots: List<Coord>) { fun move(direction: Direction): List<Coord> { val coords = knots.toMutableList() coords[0] = when (direction) { UP -> coords[0].minusY(1) DOWN -> coords[0].plusY(1) RIGHT -> coords[0].plusX(1) LEFT -> coords[0].minusX(1) } for (i in 0 until coords.lastIndex) { val rope = Rope(coords[i], coords[i + 1]) val tail = if (rope.touching()) coords[i + 1] else Rope.tailMove(Rope(coords[i], coords[i + 1])) if (coords[i + 1] != tail) { coords[i + 1] = tail } } return coords.toList() } fun getPrintableState(lowY: Int = -4, highX: Int = 5): String { return (lowY..0).map { y -> (0..highX).map { x -> val atSpot = knots.mapIndexedNotNull { index, coord -> if (coord == Coord(x, y)) index else null } atSpot.firstOrNull() ?: "." }.joinToString("") }.joinToString("\n") } companion object { val INITIAL_COORDS = listOf( Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), Coord(0, 0), ) } } data class Rope(val head: Coord, val tail: Coord) { fun touching(): Boolean { return head == tail || tail in head.getAdjacent(true) } fun move(direction: Direction, n: Int): List<Rope> { return (0 until n).fold(listOf(this)) { ropes, _ -> ropes + ropes.last().move(direction) }.drop(1) } private fun move(direction: Direction): Rope { val afterHeadMoved = copy(head = when (direction) { UP -> head.minusY(1) DOWN -> head.plusY(1) RIGHT -> head.plusX(1) LEFT -> head.minusX(1) }) return if (afterHeadMoved.touching()) afterHeadMoved else afterHeadMoved.copy(tail = tailMove(afterHeadMoved)) } companion object { val INITIAL = Rope(Coord(0, 0), Coord(0, 0)) // todo surely a better way of doing this fun tailMove(rope: Rope): Coord { val diff = rope.head.diff(rope.tail) return when { diff.x == 2 && diff.y == 0 -> rope.tail.copy(x = rope.tail.x + 1) diff.x == -2 && diff.y == 0 -> rope.tail.copy(x = rope.tail.x - 1) diff.y == 2 && diff.x == 0 -> rope.tail.copy(y = rope.tail.y + 1) diff.y == -2 && diff.x == 0 -> rope.tail.copy(y = rope.tail.y - 1) diff.x == 2 && diff.y == 1 -> rope.tail.copy(x = rope.tail.x + 1, rope.tail.y + 1) diff.x == 2 && diff.y == -1 -> rope.tail.copy(x = rope.tail.x +1, rope.tail.y - 1) diff.x == -2 && diff.y == 1 -> rope.tail.copy(x = rope.tail.x - 1, rope.tail.y + 1) diff.x == -2 && diff.y == -1 -> rope.tail.copy(x = rope.tail.x - 1, rope.tail.y - 1) diff.y == 2 && diff.x == 1 -> rope.tail.copy(x = rope.tail.x + 1, rope.tail.y + 1) diff.y == 2 && diff.x == -1 -> rope.tail.copy(x = rope.tail.x - 1, rope.tail.y + 1) diff.y == -2 && diff.x == 1 -> rope.tail.copy(x = rope.tail.x + 1, rope.tail.y - 1) diff.y == -2 && diff.x == -1 -> rope.tail.copy(x = rope.tail.x - 1, rope.tail.y - 1) diff.x == 2 && diff.y == -2 -> rope.tail.copy(x = rope.tail.x + 1, rope.tail.y - 1) diff.x == 2 && diff.y == 2 -> rope.tail.copy(x = rope.tail.x + 1, rope.tail.y + 1) diff.x == -2 && diff.y == -2 -> rope.tail.copy(x = rope.tail.x - 1, rope.tail.y - 1) diff.x == -2 && diff.y == 2 -> rope.tail.copy(x = rope.tail.x - 1, rope.tail.y + 1) else -> Coord(0, 0) } } } } }
0
Kotlin
0
2
65014f2872e5eb84a15df8e80284e43795e4c700
5,830
aoc-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/abc/198-d.kt
kirimin
197,707,422
false
null
package abc fun main(args: Array<String>) { val s1 = readLine()!! val s2 = readLine()!! val s3 = readLine()!! println(problem198d(s1, s2, s3)) } fun problem198d(s1: String, s2: String, s3: String): String { /** * 辞書順で順列の次の組み合わせにarrayを書き換える */ fun nextPermutation(array: IntArray): Boolean { for (i in array.size-2 downTo 0) { if (array[i] < array[i+1]) { for (j in array.size-1 downTo i+1) { if (array[j] > array[i]) { array[i] = array[j].also { array[j] = array[i] } var l = i+1 var r = array.size-1 while (l < r) { array[l] = array[r].also { array[r] = array[l] } l++ r-- } return true } } } } return false } val set = (s1 + s2 + s3).toSet() if (set.size > 10) return "UNSOLVABLE" val dic = mutableMapOf<Char, Int>() for ((count, i) in set.withIndex()) { dic[i] = count } val ss1Idx = s1.map { dic[it]!! } val ss2Idx = s2.map { dic[it]!! } val ss3Idx = s3.map { dic[it]!! } val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) do { if (array[ss1Idx[0]] == 0 || array[ss2Idx[0]] == 0 || array[ss3Idx[0]] == 0) continue val ss1Num = ss1Idx.fold(0L) { acc, idx -> acc * 10L + array[idx] } val ss2Num = ss2Idx.fold(0L) { acc, idx -> acc * 10L + array[idx] } val ss3Num = ss3Idx.fold(0L) { acc, idx -> acc * 10L + array[idx] } if (ss1Num + ss2Num == ss3Num) { return "$ss1Num\n$ss2Num\n$ss3Num" } } while (nextPermutation(array)) return "UNSOLVABLE" }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
1,900
AtCoderLog
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem1572/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1572 /** * LeetCode page: [1572. Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the number of rows(columns) of mat; */ fun diagonalSum(mat: Array<IntArray>): Int { return sumPrimaryDiagonal(mat) + sumSecondaryDiagonal(mat) - sharedCenterValue(mat) } private fun sumPrimaryDiagonal(mat: Array<IntArray>): Int { var sum = 0 for (index in mat.indices) { sum += mat[index][index] } return sum } private fun sumSecondaryDiagonal(mat: Array<IntArray>): Int { var sum = 0 for (index in mat.indices) { sum += mat[mat.lastIndex - index][index] } return sum } private fun sharedCenterValue(mat: Array<IntArray>): Int { val noSharedElement = mat.size.isEven() if (noSharedElement) return 0 val center = mat.size / 2 return mat[center][center] } private fun Int.isEven(): Boolean = this and 1 == 0 }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,111
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/github/mmauro94/media_merger/util/DurationUtils.kt
MMauro94
177,452,540
false
{"Kotlin": 218767, "Dockerfile": 357}
package com.github.mmauro94.media_merger.util import java.math.BigDecimal import java.time.Duration import java.util.concurrent.TimeUnit fun Duration.toTimeString(): String { val abs = abs() val firstPart = (if (isNegative) "-" else "") + mutableListOf<String>().apply { fun add(v: Int) { add(v.toString().padStart(2, '0')) } if (abs.toHoursPart() > 0) { add(abs.toHoursPart()) } add(abs.toMinutesPart()) add(abs.toSecondsPart()) }.joinToString(":") val secondPart = if (abs.nano > 0) { mutableListOf<String>().apply { var added = false fun add(v: Int) { if (added || v > 0) { add(v.toString().padStart(3, '0')) added = true } } add(abs.nano % 1000) add((abs.nano / 1000) % 1000) add(abs.toMillisPart()) reverse() }.joinToString(separator = "", prefix = ".") } else "" return firstPart + secondPart } fun Duration?.toTimeStringOrUnknown(): String = this?.toTimeString() ?: "Unknown" fun String.parseTimeStringOrNull(): Duration? { val regex = "(-?)(?:(?:([0-9]{1,2}):)?([0-9]{1,2}):)?([0-9]{1,2})(?:\\.([0-9]{1,9}))?".toRegex() val units = listOf(TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS) return regex.matchEntire(this)?.let { m -> val neg = m.groupValues[1] == "-" val totalNanos = m.groupValues.drop(2).zip(units).map { (match, unit) -> unit.toNanos(match.toLongOrNull() ?: 0) }.sum() + m.groupValues.last().padEnd(9, '0').toLong() Duration.ofNanos(totalNanos * if (neg) -1 else 1) } } /** * Converts [this] double as a number of seconds and coverts it to a [Duration] */ fun Double.toSecondsDuration(onZero: Duration? = null): Duration? { check(this >= 0) return if (this == 0.0) onZero else Duration.ofSeconds(toLong(), ((this % 1) * 1000000000).toLong())!! } /** * Converts [this] BigDecimal as a number of seconds and coverts it to a [Duration] */ fun BigDecimal.toSecondsDuration() = Duration.ofNanos(this.setScale(9).unscaledValue().longValueExact())!! /** * Converts this duration to a [BigDecimal] in seconds and returns its plain string representation. */ fun Duration.toTotalSeconds(): String = BigDecimal.valueOf(toNanos(), 9).toPlainString() /** * Sums this iterable of [Duration]s. */ fun Iterable<Duration>.sum(): Duration = fold(Duration.ZERO) { acc, it -> acc + it }
0
Kotlin
0
0
40a1d363e2260a41bfb6cb77e4c07f49b8cccc89
2,573
media-merger
MIT License
Phone Book (Kotlin)/Phone Book (Kotlin)/task/src/phonebook/Main.kt
Undiy
617,323,453
false
null
package phonebook import java.io.BufferedReader import java.io.File import java.io.FileReader import java.lang.Integer.min import java.util.* import kotlin.math.sqrt import kotlin.streams.asSequence const val FIND_FILENAME = "find.txt" const val DIRECTORY_FILENAME = "directory.txt" fun getRecordName(record: String) = record.substringAfter(" ", record) fun linearSearchFn(value: String): Boolean { BufferedReader(FileReader(DIRECTORY_FILENAME)).use { directoryReader -> return directoryReader.lines().anyMatch { getRecordName(it) == value } } } fun jumpSearch(data: List<String>, value: String): Boolean { val blockSize = sqrt(data.size.toDouble()).toInt() for (i in 0..data.size / blockSize) { val boundary = min(data.lastIndex, (i + 1) * blockSize - 1) if (getRecordName(data[boundary]) >= value) { for (j in boundary downTo i * blockSize) { if (getRecordName(data[j]) == value) { return true } } } } return false } fun binarySearch(data: List<String>, value: String): Boolean { if (data.isEmpty()) { return false } val pivotIndex = data.size / 2 val pivot = getRecordName(data[pivotIndex]) return if (pivot == value) { true } else if (pivot > value) { binarySearch(data.subList(0, pivotIndex), value) } else { binarySearch(data.subList(pivotIndex, data.size), value) } } fun search(searchFn: (String) -> Boolean) = search(searchFn, System.currentTimeMillis()) fun search(searchFn: (String) -> Boolean, start: Long): Long { var count = 0 var found = 0 BufferedReader(FileReader(FIND_FILENAME)).use { findReader -> findReader.lines().forEach { count++ if (searchFn(it)) { found++ } } } val time = System.currentTimeMillis() - start println("Found $found / $count entries. Time taken: ${formatTimeMillis(time)}") return time } fun bubbleAndJumpSearch(limit: Long): Long { val start = System.currentTimeMillis() val directory = File(DIRECTORY_FILENAME).readLines() val (isSorted, sortTime) = bubbleSort(directory, limit) val time = search(if (isSorted) { { jumpSearch(directory, it) } } else { ::linearSearchFn }, start) if (isSorted) { println("Sorting time: ${formatTimeMillis(sortTime)}") } else { println("Sorting time: ${formatTimeMillis(sortTime)} - STOPPED, moved to linear search") } println("Searching time: ${formatTimeMillis(time - sortTime)}") return time } fun formatTimeMillis(millis: Long) = "${millis / 1000_000} min. ${millis % 1000_000 / 1000} sec. ${millis % 1000} ms." fun bubbleSort(data: List<String>, timeLimit: Long): Pair<Boolean, Long> { val start = System.currentTimeMillis() var isSorted: Boolean do { isSorted = true for (i in 0 until data.lastIndex) { val time = System.currentTimeMillis() - start if (time > timeLimit) { return Pair(false, time) } if (getRecordName(data[i]) > getRecordName(data[i + 1])) { isSorted = false Collections.swap(data, i, i + 1) } } } while (!isSorted) return Pair(true, System.currentTimeMillis() - start) } fun quickSort(data: List<String>) { if (data.size < 2) { return } val pivot = getRecordName(data.random()) var boundary = 0 for (i in data.indices) { if (getRecordName(data[i]) < pivot) { Collections.swap(data, i, boundary) boundary++ } } quickSort(data.subList(0, boundary)) quickSort(data.subList(boundary, data.size)) } fun quickAndBinarySearch(): Long { val start = System.currentTimeMillis() val directory = File(DIRECTORY_FILENAME).readLines() quickSort(directory) val sortTime = System.currentTimeMillis() - start val time = search({ binarySearch(directory, it) }, start) println("Sorting time: ${formatTimeMillis(sortTime)}") println("Searching time: ${formatTimeMillis(time - sortTime)}") return time } fun hashSearch(): Long { val start = System.currentTimeMillis() val table = BufferedReader(FileReader(DIRECTORY_FILENAME)).use { directoryReader -> directoryReader.lines().asSequence().groupBy( ::getRecordName ) { it.substringBefore(" ", it) } } val createTime = System.currentTimeMillis() - start val time = search({ it in table }, start) println("Creating time: ${formatTimeMillis(createTime)}") println("Searching time: ${formatTimeMillis(time - createTime)}") return time } fun main() { println("Start searching (linear search)...") val linearTime = search(::linearSearchFn) println() println("Start searching (bubble sort + jump search)...") bubbleAndJumpSearch(linearTime * 10) println() println("Start searching (quick sort + binary search)...") quickAndBinarySearch() println("Start searching (hash table)...") hashSearch() }
0
Kotlin
0
0
70695fbaa9b5909be4740c57a49a955855dfd738
5,193
hyperskill-kotlin-core
MIT License
src/main/kotlin/g0201_0300/s0208_implement_trie_prefix_tree/Trie.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0201_0300.s0208_implement_trie_prefix_tree // #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Design #Trie // #Level_2_Day_16_Design #Udemy_Trie_and_Heap // #Big_O_Time_O(word.length())_or_O(prefix.length())_Space_O(N) // #2022_09_10_Time_689_ms_(61.00%)_Space_87.9_MB_(36.00%) class Trie { private val root: TrieNode private var startWith = false class TrieNode { // Initialize your data structure here. var children: Array<TrieNode?> var isWord = false init { children = arrayOfNulls(26) } } // Inserts a word into the trie. fun insert(word: String) { insert(word, root, 0) } private fun insert(word: String, root: TrieNode?, idx: Int) { if (idx == word.length) { root!!.isWord = true return } val index = word[idx] - 'a' if (root!!.children[index] == null) { root.children[index] = TrieNode() } insert(word, root.children[index], idx + 1) } // Returns if the word is in the trie. @JvmOverloads fun search(word: String, root: TrieNode? = this.root, idx: Int = 0): Boolean { if (idx == word.length) { startWith = true return root!!.isWord } val index = word[idx] - 'a' if (root!!.children[index] == null) { startWith = false return false } return search(word, root.children[index], idx + 1) } // Returns if there is any word in the trie // that starts with the given prefix. fun startsWith(prefix: String): Boolean { search(prefix) return startWith } init { root = TrieNode() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,770
LeetCode-in-Kotlin
MIT License
kotlin/673.Number of Longest Increasing Subsequence(最长递增子序列的个数).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 an unsorted array of integers, find the number of longest increasing subsequence. </p> <p><b>Example 1:</b><br /> <pre> <b>Input:</b> [1,3,5,4,7] <b>Output:</b> 2 <b>Explanation:</b> The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. </pre> </p> <p><b>Example 2:</b><br /> <pre> <b>Input:</b> [2,2,2,2,2] <b>Output:</b> 5 <b>Explanation:</b> The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. </pre> </p> <p><b>Note:</b> Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. </p><p>给定一个未排序的整数数组,找到最长递增子序列的个数。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1,3,5,4,7] <strong>输出:</strong> 2 <strong>解释:</strong> 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。 </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong> [2,2,2,2,2] <strong>输出:</strong> 5 <strong>解释:</strong> 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。 </pre> <p><strong>注意:</strong>&nbsp;给定的数组长度不超过 2000 并且结果一定是32位有符号整数。</p> <p>给定一个未排序的整数数组,找到最长递增子序列的个数。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1,3,5,4,7] <strong>输出:</strong> 2 <strong>解释:</strong> 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。 </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong> [2,2,2,2,2] <strong>输出:</strong> 5 <strong>解释:</strong> 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。 </pre> <p><strong>注意:</strong>&nbsp;给定的数组长度不超过 2000 并且结果一定是32位有符号整数。</p> **/ class Solution { fun findNumberOfLIS(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,031
leetcode
MIT License
Peaceful_chess_queen_armies/Kotlin/src/Peaceful.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
import kotlin.math.abs enum class Piece { Empty, Black, White, } typealias Position = Pair<Int, Int> fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean { if (m == 0) { return true } var placingBlack = true for (i in 0 until n) { inner@ for (j in 0 until n) { val pos = Position(i, j) for (queen in pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { continue@inner } } for (queen in pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { continue@inner } } placingBlack = if (placingBlack) { pBlackQueens.add(pos) false } else { pWhiteQueens.add(pos) if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true } pBlackQueens.removeAt(pBlackQueens.lastIndex) pWhiteQueens.removeAt(pWhiteQueens.lastIndex) true } } } if (!placingBlack) { pBlackQueens.removeAt(pBlackQueens.lastIndex) } return false } fun isAttacking(queen: Position, pos: Position): Boolean { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second) } fun printBoard(n: Int, blackQueens: List<Position>, whiteQueens: List<Position>) { val board = MutableList(n * n) { Piece.Empty } for (queen in blackQueens) { board[queen.first * n + queen.second] = Piece.Black } for (queen in whiteQueens) { board[queen.first * n + queen.second] = Piece.White } for ((i, b) in board.withIndex()) { if (i != 0 && i % n == 0) { println() } if (b == Piece.Black) { print("B ") } else if (b == Piece.White) { print("W ") } else { val j = i / n val k = i - j * n if (j % 2 == k % 2) { print("• ") } else { print("◦ ") } } } println('\n') } fun main() { val nms = listOf( Pair(2, 1), Pair(3, 1), Pair(3, 2), Pair(4, 1), Pair(4, 2), Pair(4, 3), Pair(5, 1), Pair(5, 2), Pair(5, 3), Pair(5, 4), Pair(5, 5), Pair(6, 1), Pair(6, 2), Pair(6, 3), Pair(6, 4), Pair(6, 5), Pair(6, 6), Pair(7, 1), Pair(7, 2), Pair(7, 3), Pair(7, 4), Pair(7, 5), Pair(7, 6), Pair(7, 7) ) for ((n, m) in nms) { println("$m black and $m white queens on a $n x $n board:") val blackQueens = mutableListOf<Position>() val whiteQueens = mutableListOf<Position>() if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens) } else { println("No solution exists.\n") } } }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
3,109
rosetta
MIT License
src/Day09.kt
ka1eka
574,248,838
false
{"Kotlin": 36739}
import kotlin.math.abs fun main() { fun Pair<Int, Int>.isTouching(other: Pair<Int, Int>): Boolean = this == other || abs(first - other.first) <= 1 && abs(second - other.second) <= 1 fun Pair<Int, Int>.moveUp(): Pair<Int, Int> = Pair(first, second - 1) fun Pair<Int, Int>.moveDown(): Pair<Int, Int> = Pair(first, second + 1) fun Pair<Int, Int>.moveLeft(): Pair<Int, Int> = Pair(first - 1, second) fun Pair<Int, Int>.moveRight(): Pair<Int, Int> = Pair(first + 1, second) fun Pair<Pair<Int, Int>, Pair<Int, Int>>.move(block: () -> Pair<Int, Int>): Pair<Pair<Int, Int>, Pair<Int, Int>> = with(block()) { Pair( this, if (this.isTouching([email protected])) [email protected] else [email protected] ) } fun move(target: Pair<Int, Int>, start: Pair<Int, Int>): Pair<Int, Int> { return listOf( start.moveUp(), start.moveDown(), start.moveLeft(), start.moveRight(), start.moveUp().moveLeft(), start.moveUp().moveRight(), start.moveDown().moveLeft(), start.moveDown().moveRight() ).minBy { abs(target.first - it.first) + abs(target.second - it.second) } } fun MutableList<Pair<Int, Int>>.move(block: () -> Pair<Int, Int>) = with(block()) { this@move[0] = this for (i in 1 until [email protected]) { if (this@move[i].isTouching(this@move[i - 1])) { break } this@move[i] = move(this@move[i - 1], this@move[i]) } } fun part1(input: List<String>): Int = with(ArrayDeque(listOf(Pair(Pair(0, 0), Pair(0, 0))))) { input .map { it.split(' ') } .map { Pair(it[0], it[1].toInt()) } .forEach { var start = this.last() when (it.first) { "U" -> repeat(it.second) { start = start.move { start.first.moveUp() } this.addLast(start) } "D" -> repeat(it.second) { start = start.move { start.first.moveDown() } this.addLast(start) } "L" -> repeat(it.second) { start = start.move { start.first.moveLeft() } this.addLast(start) } "R" -> repeat(it.second) { start = start.move { start.first.moveRight() } this.addLast(start) } } } this.map { it.second } .toSet() .size } fun part2(input: List<String>): Int = with(mutableSetOf<Pair<Int, Int>>()) { val rope = MutableList(10) { Pair(0, 0) } input .map { it.split(' ') } .map { Pair(it[0], it[1].toInt()) } .forEach { when (it.first) { "U" -> repeat(it.second) { rope.move { rope.first().moveUp() } this.add(rope.last()) } "D" -> repeat(it.second) { rope.move { rope.first().moveDown() } this.add(rope.last()) } "L" -> repeat(it.second) { rope.move { rope.first().moveLeft() } this.add(rope.last()) } "R" -> repeat(it.second) { rope.move { rope.first().moveRight() } this.add(rope.last()) } } } this.size } val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4f7893448db92a313c48693b64b3b2998c744f3b
4,103
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kr/co/programmers/P49191.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/532 class P49191 { fun solution(n: Int, results: Array<IntArray>): Int { // 승/패로 초기화 val graph = Array(n) { IntArray(n) } for ((win, lose) in results) { graph[win - 1][lose - 1] = 1 graph[lose - 1][win - 1] = -1 } // 플로이드 와샬 for (k in 0 until n) { for (i in 0 until n) { for (j in 0 until n) { if (graph[i][k] == 1 && graph[k][j] == 1) { graph[i][j] = 1 graph[j][i] = -1 } } } } // 경기 결과의 수가 (n-1)개면 이 선수의 순위를 알 수 있다. return graph.count { p -> p.count { it != 0 } == n - 1 } } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
887
algorithm
MIT License
src/main/kotlin/com/leetcode/monthly_challenges/2021/april/phone_number_to_words/Main.kt
frikit
254,842,734
false
null
package com.leetcode.monthly_challenges.`2021`.april.phone_number_to_words fun main() { println("Test case 1:") println(Solution().letterCombinations("23"))//["ad","ae","af","bd","be","bf","cd","ce","cf"] println() println("Test case 2:") println(Solution().letterCombinations(""))//[] println() println("Test case 3:") println(Solution().letterCombinations("1"))//[] println() println("Test case 4:") println(Solution().letterCombinations("0"))//[] println() } class Solution { companion object { val keypad = mutableMapOf<Char, CharArray>().apply { put('2', "abc".toCharArray()) put('3', "def".toCharArray()) put('4', "ghi".toCharArray()) put('5', "jkl".toCharArray()) put('6', "mno".toCharArray()) put('7', "pqrs".toCharArray()) put('8', "tuv".toCharArray()) put('9', "wxyz".toCharArray()) } } fun letterCombinations(digits: String): List<String> { var result: MutableList<String> = ArrayList() if (digits.isEmpty() || digits == "1" || digits == "0") return result result.add("") for (element in digits) result = combine(keypad[element]!!, result) return result } fun combine(digit: CharArray, l: List<String>): MutableList<String> { val result: MutableList<String> = ArrayList() for (element in digit) for (x in l) result.add(x + element) return result } }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,543
leet-code-problems
Apache License 2.0
src/day8/TreeGrid.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day8 /** * */ data class TreeGrid (val data: List<List<Int>>) { init { data.forEach { assert (it.size == data.size) } } val cols: Int = data[0].size val rows: Int = data.size fun height (x: Int, y: Int): Int = data[y][x] fun row (y: Int): List<Int> = data[y] fun col (x: Int): List<Int> = data.map { it [x] } val trees: Int get () = cols * rows fun visit (func: TreeGrid.(x: Int, y: Int) -> Unit) { for (x in 0 until cols) { for (y in 0 until rows) { this.func (x, y) } } return } fun assess (x: Int, y: Int): List<List<Int?>> { return data.mapIndexed { iy, row -> row.mapIndexed { ix, height -> if (x == ix || y == iy) { height } else { null } } } } fun dump () { data.dump () return } fun visibleMatrix (): List<List<Boolean>> { return data.mapIndexed { y, row -> row.mapIndexed { x, _ -> isVisible (x, y) } } } fun dumpVisible () { visibleMatrix().forEach { it.forEach { if (it) { print ("* ") } else { print (". ") } } println () } } val visible: Int get () { var total = 0 visit { x, y -> if (isVisible (x, y)) { total ++ } } return total } val maxScenicScore: Int get () { val scores = mutableListOf<Int> () visit { x, y, -> scores.add (getScenicScore(x, y)) } return scores.maxOf { it } } fun getViews (x: Int, y: Int): List<List<Int>> { val xs = row (y) val ys = col (x) return listOf ( xs.subList(0, x).reversed (), xs.subList(x + 1, xs.size), ys.subList(0, y).reversed (), ys.subList(y + 1, ys.size) ) } fun getViewingDistance (height: Int, view: List<Int>): Int { var distance = 0 for (tree in view) { distance ++ if (tree >= height) { break } } return distance } fun getScenicScores (x: Int, y: Int): List<Int> { val result = mutableListOf<Int> () val height = height (x, y) getViews (x, y).forEach { val score = getViewingDistance(height, it) result.add (score) } return result } fun getScenicScore (x: Int, y: Int): Int { var result = 1 getScenicScores(x, y).forEach { result *= it } return result } fun isVisible (x: Int, y: Int): Boolean { if (x == 0 || x == cols - 1 || y == 0 || y == rows - 1) { return true } val height = height (x, y) var visible = false getViews(x, y).forEach { if (height > it.maxOf { it }) { visible = true } } return visible } companion object { fun loadGrid (str: String): TreeGrid { val split = str.split ("\n") val rows = ArrayList<List<Int>> (split.size) split.forEach { val row = it.map { it.digitToInt() } rows.add (row) } return TreeGrid (rows) } } } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
3,688
advent_of_code_2022
Apache License 2.0
src/main/java/challenges/educative_grokking_coding_interview/fast_slow_pointers/_5/FindDuplicate.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.fast_slow_pointers._5 import challenges.util.PrintHyphens import java.util.* /** Given an array of integers, nums, find a duplicate number such that the array contains n+1 elements, and each integer is in the range [1,n] inclusive. There is only one repeated number in nums. Find and return that number. Note: You cannot modify the given array nums. You have to solve the problem using only constant extra space. https://www.educative.io/courses/grokking-coding-interview-patterns-java/g7Pq3G7NK06 */ object FindDuplicate { fun findDuplicate(nums: IntArray): Int { // Intialize the fast and slow pointers and make them point the first // element of the array var fast = nums[0] var slow = nums[0] // PART #1 // Traverse in array until the intersection point is found while (true) { // Move the slow pointer using the nums[slow] flow slow = nums[slow] // Move the fast pointer two times fast as the slow pointer using the // nums[nums[fast]] flow fast = nums[nums[fast]] // Break the loop when slow pointer becomes equal to the fast pointer, i.e., // if the intersection is found if (slow == fast) { break } } // PART #2 // Make the slow pointer point the starting position of an array again, i.e., // start the slow pointer from starting position slow = nums[0] // Traverse the array until the slow pointer becomes equal to the // fast pointer while (slow != fast) { // Move the slow pointer using the nums[slow] flow slow = nums[slow] // Move the fast pointer slower than before, i.e., move the fast pointer // using the nums[fast] flow fast = nums[fast] } // Return the fast pointer as it points the duplicate number of the array return fast } @JvmStatic fun main(args: Array<String>) { val nums = arrayOf( intArrayOf(1, 3, 2, 3, 5, 4), intArrayOf(2, 4, 5, 4, 1, 3), intArrayOf(1, 6, 3, 5, 1, 2, 7, 4), intArrayOf(1, 2, 2, 4, 3), intArrayOf(3, 1, 3, 5, 6, 4, 2) ) for (i in nums.indices) { print(i + 1) println(".\tnums = " + Arrays.toString(nums[i])) println("\tDuplicate number = " + findDuplicate(nums[i])) println(PrintHyphens.repeat("-", 100)) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,606
CodingChallenges
Apache License 2.0
src/Day20.kt
felldo
572,233,925
false
{"Kotlin": 76496}
import java.lang.Exception data class WorkingNumber(val original: Int, val number: Long) fun main() { fun moveItem(coords: MutableList<WorkingNumber>, index: Int) { val item = coords.find { it.original == index } ?: throw Exception() val oldIndex = coords.indexOf(item) var newIndex = (oldIndex + item.number) % (coords.size - 1) if (newIndex < 0) { newIndex += coords.size - 1 } coords.removeAt(oldIndex) coords.add(newIndex.toInt(), item) } fun part1(input: List<String>): Long { val coords = input.mapIndexed { index, s -> WorkingNumber(index, s.toLong()) }.toMutableList() for (i in coords.indices) { moveItem(coords, i) } val zeroIndex = coords.indexOfFirst { it.number == 0L } ?: throw Exception() return coords[((zeroIndex + 1_000L) % coords.size).toInt()].number + coords[((zeroIndex + 2_000L) % coords.size).toInt()].number + coords[((zeroIndex + 3_000L) % coords.size).toInt()].number } fun part2(input: List<String>): Long { val coords = input.mapIndexed { index, s -> WorkingNumber(index, s.toLong() * 811_589_153L) }.toMutableList() for (x in 0 until 10) { for (i in coords.indices) { moveItem(coords, i) } } val zeroIndex = coords.indexOfFirst { it.number == 0L } ?: throw Exception() return coords[(zeroIndex + 1_000) % coords.size].number + coords[(zeroIndex + 2_000) % coords.size].number + coords[(zeroIndex + 3_000) % coords.size].number } val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
1,684
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/top/solver/State.kt
kaarthiksundar
366,758,030
false
null
package top.solver import top.data.Parameters import top.main.TOPException /** * Class representing a partial path used in solving the elementary shortest path problem with * resource constraints in the pricing problem. * * @param vertex Current vertex * @param cost Accumulated reduced cost * @param score Accumulated prize collected * @param length Length of the path * @param parent Previous state that was extended to create this state. Null for source vertex. * @param visitedVertices Array of Longs representing if a vertex has been visited or not. */ class State private constructor ( val isForward: Boolean, val vertex: Int, val cost: Double, val score: Double, val length: Double, val parent: State?, val visitedVertices: LongArray ) : Comparable<State>{ /** * Reduced cost per unit length of partial path used for comparing states for sorting in a priority queue. */ private val bangForBuck = if (length > 0) cost / length else 0.0 /** * Create a new State object corresponding to extending the current State's path * * @param newVertex New vertex being visited in the extended path * @param edgeCost Reduced cost of edge used in the extension of the path * @param edgeLength Length of edge being used in the extension * @param newVertexScore Prize of new vertex being visited * * @return New state corresponding to the extended path */ fun extend( newVertex: Int, edgeCost: Double, edgeLength: Double, newVertexScore: Double, parameters: Parameters ): State { val newVisitedVertices = visitedVertices.copyOf() markVertex(newVertex, newVisitedVertices, parameters) return State( isForward, vertex = newVertex, cost = cost + edgeCost, score = score + newVertexScore, length = length + edgeLength, parent = this, visitedVertices = newVisitedVertices ) } /** * Function that returns the partial path corresponding to the label. The order the vertices are visited * is in most recently visited to first visited. */ fun getPartialPath() : List<Int> { val path = mutableListOf<Int>() var state: State? = this while (state != null) { path.add(state.vertex) state = state.parent } return path } /** * Function that checks if this state and another given state share visited vertices. True if yes, false otherwise. */ fun hasCommonVisits(otherState: State) : Boolean { for (i in visitedVertices.indices) { // Checking the AND operation yields 0L (i.e., checking if a vertex is shared) if (visitedVertices[i] and otherState.visitedVertices[i] != 0L) { return true } } return false } /** * Function that checks if this state dominates another given state. */ fun dominates(otherState: State, parameters: Parameters) : Boolean { // States can only be compared if they have a partial path ending at the same vertex if (vertex != otherState.vertex) throw TOPException("States must have same vertex to be comparable.") if (isForward != otherState.isForward) throw TOPException("States can only be compared if they are going in the same direction.") /** * Comparing the components of the state. Using a Boolean to track whether there's at least one strict * inequality. */ var strict = false // Comparing the cost if (cost >= otherState.cost + parameters.eps) return false if (cost <= otherState.cost - parameters.eps) strict = true // Comparing the path length used if (length >= otherState.length + parameters.eps) return false if (length <= otherState.length - parameters.eps) strict = true // Checking visited vertices for (i in visitedVertices.indices) { if (visitedVertices[i] > otherState.visitedVertices[i]) return false if (visitedVertices[i] < otherState.visitedVertices[i]) strict = true } return strict } fun markVertex(vertex: Int, visitedVertices: LongArray, parameters: Parameters) { // Finding which set of n bits to update val quotient : Int = vertex / parameters.numBits // Finding which bit in the set of n bits to update val remainder : Int = vertex % parameters.numBits // Updating visitedVertices[quotient] = visitedVertices[quotient] or (1L shl remainder) } fun inPartialPath(vertex: Int, parameters: Parameters) : Boolean { val quotient : Int = vertex / parameters.numBits val remainder : Int = vertex % parameters.numBits return visitedVertices[quotient] and (1L shl remainder) != 0L } companion object { /** * Factory constructor for creating the initial forward (backward) state at the source (destination) */ fun buildTerminalState(isForward: Boolean, vertex: Int, numVertices: Int, parameters: Parameters) : State { val numberOfLongs : Int = (numVertices / parameters.numBits) + 1 val arrayOfLongs = LongArray(numberOfLongs) {0L} // Updating the terminal vertex's bit to be a 1 val quotient : Int = vertex / parameters.numBits val remainder : Int = vertex % parameters.numBits arrayOfLongs[quotient] = 1L shl remainder return State(isForward, vertex, 0.0, 0.0, 0.0, null, LongArray(numberOfLongs) {0L}) } } /** * Comparator based on reduced cost per unit length. */ override fun compareTo(other: State): Int { return when { bangForBuck < other.bangForBuck -> -1 bangForBuck > other.bangForBuck -> 1 else -> 0 } } }
1
Kotlin
1
0
13d8af37d35fff8251d89db2cb95b5c10d31a5a0
6,132
top-sensitivity
MIT License
src/main/kotlin/days/Day14.kt
vovarova
572,952,098
false
{"Kotlin": 103799}
package days import util.Cell import util.range class Day14 : Day(14) { class CaveMap(input: List<String>) { val rock: Set<Cell> var maxRow: Int val sand: MutableSet<Cell> = mutableSetOf() init { rock = createRockIndex(input) maxRow = rock.map { it.row }.max() } fun createRockIndex(input: List<String>): Set<Cell> { return input.flatMap { line -> line.split(" -> ").map { it.split(",").let { Cell(row = it[1].toInt(), column = it[0].toInt()) } } .windowed(2) { Pair(it[0], it[1]) }.flatMap { it -> val columnRange = range(it.first.column, it.second.column) val rowRange = range(it.first.row, it.second.row) rowRange.flatMap { row -> columnRange.map { column -> Cell(row, column) } } } }.toSet() } fun fallSand(init: Cell): Boolean { var currentPosition = init while (currentPosition.row < maxRow) { val first = listOf( currentPosition.down(), currentPosition.down().left(), currentPosition.down().right() ).find { !(rock.contains(it) || sand.contains(it)) } if (first == null) { sand.add(currentPosition) return true } else currentPosition = first } return false } fun fallSandWithInfiniteFloor(init: Cell): Boolean { if (sand.contains(init)) { return false } var currentPosition = init val floorRow = maxRow + 2 while (currentPosition.row < floorRow) { val first = listOf( currentPosition.down(), currentPosition.down().left(), currentPosition.down().right() ).find { !(rock.contains(it) || sand.contains(it) || it.row == floorRow) } if (first == null) { sand.add(currentPosition) return true } else currentPosition = first } return false } } override fun partOne(): Int { val caveMap = CaveMap(inputList) while (caveMap.fallSand(Cell(0, 500))) { } return caveMap.sand.size } override fun partTwo(): Any { val caveMap = CaveMap(inputList) while (caveMap.fallSandWithInfiniteFloor(Cell(0, 500))) { } return caveMap.sand.size } }
0
Kotlin
0
0
e34e353c7733549146653341e4b1a5e9195fece6
2,709
adventofcode_2022
Creative Commons Zero v1.0 Universal
src/graphs/weighted/UndirectedWeightedGraph.kt
ArtemBotnev
136,745,749
false
{"Kotlin": 79256, "Shell": 292}
package graphs.weighted import java.util.* import kotlin.collections.HashMap /** * Model of undirected weighted graph */ class UndirectedWeightedGraph<T>(maxVertexCount: Int, infinity: Long) : WeightedGraph<T>(maxVertexCount, infinity) { override fun addEdge(first: T, second: T, weight: Long): Boolean { val values = vertexList.map { it.value } val start = values.indexOf(first) val end = values.indexOf(second) if (start < 0 || end < 0) return false adjMatrix[start][end] = weight adjMatrix[end][start] = weight return true } /** * Minimum Spanning Tree of Weighted graph function * makes vertices connected with minimum edges count = vertices - 1 * * @param action - lambda what perform an action with two bound vertices values * and weight between them */ fun mstw(action: (T?, T?, Long) -> Unit) { // priority queue of graph vertices val pQueue = PriorityQueue<Edge<T>>(currentVertexCount) // map - contains info if particular vertex has already bound in MST or not val wasBoundMap = HashMap<Vertex<T>, Boolean>(currentVertexCount) // count of vertices added in MST var addedVerticesCount = 0 var currentVertex: Vertex<T> = vertexList[0] // fill connectivity map vertexList.forEach { wasBoundMap[it] = false } while (addedVerticesCount < currentVertexCount - 1) { currentVertex.wasVisited = true addedVerticesCount++ val currentVertexIndex = vertexList.indexOf(currentVertex) for (i in 0 until currentVertexCount) { if (i == currentVertexIndex) continue if (vertexList[i].wasVisited) continue val weight = adjMatrix[currentVertexIndex][i] if (weight >= infinity) continue val destinationVertex = vertexList[i] // create edge and put it in queue pQueue.add(Edge(currentVertex, destinationVertex, weight)) } if (pQueue.isEmpty()) { // graph isn't connected action(null, null, infinity) return } var minWeightEdge: Edge<T> do { // get edge with min weight minWeightEdge = pQueue.remove() // check if this vertex has already bound and skip it } while (wasBoundMap[minWeightEdge.to]!!) // add to map wasBoundMap[minWeightEdge.to] = true val vertexFrom = minWeightEdge.from currentVertex = minWeightEdge.to action(vertexFrom.value, currentVertex.value, minWeightEdge.weight) } // flags reset vertexList.forEach { it.wasVisited = false } } /** * Represents edge between two vertex and weight of this edge */ private class Edge<T>(val from: Vertex<T>, val to: Vertex<T>, val weight: Long) : Comparable<Edge<T>> { override fun compareTo(other: Edge<T>) = this.weight.compareTo(other.weight) } }
0
Kotlin
0
0
530c02e5d769ab0a49e7c3a66647dd286e18eb9d
3,150
Algorithms-and-Data-Structures
MIT License
src/2023/Day18.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import common.Linearizer import java.io.File import java.lang.RuntimeException import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { Day18().solve() } class Day18 { val input1 = """ R 6 (#70c710) D 5 (#0dc571) L 2 (#5713f0) D 2 (#d2c081) R 2 (#59c680) D 2 (#411b91) L 5 (#8ceee2) U 2 (#caa173) L 1 (#1b58a2) U 2 (#caa171) R 2 (#7807d2) U 3 (#a77fa3) L 2 (#015232) U 2 (#7a21e3) """.trimIndent() val input2 = """ """.trimIndent() fun Pair<Int, Int>.apply(xy: Pair<Int, Int>): Pair<Int, Int> { val (d, n) = this var (x1, y1) = xy when (d) { 0 -> x1 += n 1 -> y1 += n 2 -> x1 -= n 3 -> y1 -= n } return x1 to y1 } fun Pair<Int, Int>.apply(xy0: Pair<Int, Int>, tiles: MutableList<Char>, l: Linearizer): Pair<Int, Int> { val (x0, y0) = xy0 val (x1,y1) = apply(xy0) val (d, n) = this val ix0 = l.toIndex(x0, y0) val ix1 = l.toIndex(x1, y1) tiles[ix0] = '*' tiles[ix1] = '*' when (d) { 0 -> for (x in x0+1 until x1) tiles[l.toIndex(x, y0)] = '-' 1 -> for (y in y0+1 until y1) tiles[l.toIndex(x0, y)] = '|' 2 -> for (x in x1+1 until x0) tiles[l.toIndex(x, y0)] = '-' 3 -> for (y in y1+1 until y0) tiles[l.toIndex(x0, y)] = '|' else -> throw RuntimeException() } // print(tiles, l) return x1 to y1 } fun print(map: List<Char>, l: Linearizer) { for (y in 0 until l.dimensions[1]) { for (x in 0 until l.dimensions[0]) { print("${map[l.toIndex(x,y)]}") } print("\n") } println() } fun solve() { val f = File("src/2023/inputs/day18.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = 0 var sum1 = 0 var lineix = 0 val lines = mutableListOf<String>() val cmds = mutableListOf<Pair<Int, Int>>() val cmds1 = mutableListOf<Pair<Int, Int>>() while (s.hasNextLine()) { lineix++ val line = s.nextLine().trim() if (line.isEmpty()) { continue } lines.add(line) val (d, n, h) = Regex("(.+) (.+) \\(#(.+)\\)").find(line)!!.destructured cmds.add(d.let { when (it) {"R" -> 0; "D" -> 1; "L" -> 2; "U" -> 3; else -> throw RuntimeException()}} to n.toInt()) val d1 = h.last().digitToInt() val h1 = h.substring(0, h.length-1) val n1 = h1.toInt(16) cmds1.add(d1 to n1) } // // val points0 = mutableListOf<Pair<Int, Int>>() // cmds.fold(0 to 0){p, cmd -> val p1 = cmd.apply(p); points0.add(p1); p1} // // val minX = points0.minOf { it.first } // val maxX = points0.maxOf { it.first } // val minY = points0.minOf { it.second } // val maxY = points0.maxOf { it.second } // // val startPoint = -1 * minX + 1 to -1 * minY + 1 // val l = Linearizer(maxX - minX + 3, maxY - minY + 3) // // val tiles = MutableList(l.size){'.'} //// print(tiles, l) // // val points1 = mutableListOf<Pair<Int, Int>>() // cmds.fold(startPoint){p, cmd -> val p1 = cmd.apply(p, tiles, l); points1.add(p1); p1} //// print(tiles, l) // // for (i in cmds.indices) { // val (x, y) = points1[i] // val ix = l.toIndex(x, y) // val d = cmds[i].first // val d1 = cmds[(i+1)%cmds.size].first // val corner = // when (d to d1) { // 0 to 0 -> '-' // 0 to 1 -> 'i' // 0 to 3 -> '!' // 1 to 0 -> '!' // 1 to 1 -> '|' // 1 to 2 -> '!' // 2 to 1 -> 'i' // 2 to 2 -> '-' // 2 to 3 -> '!' // 3 to 0 -> 'i' // 3 to 1 -> '|' // 3 to 2 -> 'i' // else -> 'K' // } // tiles[ix] = corner // } // //// print(tiles, l) // // for (y in 0 until l.dimensions[1]) { // // 0 - out // // 1 - in // var w = 0 // var lastNonDash = 'K' // for (x in 0 until l.dimensions[0]) { // val ix = l.toIndex(x, y) // if (tiles[ix] == '.') { // if (w == 1) { // tiles[ix] = ' ' // } // } else if (tiles[ix] == '|') { // w = 1 - w // } else if (tiles[ix] == '-') { // continue // } else if (tiles[ix] == 'i' && lastNonDash == '!' || tiles[ix] == '!' && lastNonDash == 'i') { // w = 1-w // } // lastNonDash = tiles[ix] // } // } // // print(tiles, l) // // sum = tiles.count { it != '.' } // // print("$sum $sum1\n") // // val cmds2 = cmds.toMutableList() var area = cmds1.area(1) // var area2 = cmds1.area(-1) print("$area\n") } fun List<Pair<Int, Int>>.area(dir: Int): Long { var a = 0L val cmds1 = toMutableList() while (cmds1.size != 2) { while (cmds1.removeLineDots()) {} a += cmds1.removeRectangles(dir) } a += cmds1[0].second + 1 return a } fun MutableList<Pair<Int, Int>>.removeLineDots(): Boolean { for (i in 0 until size) { val i1 = (i+1)%size if (get(i).first == get(i1).first) { set(i, get(i).first to get(i).second + get(i1).second) removeAt(i1) return true } } return false } // fun MutableList<Pair<Int, Int>>.removeBackAndForth(dir: Int): Long { // // var ii = -1 // var sign = 0L // for (i in 0 until size) { // val (d, n) = get(i) // val i1 = (i + 1) % size // val (d1, n1) = get(i1) // if ((d + 2) % 4 == d1) { // ii = i // sign = 1L * dir // break; // } // if ((d1 + 2) % 4 == d) { // ii = i // sign = 1L * dir // break; // } // // if (n > n1) { // set(i, d to n-n1) // removeAt(i1) // sign * (n1 + dir.toLong()) * n2 // } else if (n2 > n) { // set(i2, d2 to n2-n) // removeAt(i) // sign * (n1 + sign) * n // } else { // removeAt(max(i, i2)) // removeAt(min(i, i2)) // sign * (n1 + sign) * n // } // } // } // // } fun MutableList<Pair<Int, Int>>.removeRectangles(dir: Int): Long { var a = 0L var imin = -1 var n1min = 0 var sign = 0L for (i in 0 until size) { val (d, n) = get(i) val i1 = (i+1)%size val (d1, n1) = get(i1) val i2 = (i+2)%size val (d2, n2) = get(i2) if ((d+1)%4 == d1 && (d1+1)%4 == d2) { if (imin == -1 || n1<n1min) { imin = i n1min = n1 sign = 1L } } if ((d2+1)%4 == d1 && (d1+1)%4 == d) { if (imin == -1 || n1<n1min) { imin = i n1min = n1 sign = -1L } } } val sign1 = sign * dir if (imin != -1) { val i = imin val (d, n) = get(i) val i1 = (i+1)%size val (d1, n1) = get(i1) val i2 = (i+2)%size val (d2, n2) = get(i2) val toRemoveIxs = mutableListOf<Int>() var r = if (n > n2) { set(i, d to n-n2) val i3 = (i+3)%size val (d3, n3) = get(i3) if ((d2 + sign.toInt() + 4)%4 == d3) { set(i2, d2 to 0) } else { toRemoveIxs.add(i2) } sign1 * (n1 + sign1) * n2 } else if (n2 > n) { set(i2, d2 to n2-n) val i01 = (i+size-1)%size val (d01, n01) = get(i01) if ((d - sign.toInt() + 4)%4 == d01) { set(i, d to 0) } else { toRemoveIxs.add(i) } sign1 * (n1 + sign1) * n } else { val i3 = (i+3)%size val (d3, n3) = get(i3) // if ((d2 + sign.toInt() + 4)%4 == d3) { // set(i2, d2 to 0) // } else { toRemoveIxs.add(i2) // } val i01 = (i+size-1)%size val (d01, n01) = get(i01) // if ((d - sign.toInt() + 4)%4 == d01) { // set(i, d to 0) // } else { toRemoveIxs.add(i) // } sign1 * (n1 + sign1) * n } toRemoveIxs.sorted().reversed().forEach { removeAt(it) } return r } return 0L } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
9,990
advent-of-code
Apache License 2.0
src/utils/SolutionUtils.kt
Arch-vile
162,448,942
false
null
package utils import model.Location import model.Route import shortestPath /** * Shortest route from Korvatunturi visiting all locations. Route will start and end to Korvatunturi. * Given locations must not include Korvatunturi. */ fun shortestRouteFromKorvatunturi(locations: List<Location>): Route { val stops = locations.toMutableList() stops.add(0,KORVATUNTURI) // Calculate the shortest route and also add Korvatunturi as last stop val routeStops = shortestPath(stops).stops.toMutableList() routeStops.add(KORVATUNTURI) return Route(routeStops) } fun shortestRouteFromKorvatunturiLooping(locations: List<Location>): Route { var minRoute = shortestRouteFromKorvatunturi(locations) var minLength = Double.MAX_VALUE for(i in 1..1000) { val route = shortestRouteFromKorvatunturi(locations.shuffled()) val routeLength = routeLength(route) if(routeLength < minLength) { minRoute = route minLength = routeLength } } return minRoute } fun routeFromKorvatunturi(locations: List<Location>): Route { val stops = locations.toMutableList() stops.add(0,KORVATUNTURI) stops.add(KORVATUNTURI) return Route(stops) } fun sleightWeight(route: Route): Int { return route.stops.map { it.weight }.fold(0) { acc, v -> acc + v } } fun removeKorvatunturi(route: Route): Route { val copy = route.stops.toMutableList() copy.remove(KORVATUNTURI) copy.remove(KORVATUNTURI) return Route(copy) }
0
Kotlin
0
0
03160a5ea318082a0995b08ba1f70b8101215ed7
1,521
santasLittleHelper
Apache License 2.0
CF_892_2_B/CF_892_2_B.kt
AZenhom
680,515,632
false
null
package com.ahmedzenhom.problem_solving.cf_892_2_b var input = mutableListOf<String>( // Not to be included in your submitting "3", "2", "2", "1 2", "2", "4 3", "1", "3", "100 1 6", "3", "4", "1001 7 1007 5", "3", "8 11 6", "2", "2 9" ) fun readLine(): String? { // Not to be included in your submitting val line = input.firstOrNull() input.removeAt(0) return line } // You answer goes here fun main() { val tests = readLine()?.toInt()!! repeat(tests) { val noOfarrays = readLine()?.toInt()!! val arrays = mutableListOf<List<Long>>() var minFirst = -1L var minSecond = Pair(-1L, -1L) for (i in 0 until noOfarrays) { readLine() val array = readLine()!!.split(" ").toList().map { it.toLong() }.sorted() arrays.add(array) val firstSmallest = array[0] if (minFirst == -1L || firstSmallest < minFirst) { minFirst = firstSmallest } val secondSmallest = array[1] if (minSecond.first == -1L || secondSmallest < minSecond.second) { minSecond = Pair(i.toLong(), secondSmallest) } } var sum = 0L for (i in 0 until noOfarrays) { sum += (if (i.toLong() != minSecond.first) arrays[i][1] else minFirst) } println(sum) } }
0
Kotlin
0
0
a2ea0ddda92216103ad1b06a61abedb4298d1562
1,641
Problem-Solving
Apache License 2.0
src/games/simplegridgame/fdc/FitnessDistanceCorrelation.kt
GAIGResearch
186,301,600
false
null
package games.simplegridgame.fdc import agents.DoNothingAgent import games.gridgame.UpdateRule import games.simplegridgame.* import utilities.ElapsedTimer import utilities.StatSummary import java.util.* import kotlin.random.Random val predictionSteps = 5 // set this true to force a random rule val forceRandom = true fun main() { var rule: SimpleUpdateRule = LifeFun() rule = CaveFun() val reference = TruthTableRule().setRule(rule) val t = ElapsedTimer() val nReps = 30 val predictions = TreeMap<Int,StatSummary>() val scores = TreeMap<Int,StatSummary>() for (i in 0 .. 0 step 10 ) { val pair = runTrial(reference, i, nReps) scores[i] = pair.first predictions[i] = pair.second } println("Scores (mean, s.e.)") report(scores) println("Prediction Errors (mean, s.e.)") report(predictions) println(t) } fun report(results: TreeMap<Int,StatSummary>) { results.forEach{key, value -> println("$key\t %.1f\t %.1f".format(value.mean(), value.stdErr()))} } fun runTrial(reference: TruthTableRule, diff: Int, nReps: Int) : Pair<StatSummary,StatSummary> { val scoreSS = StatSummary("Scores (dist = ${diff})") val predSS = StatSummary("Prediction Errors (dist = ${diff})") for (i in 0 until nReps) { // make a new one for each step of the way.. val fdc = FitnessDistanceCorrelation() val drifter = TruthTableRule().setRule(reference) drifter.randomWalkFromStart(diff) if (forceRandom) drifter.randomise() val dist = reference.distance(drifter) println("Check: distance = " + dist) predSS.add(fdc.predictionTest(reference.updateRule(), drifter.updateRule(), predictionSteps)) scoreSS.add(FalseModelPlayTest().playTests(reference.updateRule(), drifter.updateRule(), nGames = 1)) } println(scoreSS) return Pair(scoreSS, predSS) } fun randomHammingTest(size: Int, nTrials: Int) : StatSummary { // use this to sanity check that average hamming distances are equal to size / 2 val ss = StatSummary("Random hamming test (nDims = $size)") val rand = Random for (i in 0 until nTrials) { val x = IntArray(size, {rand.nextInt(2) } ) val y = IntArray(size, {rand.nextInt(2) } ) // println(x.size) var tot = 0 for (ix in 0 until size) tot += Math.abs(x[ix] - y[ix]) ss.add(tot) } return ss } fun simpleTest() { val ttr1 = TruthTableRule().setRule(LifeFun()) val ttr2 = TruthTableRule().setRule(CaveFun()) println(ttr1.distance(ttr2)) println(ttr1.distance(ttr1)) val t = ElapsedTimer() val fdc = FitnessDistanceCorrelation() val nTrials = 100 for (i in 0 until nTrials) { fdc.predictionTest(ttr1.updateRule(), ttr1.updateRule()) } println(fdc.ss) println(t) } interface SimpleUpdateRule { fun f(p: ArrayList<Int>) : Int } class LifeFun : SimpleUpdateRule { override fun f(p: ArrayList<Int>) : Int { assert(p.size == 9) // find total excluding the centre var tot = p.sum() - p.get(4) if (p.get(4) == 0) { return if (tot == 3) 1 else 0 } else { return if (tot == 2 || tot == 3) 1 else 0 } } } class CaveFun : SimpleUpdateRule { override fun f(p: ArrayList<Int>) : Int { assert(p.size == 9) return if (p.sum() > 4) 1 else 0 } } class TruthTableRule : SimpleUpdateRule { val lut = HashMap<ArrayList<Int>, Int>() // val cards = ArrayList<Int>() val stack = Stack<Int>() fun shuffleWalk() { (0 until lut.size).forEach{ t -> stack.add(t) } stack.shuffle() // println(stack) } fun randomWalkFromStart(nSteps: Int) { shuffleWalk() (0 until nSteps).forEach { walkAway() } } fun walkAway() : SimpleUpdateRule { val ix = if (!stack.empty()) stack.pop() else null if (ix != null) { val p = getPattern(ix) lut[p] = 1 - lut[p]!! } return this } fun getPattern(i: Int) : ArrayList<Int> { val a = ArrayList<Int>() i.toString(2).forEach { a.add(it.toInt() - '0'.toInt()) } // now append enough leading zeros while (a.size < 9) a.add(0, 0) return a } override fun f(p: ArrayList<Int>) : Int { return lut[p]!!} fun setRule(rule: SimpleUpdateRule) : TruthTableRule { for (i in 0 until 512) { val p = getPattern(i) lut[p] = rule.f(p) } // println("nPatterns = ${lut.size}") return this } fun setRule(statLearner: StatLearner) : TruthTableRule { for (i in 0 until 512) { val p = getPattern(i) lut[p] = statLearner.getProb(p).toInt() } println("nPatterns = ${lut.size}") return this } fun distance(ttr: TruthTableRule) : Int { var tot = 0 lut.forEach { t, u -> val v = ttr.lut[t] tot += if (v!=null) Math.abs(u-v) else 1 } return tot } fun updateRule() : UpdateRule { return LutRule(this) } fun randomise() { lut.forEach { t, u -> lut[t] = Random.nextInt(2) } } } class FitnessDistanceCorrelation { val ss = StatSummary("Prediction errors") fun predictionTest(r1: UpdateRule, r2: UpdateRule, predictionSteps: Int = 1) : StatSummary{ // test and checking the differences a number of times val g1 = SimpleGridGame(w, h) val g2 = g1.copy() as SimpleGridGame g1.updateRule = r1 g2.updateRule = r2 val agent = DoNothingAgent() // bit of a clumsy way to set doNothing actions val action = agent.getAction(g1.copy(), 0) val actions = intArrayOf(action, action) for (i in 0 until predictionSteps) { g1.next(actions) g2.next(actions) // println("Test ${i}, \t diff = ${g1.grid.difference(g2.grid)}") } val diff = g1.grid.difference(g2.grid) // println("Test ${i}, \t diff = ${diff}") ss.add(diff) // println(ss) return ss } }
0
Kotlin
0
1
247583c5286c45893e8377fe357a56903859f800
6,216
LearningFM
MIT License
src/advent/of/code/NinethPuzzle.kt
1nco
725,911,911
false
{"Kotlin": 112713, "Shell": 103}
package advent.of.code import utils.Util import java.util.* class NinethPuzzle { companion object { private val day = "9"; private var input: MutableList<String> = arrayListOf(); private var result = 0L; private var resultSecond = 0L; private var histories = arrayListOf<History>(); fun solve() { var startingTime = Date(); input.addAll(Reader.readInput(day)); var lineNum = 0; input.forEach { line -> histories.add(getHistory(line)); lineNum++; } histories.forEach{ history -> extrapolate(history); extrapolateBackwards(history); result += history.sequences[0][history.sequences[0].size - 1]; resultSecond += history.reversed[0][history.reversed[0].size - 1]; } System.out.println(result) System.out.println(resultSecond) System.out.println(startingTime); System.out.println(Date()); } private fun getHistory(line: String): History { var history = History(line, arrayListOf()); // history.sequences.add(line.split(" ").map { v -> v.trim().toLong() }.toMutableList()); var l = Util.getNumbers(line).toMutableList(); var l2 = line.split(" ").map { v -> v.trim().toLong() }.toMutableList() history.sequences.add(Util.getNumbers(line).toMutableList()); var depth = 0; var i = 0; var seqence = arrayListOf<Long>(); var allZero = false; while (!allZero) { seqence.add(history.sequences[depth][i + 1] - history.sequences[depth][i]); i++; if (i == history.sequences[depth].size - 1) { i = 0; depth++; history.sequences.add(seqence); if (seqence.all { v -> v == 0L }) { allZero = true; } seqence = arrayListOf(); } } return history; } private fun extrapolate(history: History) { history.sequences[history.sequences.size - 1].add(0); var depth = history.sequences.size - 1 - 1; while (depth != -1) { var depthSeq = history.sequences[depth]; var depthSeqPlusOne = history.sequences[depth + 1] depthSeq.add(depthSeq[depthSeq.size - 1] + depthSeqPlusOne[depthSeqPlusOne.size - 1]) depth--; } } private fun extrapolateBackwards(history: History) { history.sequences.forEach{ history.reversed.add(it.reversed().toMutableList()) } history.reversed[history.reversed.size - 1]; var depth = history.reversed.size - 1 - 1; while (depth != -1) { var depthSeq = history.reversed[depth]; var depthSeqPlusOne = history.reversed[depth + 1] depthSeq.add(depthSeq[depthSeq.size - 1] - depthSeqPlusOne[depthSeqPlusOne.size - 1]) depth--; } } } } class History(line: String, sequences: MutableList<MutableList<Long>>) { var line: String; var sequences: MutableList<MutableList<Long>>; var reversed: MutableList<MutableList<Long>>; init { this.line = line; this.sequences = sequences; reversed = arrayListOf() } }
0
Kotlin
0
0
0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3
3,604
advent-of-code
Apache License 2.0
2021/kotlin-lang/src/main/kotlin/mmxxi/days/DayOne.kt
Delni
317,500,911
false
{"Kotlin": 66017, "Dart": 53066, "Go": 28200, "TypeScript": 7238, "Rust": 7104, "JavaScript": 2873}
package mmxxi.days /** * --- Day 1: Sonar Sweep --- */ class DayOne: Abstract2021("01", "Sonar Sweep", 7, 5) { override fun part1(input: List<String>): Int { return input .map(Integer::parseInt) .foldIndexed(0) { index, accumulator, element -> val previous = index.takeIf { it >= 1 }?.let { Integer.parseInt(input[it - 1]) } element .takeIf { it > (previous ?: it) } ?.let { accumulator + 1 } ?: accumulator } } override fun part2(input: List<String>): Int { val summedInput = input .map(Integer::parseInt) .mapIndexed { index, value -> value + getValueWithOffset(1, index, input) + getValueWithOffset(2, index, input) } return summedInput.foldIndexed(0) { index, accumulator, element -> val previous = index.takeIf { it >= 1 }?.let { summedInput[it - 1] } element.takeIf { it > (previous ?: it) }?.let { accumulator + 1 } ?: accumulator } } private fun getValueWithOffset(offset: Int, index: Int, input: List<String>): Int { return (index.takeIf { it < input.size - offset }?.let { input[it + offset] }?.let(Integer::parseInt) ?: 0) } }
0
Kotlin
0
1
d8cce76d15117777740c839d2ac2e74a38b0cb58
1,319
advent-of-code
MIT License
day10/src/Day10.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day10(private val path: String) { private val lines = mutableListOf<String>() init { File(path).forEachLine { line -> lines.add(line) } } private fun match(a: Char, b: Char): Boolean { if (a == '(' && b == ')') { return true } else if (a == '{' && b == '}') { return true } else if (a == '[' && b == ']') { return true } else if (a == '<' && b == '>') { return true } return false } private fun checkAndRemove(stack: ArrayDeque<Char>, last: Char): Boolean { val end = stack.last() if (match(end, last)) { stack.removeLast() } else { return false } return true } private fun parseLine(line: String): Int { val stack = ArrayDeque<Char>() line.forEach { c -> // check for openings var valid = true when (c) { '[', '{', '<', '(' -> stack.add(c) ']', '}', '>', ')' -> valid = checkAndRemove(stack, c) } if (!valid) { return when (c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } } return 0 } private fun parseLine2(stack: ArrayDeque<Char>, line: String): Boolean { line.forEach { c -> // check for openings var valid = true when (c) { '[', '{', '<', '(' -> stack.add(c) ']', '}', '>', ')' -> valid = checkAndRemove(stack, c) } if (!valid) { return false } } return true } private fun complete(stack: ArrayDeque<Char>): Long { var points = 0L while (stack.size > 0) { val last = stack.removeLast() points = points * 5 + when (last) { '(' -> 1 '[' -> 2 '{' -> 3 '<' -> 4 else -> 0 } } return points } fun part1(): Int { var points = 0 lines.forEach { line -> points += parseLine(line) } return points } fun part2(): Long { var points = mutableListOf<Long>() lines.forEach { line -> val stack = ArrayDeque<Char>() if (parseLine2(stack, line)) { points.add(complete(stack)) } } points.sort() return points[points.size / 2] } } fun main(args: Array<String>) { val aoc = Day10("day10/input.txt") println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
2,853
aoc2021
Apache License 2.0
scripts/Day9.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File import kotlin.math.abs import kotlin.math.sign val program = File("../inputs/9.txt").readLines().map { val splits = it.split(" ") Pair(splits[0][0], splits[1].toInt()) } val visited: MutableSet<Pair<Int,Int>> = mutableSetOf(Pair(0,0)) var xh = 0 var yh = 0 var xt = 0 var yt = 0 program.forEach { (dir, len) -> var oldxt = xt var oldyt = yt if (dir == 'U') yh -= len if (dir == 'D') yh += len if (dir == 'L') xh -= len if (dir == 'R') xh += len val dx = xt - xh val dy = yt - yh if (dx > 1 && abs(dx) >= abs(dy)) { xt = xh + 1; if (dy != 0) yt = yh} if (dx < -1 && abs(dx) >= abs(dy)) { xt = xh - 1; if (dy != 0) yt = yh} if (dy > 1 && abs(dy) >= abs(dx)) {yt = yh + 1; if (dx != 0) xt = xh} if (dy < -1 && abs(dy) >= abs(dx)) {yt = yh - 1; if (dx != 0) xt = xh} while (oldxt != xt || oldyt != yt) { oldxt += (xt - oldxt).sign oldyt += (yt - oldyt).sign visited.add(Pair(oldxt, oldyt)) } } println("After all the moves were simulated with a 2-knot rope, the tail visited ${visited.size} locations.") val visited2: MutableSet<Pair<Int,Int>> = mutableSetOf(Pair(0,0)) val xs = MutableList(10) { 0 } val ys = MutableList(10) { 0 } fun dx(i: Int) = xs[i+1] - xs[i] fun dy(i: Int) = ys[i+1] - ys[i] fun adx(i: Int) = abs(dx(i)) fun ady(i: Int) = abs(dy(i)) program.forEach { (dir, len) -> for (n in 0 until len) { if (dir == 'U') ys[0] += 1 if (dir == 'D') ys[0] -= 1 if (dir == 'L') xs[0] -= 1 if (dir == 'R') xs[0] += 1 for (i in 0 until 9) { if (adx(i) > 1 || ady(i) > 1) { xs[i+1] -= dx(i).sign ys[i+1] -= dy(i).sign } } visited2.add(Pair(xs[9], ys[9])) } } println(visited2) println("After all the moves were simulated with a 10-knot rope, the tail visited ${visited2.size} locations.")
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
1,987
adventofcode2022
MIT License
year2018/src/main/kotlin/net/olegg/aoc/year2018/day8/Day8.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day8 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 8](https://adventofcode.com/2018/day/8) */ object Day8 : DayOf2018(8) { override fun first(): Any? { val numbers = data.parseInts() return sumMetadata(ArrayDeque(numbers)) } override fun second(): Any? { val numbers = data.parseInts() return sumValues(ArrayDeque(numbers)) } private fun sumMetadata(data: ArrayDeque<Int>): Int { val child = data.removeFirst() val metadata = data.removeFirst() return (0..<child).sumOf { sumMetadata(data) } + (0..<metadata).sumOf { data.removeFirst() } } private fun sumValues(data: ArrayDeque<Int>): Int { val child = data.removeFirst() val metadata = data.removeFirst() val childValues = (0..<child).associateWith { sumValues(data) } return (0..<metadata).sumOf { if (child > 0) { childValues[data.removeFirst() - 1] ?: 0 } else { data.removeFirst() } } } } fun main() = SomeDay.mainify(Day8)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,116
adventofcode
MIT License
src/main/kotlin/dev/claudio/adventofcode2021/Day5Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 import kotlin.math.abs import kotlin.math.sign fun main() { Day5Part2().main() } private class Day5Part2 { fun main() { val inputList: List<String> = Support.readFileAsListString("day5-input.txt") val lines = inputList .map { val split: List<String> = it.split(" -> ", ",") Line( Integer.valueOf(split[0]), Integer.valueOf(split[1]), Integer.valueOf(split[2]), Integer.valueOf(split[3]), ) } .filter { it.isHorizontalOrVerticalOrDiagonal45() } val hits: Map<String, Int> = lines.flatMap { it.hits() }.groupingBy { it }.eachCount() val count = hits.filter { it.value > 1 }.count() println(lines) println(hits) println(count) } data class Line( val x1: Int, val y1: Int, val x2: Int, val y2: Int, ) { fun isHorizontalOrVerticalOrDiagonal45(): Boolean { return x1 == x2 || y1 == y2 || abs(x1-x2) == abs(y1-y2) } fun hits() : List<String> { val hits: MutableList<String> = mutableListOf() if (x1 == x2) { var low : Int var high : Int if (y1 <= y2) { low = y1; high = y2 } else { low = y2; high = y1 } (low..high).forEach { hits.add("$x1,$it") } } else if (y1 == y2) { var low : Int var high : Int if (x1 <= x2) { low = x1; high = x2 } else { low = x2; high = x1 } (low..high).forEach { hits.add("$it,$y1") } } else if (abs(x1-x2) == abs(y1-y2)) { val directionX = sign((x1-x2).toDouble()).toInt() val directionY = sign((y1-y2).toDouble()).toInt() var currentX = x2 var currentY = y2 hits.add("$currentX,$currentY") while (currentX != x1) { currentX += directionX currentY += directionY hits.add("$currentX,$currentY") } } return hits } } }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
2,362
adventofcode-2021
Apache License 2.0
src/main/kotlin/com/sk/set1/127. Word Ladder.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set1 class Solution127 { fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int { val seen = mutableSetOf<String>() val q = ArrayDeque<String>() q.add(beginWord) var ladder = 1 while (q.isNotEmpty()) { var size = q.size while (size-- > 0) { val start = q.removeFirst() for (end in wordList) { if (seen.contains(end)) continue if (distance(start, end) == 1) { seen.add(end) if (end == endWord) return ladder + 1 q.add(end) } } } ladder++ } return 0 } private fun distance(start: String, end: String): Int { var c = 0 for (i in start.indices) { if (start[i] != end[i]) c++ if (c == 2) return c } return c } /** * TC: O(n * m * 26) = O(n * m) * SC: O(n) * n: No of words in list * m: Size of each word */ fun ladderLength2(beginWord: String, endWord: String, wordList: List<String>): Int { val dict = wordList.toMutableSet() // Contains words yet to visit val q = ArrayDeque<String>() // Contains next step of words to traverse q.add(beginWord) var ladder = 1 while (q.isNotEmpty()) { var size = q.size while (size-- > 0) { val start = q.removeFirst().toCharArray() for (i in start.indices) { val old = start[i] for (c in 'a'..'z') { start[i] = c val end = String(start) if (dict.contains(end)) { if (end == endWord) { return ladder + 1 } q.add(end) dict.remove(end) } } start[i] = old } } ladder++ } return 0 } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,223
leetcode-kotlin
Apache License 2.0
Retos/Reto #7 - EL SOMBRERO SELECCIONADOR [Media]/kotlin/Mariopolonia0.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
package EjercicioKotlin.Mouredev /* * Crea un programa que simule el comportamiento del sombrero selccionador del * universo mágico de <NAME>. * - De ser posible realizará 5 preguntas (como mínimo) a través de la terminal. * - Cada pregunta tendrá 4 respuestas posibles (también a selecciona una a través de terminal). * - En función de las respuestas a las 5 preguntas deberás diseñar un algoritmo que * coloque al alumno en una de las 4 casas de Hogwarts: * (Gryffindor, Slytherin , Hufflepuff y Ravenclaw) * - Ten en cuenta los rasgos de cada casa para hacer las preguntas * y crear el algoritmo seleccionador: * Por ejemplo, en Slytherin se premia la ambición y la astucia. */ fun main() { val pregunta = Question().getQuestions() val repuestas = arrayOf(0, 0, 0, 0) println("EL SOMBRERO SELECCIONADOR") var contador = 0 while (contador < pregunta.size) { printQuestion(pregunta.get(contador)) print("Selecciones una respuesta:") val select = readLine()!!.toInt() when (select) { 1 ->{ repuestas[0]++ contador++ } 2 ->{ repuestas[1]++ contador++ } 3 ->{ repuestas[2]++ contador++ } 4 ->{ repuestas[3]++ contador++ } else->{ print("\nlas respuestas son del 1 al 4") print("\ndigite un numero del 1 al 4\n") } } } sortingHat(repuestas) } fun printQuestion(pregunta: Question){ println(pregunta.enuciado) println(pregunta.opcion1) println(pregunta.opcion2) println(pregunta.opcion3) println(pregunta.opcion4) } fun sortingHat(answer :Array<Int>){ var positionmayor = 0 var mayor = 0 for (item in 0..answer.size - 1){ if (answer[item] > mayor){ mayor = answer[item] positionmayor = item } } println("\n-----------------------------") when(positionmayor){ 0->{ println("Tu casa es la Gryffindor") } 1->{ println("Tu casa es la Slytherin ") } 2->{ println("Tu casa es la Hufflepuff ") } 3->{ println("Tu casa es la Ravenclaw") } } println("-----------------------------") } class Question( var enuciado: String = "", var opcion1: String = "", var opcion2: String = "", var opcion3: String = "", var opcion4: String = "" ) { fun getQuestions(): Array<Question> { return arrayOf( Question( "\n¿Qué color le gusta mas?", "1.Rojo", "2.Verde", "3.Amarillo", "4.Azul" ), Question( "\n¿Qué animal le gusta mas", "1.Leon", "2.Serpiente", "3.Tejón", "4.Águila" ), Question( "\n¿Qué mago le gusta mas?", "1.<NAME>", "2.<NAME>", "3.Nymphadora Tonks", "4.L<NAME>" ), Question( "\n¿Qué especialidad lo indentifica mas?", "1.Fuerza", "2.Determinacion", "3.Lealtad", "4.Erudicion" ), Question( "\n¿A que le das mas valor?", "1.lealtad", "2.ambicion", "3.honor", "4.valentia" ) ) } }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
3,769
retos-programacion-2023
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/AddTwoNumbers.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import com.daily.algothrim.linked.LinkedNode /** * 两数相加(leetcode 2) * * 给出两个非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。 * * 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 * * 您可以假设除了数字 0 之外,这两个数都不会以 0开头。 * * 示例: * * 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) * 输出:7 -> 0 -> 8 * 原因:342 + 465 = 807 */ class AddTwoNumbers { companion object { @JvmStatic fun main(args: Array<String>) { AddTwoNumbers().solution(LinkedNode(2, LinkedNode(4, LinkedNode(3))), LinkedNode(5, LinkedNode(6, LinkedNode(4))))?.printAll() } } /** * O(m+n) */ fun solution(l1: LinkedNode<Int>?, l2: LinkedNode<Int>?): LinkedNode<Int>? { var a = l1 var b = l2 val result = LinkedNode(-1) var temp: LinkedNode<Int>? = result var carry = 0 while (a != null || b != null) { val add = (a?.value ?: 0) + (b?.value ?: 0) + carry carry = add / 10 temp?.next = LinkedNode(add % 10) temp = temp?.next a = a?.next b = b?.next if (carry > 0) temp?.next = LinkedNode(carry) } return result.next } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,506
daily_algorithm
Apache License 2.0
src/Day06.kt
devheitt
573,207,407
false
{"Kotlin": 11944}
import java.lang.RuntimeException fun main() { // first approach fun part1(input: List<String>): Int { val data = input[0] var i = 3 while (i < data.length) { val first = data[i - 3] val second = data[i - 2] val third = data[i - 1] val forth = data[i] i++ if(setOf(first, second, third, forth).size == 4) return i } return 0 } fun solve(data: String, size: Int): Int { val windowed = data.windowed(size) for((index, window) in windowed.withIndex()) { if(window.toSet().size == size) return index + size } throw RuntimeException() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) val input = readInput("Day06") println(solve(input[0], 4)) println(solve(input[0], 14)) }
0
Kotlin
0
0
a9026a0253716d36294709a547eaddffc6387261
999
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day15.kt
EmRe-One
568,569,073
false
{"Kotlin": 166986}
package tr.emreone.adventofcode.days import kotlinx.coroutines.* import tr.emreone.adventofcode.manhattanDistanceTo import tr.emreone.kotlin_utils.Logger.logger import tr.emreone.kotlin_utils.math.Point2D import kotlin.math.abs object Day15 { private val REPORT_PATTERN = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() open class AreaElem(val coord: Point2D) class Beacon(coord: Point2D) : AreaElem(coord) {} class Sensor(coord: Point2D, val closestBeacon: Beacon) : AreaElem(coord) { val distanceToClosestBeacon = coord.manhattanDistanceTo(closestBeacon.coord) override fun toString(): String { return "Sensor(coord=${coord}, distanceToClosestBeacon=$distanceToClosestBeacon)" } } class Area { val beacons = mutableListOf<Beacon>() val sensors = mutableListOf<Sensor>() companion object { fun parseInput(input: List<String>): Area { return Area().apply { input.forEach { line -> val (sensorX, sensorY, beaconX, beaconY) = REPORT_PATTERN.matchEntire(line)!!.destructured val beacon = Beacon(Point2D(beaconX.toLong(), beaconY.toLong())) beacons.add(beacon) sensors.add(Sensor(Point2D(sensorX.toLong(), sensorY.toLong()), beacon)) } // for part 2 sensors.sortBy { it.coord.x } } } } fun getMapElemAt(coord: Point2D): AreaElem? { sensors.find { it.coord == coord }?.let { return it } beacons.find { it.coord == coord }?.let { return it } return null } fun calcTuningFrequency(coord: Point2D): Long { return coord.x * 4_000_000 + coord.y } fun findDistressBeaconInRow(area: Area, yRow: Long, xMin: Long, xMax: Long): Point2D? { var x = xMin area.sensors.forEach { s -> val currentPoint = Point2D(x, yRow) // if currentPoint is in a sensor area if (s.coord.manhattanDistanceTo(currentPoint) <= s.distanceToClosestBeacon) { x = s.coord.x + s.distanceToClosestBeacon - abs(s.coord.y - yRow) + 1 } } return if (x <= xMax) Point2D(x, yRow) else { null } } // Printing methods private fun isInSensorArea(coord: Point2D): Boolean { return sensors.any { s -> coord.manhattanDistanceTo(s.coord) <= s.distanceToClosestBeacon } } fun printMap(min: Long, max: Long) { val sb = StringBuilder() sb.appendLine() (min..max).forEach { y -> (min..max).forEach { x -> val currentPoint = Point2D(x, y) when (this.getMapElemAt(currentPoint)) { is Beacon -> { sb.append("B") } is Sensor -> { sb.append("S") } else -> { if (this.isInSensorArea(currentPoint)) { sb.append("#") } else { sb.append(" ") } } } } sb.appendLine() } logger.info { sb.toString() } } } fun part1(input: List<String>, yCoord: Long): Int { val area = Area.parseInput(input) val setOfPossibleCoords = mutableSetOf<Point2D>() area.sensors.forEach { s -> val xMin = s.coord.x - (s.distanceToClosestBeacon - abs(s.coord.y - yCoord)) val xMax = s.coord.x + (s.distanceToClosestBeacon - abs(s.coord.y - yCoord)) if (xMin <= xMax) { (xMin..xMax).forEach { x -> // if area is not empty val currentPoint = Point2D(x, yCoord) if (area.getMapElemAt(currentPoint) == null && s.coord.manhattanDistanceTo(currentPoint) <= s.distanceToClosestBeacon) { setOfPossibleCoords.add(currentPoint) } } } } // area.printMap(-10, 30) return setOfPossibleCoords.size } fun part2(input: List<String>, minCoord: Long, maxCoord: Long): Long { val area = Area.parseInput(input) var foundLocation: Point2D? = null try { runBlocking { launch(Dispatchers.Default.limitedParallelism(20)) { (minCoord..maxCoord) .shuffled() .flatMap { y -> listOf(async { if (foundLocation == null) { val distressBeacon = area.findDistressBeaconInRow(area, y, minCoord, maxCoord) if (distressBeacon != null) { logger.debug { "found distress beacon at $distressBeacon, --> Blocking Coroutines ..." } foundLocation = distressBeacon [email protected]() } } }) } } } } catch (e: Exception) { // do nothing :D } return foundLocation?.let { area.calcTuningFrequency(it) } ?: -1 } }
0
Kotlin
0
0
a951d2660145d3bf52db5cd6d6a07998dbfcb316
5,865
advent-of-code-2022
Apache License 2.0
egklib/src/commonTest/kotlin/electionguard/tally/LagrangeCoefficientsTest.kt
votingworks
425,905,229
false
{"Kotlin": 1268236}
package electionguard.tally import electionguard.core.productionGroup import electionguard.decrypt.computeLagrangeCoefficient import kotlin.test.Test import kotlin.test.assertEquals private val group = productionGroup() class LagrangeCoefficientsTest { @Test fun testLagrangeCoefficientAreIntegral() { testLagrangeCoefficientAreIntegral(listOf(1)) testLagrangeCoefficientAreIntegral(listOf(1, 2)) testLagrangeCoefficientAreIntegral(listOf(1, 2, 3)) testLagrangeCoefficientAreIntegral(listOf(1, 2, 3, 4)) testLagrangeCoefficientAreIntegral(listOf(2, 3, 4)) testLagrangeCoefficientAreIntegral(listOf(2, 4, 5), false) testLagrangeCoefficientAreIntegral(listOf(2, 3, 4, 5)) testLagrangeCoefficientAreIntegral(listOf(5, 6, 7, 8, 9)) testLagrangeCoefficientAreIntegral(listOf(2, 3, 4, 5, 6, 7, 8, 9)) testLagrangeCoefficientAreIntegral(listOf(2, 3, 4, 5, 6, 7, 9)) testLagrangeCoefficientAreIntegral(listOf(2, 3, 4, 5, 6, 9), false) testLagrangeCoefficientAreIntegral(listOf(2, 3, 4, 5, 6, 7, 11), false) } fun testLagrangeCoefficientAreIntegral(coords: List<Int>, exact: Boolean = true) { println(coords) for (coord in coords) { val others: List<Int> = coords.filter { !it.equals(coord) } val coeff: Int = computeLagrangeCoefficientInt(coord, others) val numer: Int = computeLagrangeNumerator(others) val denom: Int = computeLagrangeDenominator(coord, others) val coeffQ = group.computeLagrangeCoefficient(coord, others.map { it}) println("($coord) $coeff == ${numer} / ${denom} rem ${numer % denom} == $coeffQ") if (exact) { assertEquals(0, numer % denom) } } println() } } fun computeLagrangeCoefficientInt(coordinate: Int, others: List<Int>): Int { if (others.isEmpty()) { return 1 } val numerator: Int = others.reduce { a, b -> a * b } val diff: List<Int> = others.map { degree: Int -> degree - coordinate } val denominator = diff.reduce { a, b -> a * b } return numerator / denominator } fun computeLagrangeNumerator(others: List<Int>): Int { if (others.isEmpty()) { return 1 } return others.reduce { a, b -> a * b } } fun computeLagrangeDenominator(coordinate: Int, others: List<Int>): Int { if (others.isEmpty()) { return 1 } val diff: List<Int> = others.map { degree: Int -> degree - coordinate } return diff.reduce { a, b -> a * b } }
32
Kotlin
3
8
4e759afe9d57fa8f8beea82c3b78b920351023d8
2,584
electionguard-kotlin-multiplatform
MIT License
src/main/kotlin/algorithms/OverlapGraphsOofN.kt
jimandreas
377,843,697
false
null
@file:Suppress("unused") package algorithms /** * See also: * http://rosalind.info/problems/grph/ * Overlap Graphs * * Problem A graph whose nodes have all been labeled can be represented by an adjacency list, in which each row of the list contains the two node labels corresponding to a unique edge. A directed graph (or digraph) is a graph containing directed edges, each of which has an orientation. That is, a directed edge is represented by an arrow instead of a line segment; the starting and ending nodes of an edge form its tail and head, respectively. The directed edge with tail v and head w is represented by (v,w) (but not by (w,v)). A directed loop is a directed edge of the form (v,v) For a collection of strings and a positive integer k, the overlap graph for the strings is a directed graph Ok in which each string is represented by a node, and string s is connected to string t with a directed edge when there is a length k suffix of s that matches a length k prefix of t, as long as s≠t; we demand s≠t to prevent directed loops in the overlap graph (although directed cycles may be present). Given: A collection of DNA strings in FASTA format having total length at most 10 kbp. Return: The adjacency list corresponding to O3. You may return edges in any order. KEY HERE is O3 - three characters must match in prefix and suffix! */ class OverlapGraphsOofN { /** * iterate through all strings, matching each against the other * if there is a matching prefix/suffix in a pair, then add the pair to the * suffix->prefix hash map. */ fun overlappingPrefixAndSuffix(mustMatchCount: Int, s: List<String>): HashMap<String, MutableList<String>> { val outputMap: HashMap<String, MutableList<String>> = hashMapOf() // add a placeholder list for all strings for (str in s) { outputMap[str] = mutableListOf() } val numStrings = s.size for (i in 0 until numStrings) { for (j in i + 1 until numStrings) { val si = s[i] // for ease of debugging val sj = s[j] val silen = si.length val sjlen = sj.length if (si.substring(0, mustMatchCount) == sj.substring(sjlen - mustMatchCount, sjlen)) { outputMap[sj]!!.add(si) } if (sj.substring(0, mustMatchCount) == si.substring(silen - mustMatchCount, silen)) { outputMap[si]!!.add(sj) } } } return outputMap } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
2,585
stepikBioinformaticsCourse
Apache License 2.0
kotlin/07.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
import kotlin.math.absoluteValue class Day7 : Day<List<Int>>("07") { override fun dataStar1(lines: List<String>): List<Int> = lines[0].split(",").map(String::toInt) override fun dataStar2(lines: List<String>): List<Int> = dataStar1(lines) override fun star1(data: List<Int>): Number = data.minOf { it }.rangeTo(data.maxOf { it }) .minOfOrNull { pos -> data.sumOf { (it - pos).absoluteValue } } ?: 0 // Sum 0 to n: n * (n+1) / 2 override fun star2(data: List<Int>): Number = data.minOf { it }.rangeTo(data.maxOf { it }) .minOf { pos -> data.map { crab -> (crab - pos).absoluteValue }.sumOf { diff -> diff * (diff + 1) / 2 } } // Sum 0 to n: (0..n).sum() override val additionalStar2Solutions: List<(List<Int>) -> Number> get() = listOf { data -> data.minOf { it }.rangeTo(data.maxOf { it }) .minOf { pos -> data.sumOf { (1..(it - pos).absoluteValue).sum() } } } } fun main() { Day7()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
984
advent-of-code-2021
MIT License
src/arrays/Experiment.kt
agapeteo
157,038,583
false
null
package arrays import java.io.File import java.util.* fun main() { printDirContent(File("/Users/emix/go/src/practicalalgo")) } fun printDirContent(dir: File, tabsCount: Int = 0, ignoreHidden: Boolean = true) { require(dir.exists()) { "$dir must exist" } require(dir.isDirectory) { "$dir must be directory" } val tabs = StringBuilder() repeat(tabsCount) { tabs.append("\t") } val dirOutput = StringBuilder() dirOutput.append(tabs).append(dir.name).append("/") println(dirOutput.toString()) for (file in dir.listFiles()) { if (ignoreHidden && file.name.startsWith(".")) continue if (file.isDirectory) { printDirContent(file, tabsCount + 1, ignoreHidden) } else { val fileOutput = StringBuilder() fileOutput.append("\t").append(tabs).append(file.name) println(fileOutput.toString()) } } } fun <T> binarySearch(list: List<Comparable<in T>>, value: T): Int { var lowIdx = 0 var highIdx = list.size - 1 while (lowIdx <= highIdx) { val midIdx = lowIdx + (highIdx - lowIdx) / 2 when { list[midIdx] == value -> return midIdx list[midIdx] < value -> lowIdx = midIdx + 1 list[midIdx] > value -> highIdx = midIdx - 1 } } return -(lowIdx + 1) } fun <T> binarySearchRecursive(list: List<Comparable<in T>>, value: T, lowIdx: Int = 0, highIdx: Int = list.size - 1): Int { val notFound = -(lowIdx + 1) if (lowIdx > highIdx) { return notFound } val midIdx = lowIdx + (highIdx - lowIdx) / 2 return when { list[midIdx] == value -> midIdx list[midIdx] < value -> binarySearchRecursive(list, value, midIdx + 1, highIdx) list[midIdx] > value -> binarySearchRecursive(list, value, lowIdx, midIdx - 1) else -> notFound } } fun <T> binarySearchLowestIndex(list: List<Comparable<in T>>, value: T): Int { var lowIdx = -1 var highIdx = list.size while (lowIdx + 1 < highIdx) { val midIdx = (lowIdx + highIdx) ushr 1 // shifting but to right is same as dividing by 2 if (list[midIdx] >= value) { highIdx = midIdx } else { lowIdx = midIdx } } return when (value) { list[highIdx] -> highIdx else -> -(highIdx + 1) } } fun average(numbers: List<Int>): Int { var sum = 0 for (n in numbers) { sum += n } return sum / numbers.size } fun max(numbers: List<Int>): Int { var max = Int.MIN_VALUE for (n in numbers) { if (n > max) { max = n } } return max } fun idxOf(value: Int, list: List<Int>): Int { for ((idx, element) in list.withIndex()) { if (element == value) return idx } return -1 }
0
Kotlin
0
1
b5662c8fe416e277c593931caa1b29b7f017ef60
2,820
kotlin-data-algo
MIT License
Java_part/AssignmentC/src/Q2.kt
enihsyou
58,862,788
false
{"Java": 77446, "Python": 65409, "Kotlin": 35032, "C++": 6214, "C": 3796, "CMake": 818}
import kotlin.math.max import kotlin.text.Typography.times /* 某一印刷厂有6项加工任务,对印刷车间和装订车间所需时间如表所示。完成每项任务都要先去印刷车间印刷, 再去装订车间装订。问怎样安排这6项加工任务的加工工序,使得加工总工时最少。 任务 J1 J2 J3 J4 J5 J6 印刷车间 3 12 5 2 9 11 装订车间 8 10 9 6 3 1 */ fun main(args: Array<String>) { val input = arrayListOf( 3 to 8, 12 to 10, 5 to 9, 2 to 6, 9 to 3, 11 to 1 ) val rearrange = mutableListOf<Triple<Int, Int, Int>>() input.mapIndexed { index: Int, pair: Pair<Int, Int> -> rearrange.add(Triple(index, 0, pair.first)) rearrange.add(Triple(index, 1, pair.second)) } val a = mutableListOf<Int>() val b = mutableListOf<Int>() while (a.size + b.size < input.size) { rearrange.sortBy { it.third } val (job, machine, _) = rearrange.first() rearrange.removeIf { it.first == job } if (machine == 0) a += job else if (machine == 1) b += job } val result = a + b println(result.map { "Job ${it + 1}" }) }
0
Java
0
0
09a109bb26e0d8d165a4d1bbe18ec7b4e538b364
1,306
Sorting-algorithm
MIT License
src/day23/Code.kt
fcolasuonno
221,697,249
false
null
package day23 import java.io.File fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed.toMutableList())}") println("Part 2 = ${part2(parsed.toMutableList())}") } val opcodes = mapOf<String, (String, String) -> ((MutableMap<String, Long>, MutableList<Triple<String, String, String>>) -> Unit)>( "inc" to { a: String, _ -> { regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> -> regs[a] = regs.getValue(a) + 1 regs["ip"] = regs.getValue("ip") + 1 } }, "dec" to { a: String, _ -> { regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> -> regs[a] = regs.getValue(a) - 1 regs["ip"] = regs.getValue("ip") + 1 } }, "tgl" to { a: String, _ -> { regs: MutableMap<String, Long>, input: MutableList<Triple<String, String, String>> -> val position = regs.getValue("ip").toInt() + regs.getValue(a).toInt() val instruction = input.getOrNull(position) if (instruction != null) { input[position] = instruction.copy(first = when (instruction.first) { "inc" -> "dec" "dec" -> "inc" "tgl" -> "inc" "jnz" -> "cpy" "cpy" -> "jnz" else -> "" }) } regs["ip"] = regs.getValue("ip") + 1 } }, "cpy" to { a: String, b: String -> { regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> -> regs[b] = (a.toLongOrNull() ?: regs.getValue(a)) regs["ip"] = regs.getValue("ip") + 1 } }, "jnz" to { a: String, b: String -> { regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> -> if ((a.toLongOrNull() ?: regs.getValue(a)) != 0L) { regs["ip"] = regs.getValue("ip") + (b.toLongOrNull() ?: regs.getValue(b)) } else { regs["ip"] = regs.getValue("ip") + 1 } } } ) private val lineStructure = """(\w+) (-?\w+) ?(-?\w+)?""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (op, op1, op2) = it.toList() Triple(op, op1, op2) } }.requireNoNulls() fun part1(input: MutableList<Triple<String, String, String>>): Any? = mutableMapOf<String, Long>("a" to 7).withDefault { 0L }.let { regs -> generateSequence { input.getOrNull(regs.getValue("ip").toInt()) }.map { (op, op1, op2) -> opcodes.getValue(op)(op1, op2)(regs, input) }.last() regs["a"] } fun part2(input: MutableList<Triple<String, String, String>>): Any? = mutableMapOf<String, Long>("a" to 12).withDefault { 0L }.let { regs -> generateSequence { val ip = regs.getValue("ip").toInt() input.getOrNull(ip)?.let { ip to it } }.map { (index, ops) -> val (op, op1, op2) = ops if (op == "jnz" && op2 == "-2") { if (input.slice((index - 2) until index).map { it.first } == listOf("inc", "dec")) { val a = (input[index - 2].second) val b = (input[index - 1].second) regs[a] = regs[a]!! + regs[b]!! regs[b] = 0 } } if (op == "jnz" && op2 == "-5") { if (input.slice((index - 5) until index).map { it.first } == listOf("cpy", "inc", "dec", "jnz", "dec")) { val a = (input[index - 4].second) val b = (input[index - 5].second) val c = (input[index - 2].second) val d = (input[index - 1].second) regs[a] = regs[a]!! + (b.toLongOrNull() ?: regs[b]!!) * regs[d]!! regs[c] = 0 regs[d] = 0 } } opcodes.getValue(op)(op1, op2)(regs, input) }.last() regs["a"] }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
4,338
AOC2016
MIT License
src/main/kotlin/com/hopkins/aoc/day17/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day17 import java.io.File import kotlin.math.abs const val debug = true const val part = 1 lateinit var mapSize: Point lateinit var map: Map<Point, Int> lateinit var endPoint: Point val minDistanceLookup = mutableMapOf<PathKey, Int>() /** Advent of Code 2023: Day 17 */ fun main() { // Step 1: Read the file input val lines: List<String> = File("input/input17.txt").readLines() if (debug) { println("Step 1: Read file") println("=======") println(" num lines: ${lines.size}") } // Step 2: Parse the map val mapWidth = lines[0].length val mapHeight = lines.size mapSize = Point.of(mapWidth, mapHeight) map = lines.flatMapIndexed { y, line -> line.mapIndexed { x, c -> Point.of(x, y) to c.digitToInt() } }.toMap() endPoint = Point.of(mapWidth - 1, mapHeight - 1) if (debug) { println("\nStep 2: Build map") println("=======") if (debug) { println(" map size: $mapSize") } println("Map") println("===") for (y in 0 until mapHeight) { print(" ") for (x in 0 until mapWidth) { print(map[Point.of(x, y)]) } println() } } // Step 3: Build up a list of all points in the map val allPoints = (0 until mapHeight).flatMap { y -> (0 until mapWidth).map { x -> Point.of(x, y) } } if (debug) { println("\nStep 3: Build all points list") println("=======") println(" Num points: ${allPoints.size}") } // Step 4: Build a lookup of minimum distance from each path to the end for (start in allPoints) { val key = PathKey.of(start, endPoint) minDistanceLookup[key] = findBestDirectPathCached(start, endPoint) } if (debug) { println("\nStep 4: Build minimum distance map") println("=======") for (y in 0 until mapHeight) { print(" ") for (x in 0 until mapWidth) { if (x > 0) print(" | ") val key = PathKey.of(Point.of(x, y), endPoint) print("%03d".format(minDistanceLookup[key]!!)) } println() } } // Step 5: find the best path via A* search val comparator = compareBy<Path>({ it.distance }, { it.estimatedCost }) var count = 0 for (offsetA in 1 until mapWidth) { for (offsetB in offsetA - 1 downTo 0) { val cornerPoint = endPoint.subtract(Point.of(offsetA, offsetA)) val startPoints = setOf( cornerPoint.add(Point.of(offsetB, 0)), cornerPoint.add(Point.of(0, offsetB)) ) for (startPoint in startPoints) { var bestPaths = listOf(Path(0, listOf(startPoint))) var currentBestLookup = mutableMapOf<Point, Int>() while (bestPaths.isNotEmpty()) { count++ if (count == 1000000) { println(".") count = 0 } val bestPath = bestPaths.first() val lastPoint = bestPath.points.last() //println("Last point= $lastPoint") val newPaths = mutableListOf<Path>() val bestFinal = currentBestLookup[endPoint] for (direction in directions) { val nextPoint = lastPoint.add(direction) if (!isInBounds(nextPoint, mapSize)) { continue } if (nextPoint.x < cornerPoint.x || nextPoint.y < cornerPoint.y) { continue } if (direction.isOpposite(bestPath.lastDirection)) { continue } if (direction == bestPath.lastThreeDirections) { continue } val cost = map[nextPoint]!! val newCost = bestPath.cost + cost val estimatedCost = newCost + minDistanceLookup[PathKey.of(nextPoint, endPoint)]!! if (bestFinal != null && estimatedCost > bestFinal) { continue } val newPath = Path(newCost, bestPath.points + listOf(nextPoint)) val currentBest = currentBestLookup[nextPoint] if (currentBest == null || currentBest >= newPath.cost) { currentBestLookup[nextPoint] = newPath.cost } newPaths.add(newPath) } bestPaths = (bestPaths.drop(1) + newPaths) .filter { it.estimatedCost < (bestFinal ?: Int.MAX_VALUE) } .sortedWith(comparator) } if (startPoint == cornerPoint) { println("start=$startPoint") println(" best: ${currentBestLookup[endPoint]}") // Incorrect [0,0]: 853 } minDistanceLookup[PathKey.of(startPoint, endPoint)] = currentBestLookup[endPoint]!! } } } } val directPathCache = mutableMapOf<PathKey, Int>() val bestDirections = listOf(Point.of(1, 0), Point.of(0, 1)) fun findBestDirectPathCached(start: Point, end: Point): Int { val key = PathKey.of(start, end) val cached = directPathCache[key] if (cached != null) { return cached } val result = findBestDirectPath(start, end) directPathCache[key] = result return result } fun findBestDirectPath(start: Point, end: Point): Int { if (start == end) { return 0 } else if (start.distanceTo(end) == 1) { return map[end]!! } else { return bestDirections .map { start.add(it) } .filter { isInBounds(it, mapSize) } .minOf { map[it]!! + findBestDirectPathCached(it, end) } } } fun printPath(path: Path, mapSize: Point) { val pointSet = path.points.toSet() for (y in 0 until mapSize.x) { for (x in 0 until mapSize.y) { val point = Point.of(x, y) if (pointSet.contains(point)) { print("#") } else { print(".") } } println() } val cost = path.cost println("Cost: $cost") } fun calculateBestPaths(start: Point, end: Point, bestPathMap: Map<PathKey, List<Path>>): List<Path> { val bestExistingPaths = bestPathMap[PathKey.of(start, end)] // Find the points we need to check paths for val pointsToTest = directions.map { start.add(it) }.filter { isInBounds(it, mapSize) } // Generate the new paths val newPaths = pointsToTest.flatMap { point -> val key = PathKey.of(point, end) val paths = bestPathMap[key] if (paths == null) { emptyList() } else { paths .map { path -> Path(path.cost + map[point]!!, listOf(start) + path.points) } .filter { it.hasValidStart() } } } // Only keep track of the two best paths return ((bestExistingPaths ?: emptyList()) + newPaths).distinct().sortedBy { it.cost }.take(2) } data class PathKey private constructor(val start: Point, val end: Point) { companion object { private val cache = mutableMapOf<Point, PathKey>() fun of(start: Point, end: Point): PathKey { return if (end == endPoint) { cache.computeIfAbsent(start) { start -> PathKey(start, end) } } else { PathKey(start, end) } } } } fun isInBounds(point: Point, size: Point) = point.x >= 0 && point.y >= 0 && point.x < size.x && point.y < size.y val directions = listOf( Point.of(-1, 0), Point.of(1, 0), Point.of(0, -1), Point.of(0, 1) ) data class Path(val cost: Int, val points: List<Point>) { val estimatedCost = cost + minDistanceLookup[PathKey.of(points.last(), endPoint)]!! val distance = points.last().distanceTo(endPoint) val lastDirection = if (points.size < 2) { Point.ORIGIN } else { val (a, b) = points.takeLast(2) b.subtract(a) } val lastThreeDirections = if (points.size < 4) { Point.ORIGIN } else { val (d1, d2, d3) = points.takeLast(4).zipWithNext().map { (a, b) -> b.subtract(a) } if (d1 == d2 && d2 == d3) { d1 } else { Point.ORIGIN } } fun getTail(): Path = Path(0, points.takeLast(4)) fun findNextPaths(map: Map<Point, Int>): List<Path> { val lastPoint = points.last() return directions // Filter paths that go out of bounds .filter { isInBounds(lastPoint.add(it), mapSize) } // Filter paths that are not allowed .filter { isDirectionAllowed(it) } .map { direction -> val nextPoint = lastPoint.add(direction) val nextCost = cost + map[nextPoint]!! Path(nextCost, points + listOf(nextPoint)) } } private fun isDirectionAllowed(direction: Point): Boolean { if (points.size <= 1) { return true } val (secondLast, last) = points.takeLast(2) val lastDirection = last.subtract(secondLast) if (direction.isOpposite(lastDirection)) { // We can't switch to the opposite direction return false } if (points.size < 4) { return true } val lastDirections = points.takeLast(4).zipWithNext { a, b -> b.subtract(a) } if (lastDirections.all { it == direction}) { // We can't go in the same direction 4 times in a row return false } return true } fun hasValidStart(): Boolean { if (points.size <= 2) { return true } val directions = points.zipWithNext().map { (a, b) -> b.subtract(a) } val (da, db) = directions.takeLast(2) for (i in directions.indices) { val two = directions.drop(i).take(2) if (two.size == 2 && two[0].isOpposite(two[1])) { return false } val four = directions.drop(i).take(4) if (four.size == 4 && four[0] == four[1] && four[0] == four[2] && four[0] == four[3]) { return false } } return true } } data class Point private constructor(val x: Int, val y: Int) { fun add(dx: Int, dy: Int): Point = of(x + dx, y + dy) fun add(delta: Point) = add(delta.x, delta.y) fun subtract(other: Point) = of(x - other.x, y - other.y) fun isOpposite(other: Point): Boolean = (x == other.x * -1) && (y == other.y * -1) fun isOrigin(): Boolean = x == 0 && y == 0 fun distanceTo(other: Point): Int = abs(other.x - x) + abs(other.y - y) companion object { private val lookup = (-1 until 200).flatMap {y -> (-1 until 200).map {x -> Point(x, y) } } val ORIGIN = of(0, 0) fun of(x: Int, y: Int): Point { if (x >= -1 && x < 200 && y >= -1 && y < 200) { return lookup[(y + 1) * 201 + (x + 1)].also { require(it.x == x && it.y == y)} } else { return Point(x, y) } } } }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
11,834
aoc2023
MIT License
archive/720/solve.kt
daniellionel01
435,306,139
false
null
/* === #720 Unpredictable Permutations - Project Euler === Consider all permutations of $\{1, 2, \ldots N\}$, listed in lexicographic order.For example, for $N=4$, the list starts as follows: $$\displaylines{ (1, 2, 3, 4) \\ (1, 2, 4, 3) \\ (1, 3, 2, 4) \\ (1, 3, 4, 2) \\ (1, 4, 2, 3) \\ (1, 4, 3, 2) \\ (2, 1, 3, 4) \\ \vdots }$$ Let us call a permutation $P$ unpredictable if there is no choice of three indices $i \lt j \lt k$ such that $P(i)$, $P(j)$ and $P(k)$ constitute an arithmetic progression. For example, $P=(3, 4, 2, 1)$ is not unpredictable because $P(1), P(3), P(4)$ is an arithmetic progression. Let $S(N)$ be the position within the list of the first unpredictable permutation. For example, given $N = 4$, the first unpredictable permutation is $(1, 3, 2, 4)$ so $S(4) = 3$. You are also given that $S(8) = 2295$ and $S(32) \equiv 641839205 \pmod{1\,000\,000\,007}$. Find $S(2^{25})$. Give your answer modulo $1\,000\,000\,007$. Difficulty rating: 35% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
1,089
euler
MIT License
aoc_2023/src/main/kotlin/problems/day24/Hailstone.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day24 class Hailstone(val pos: HailCoordinate, val vel: HailCoordinate) { override fun toString(): String { return "$pos @ $vel" } fun intersectionXY(other: Hailstone): HailCoordinate? { if (other.vel.x.toDouble() == 0.0 || other.vel.y.toDouble() == 0.0 || (this.vel.x / other.vel.x - this.vel.y / other.vel.y).abs() < 0.0001.toBigDecimal()) { return null } val m1 = this.vel.y - other.vel.y * (this.vel.x / other.vel.x) val value = other.pos.y - this.pos.y + other.vel.y * ((other.pos.x - this.pos.x) / -other.vel.x) val actualM1 = value / m1 if (actualM1 < 0.toBigDecimal()) { return null } val actualM2 = (this.pos.x - other.pos.x + this.vel.x * actualM1) / other.vel.x if (actualM2 < 0.toBigDecimal()) { return null } val x = this.pos.x + this.vel.x * actualM1 val y = this.pos.y + this.vel.y * actualM1 return HailCoordinate(x, y, 0.toBigDecimal()) } fun intersectionXZ(other: Hailstone): HailCoordinate? { if (other.vel.x.toDouble() == 0.0 || other.vel.z.toDouble() == 0.0 || (this.vel.x / other.vel.x - this.vel.z / other.vel.z).abs() < 0.0001.toBigDecimal()) { return null } val m1 = this.vel.z - other.vel.z * (this.vel.x / other.vel.x) val value = other.pos.z - this.pos.z + other.vel.z * ((other.pos.x - this.pos.x) / -other.vel.x) val actualM1 = value / m1 if (actualM1 < 0.toBigDecimal()) { return null } val actualM2 = (this.pos.x - other.pos.x + this.vel.x * actualM1) / other.vel.x if (actualM2 < 0.toBigDecimal()) { return null } val x = this.pos.x + this.vel.x * actualM1 val z = this.pos.z + this.vel.z * actualM1 return HailCoordinate(x, 0.toBigDecimal(), z) } fun intersectionXYZ(other: Hailstone): HailCoordinate? { val intXY = intersectionXY(other) ?: return null val intXZ = intersectionXZ(other) ?: return null if (intXY.x == intXZ.x) return HailCoordinate(intXY.x, intXY.y, intXZ.z) return null } fun planeParalelLines(other: Hailstone): HailPlane? { if ((this.vel.x / other.vel.x - this.vel.y / other.vel.y).abs() < 0.0001.toBigDecimal()) { print("parallel x and y") } if ((this.vel.x / other.vel.x - this.vel.y / other.vel.y).abs() < 0.0001.toBigDecimal() && (this.vel.x / other.vel.x - this.vel.z / other.vel.z).abs() < 0.0001.toBigDecimal() ) { // Paralel val p = this.pos val m1 = this.vel val m2 = this.pos.subtract(other.pos) val a = m1.y * m2.z - m1.z * m2.y val b = m1.z * m2.x - m1.x * m2.z val c = m1.x * m2.y - m1.y * m2.x val d = a * -p.x + b * -p.y + c * -p.z return HailPlane(a, b, c, d) } return null } fun relativePosition(other: Hailstone): Int { if ((this.vel.x / other.vel.x - this.vel.y / other.vel.y).abs() < 0.0001.toBigDecimal() && (this.vel.x / other.vel.x - this.vel.z / other.vel.z).abs() < 0.0001.toBigDecimal() ) { // paralel or overlapped return 0 } val intersection = intersectionXYZ(other) if (intersection != null) { return 1 } return 2 } fun toPlanes(): List<HailPlane> { val plane1 = HailPlane( this.vel.y, -this.vel.x, 0.toBigDecimal(), -this.pos.x * this.vel.y - (-this.pos.y) * this.vel.x ) val plane2 = HailPlane( this.vel.z, 0.toBigDecimal(), -this.vel.x, -this.pos.x * this.vel.z - (-this.pos.z) * this.vel.x ) return listOf(plane1, plane2) } override fun hashCode(): Int { var result = pos.hashCode() result = 31 * result + vel.hashCode() return result } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
4,119
advent-of-code-2023
MIT License
src/main/kotlin/net/navatwo/adventofcode2023/day3/Day3Solution.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023.day3 import net.navatwo.adventofcode2023.Coord import net.navatwo.adventofcode2023.Grid import net.navatwo.adventofcode2023.forEachCoord import net.navatwo.adventofcode2023.framework.ComputedResult import net.navatwo.adventofcode2023.framework.Solution sealed class Day3Solution : Solution<Day3Solution.EngineSchematic> { abstract class SolveContext<DP_COORD : Any>( private val schematic: EngineSchematic, private val uninitialized: DP_COORD, private val symbol: DP_COORD, private val empty: DP_COORD, ) { // Lazy due to needing uninitialized, etc. protected val dp: Grid<DP_COORD> by lazy(LazyThreadSafetyMode.NONE) { Grid( grid = schematic.grid.rows.mapTo(ArrayList(schematic.grid.rowCount)) { row -> row.mapTo(ArrayList(row.size)) { uninitialized } }, ) } fun solve(): Long { var result = 0L schematic.grid.forEachCoord { x, y -> result += visitCoord(Coord(x, y)) } return result } protected abstract fun visitCoord( coord: Coord, ): Long protected abstract fun partNumber( value: Int, firstCoord: Coord, lastCoord: Coord, ): DP_COORD protected open fun initializeGear(coord: Coord): DP_COORD = symbol protected fun initialize(coord: Coord): DP_COORD { val char = schematic.grid[coord].char when { char == '.' -> dp[coord] = empty char.isDigit() -> { computePartNumberForCoord(coord) } char == '*' -> dp[coord] = initializeGear(coord) // symbol else -> { dp[coord] = symbol } } return dp[coord] } protected fun initializeNeighbours(coord: Coord) { coord.forEachNeighbour { x, y -> if (dp[x, y] == uninitialized) { val neighbourCoord = Coord(x, y) initialize(neighbourCoord) } } } private fun computePartNumberForCoord( coord: Coord, ) { val searchCoordY = coord.y var searchCoordX = coord.x - 1 while (true) { val potentialPartNumber = schematic.getOrNull(searchCoordX, searchCoordY) if (potentialPartNumber == null || !potentialPartNumber.char.isDigit()) { searchCoordX += 1 break } searchCoordX -= 1 } val firstPartNumberCoord = Coord(searchCoordX, searchCoordY) var partNumber = 0 while (true) { val potentialPartNumber = schematic.getOrNull(searchCoordX, searchCoordY) if (potentialPartNumber == null || !potentialPartNumber.char.isDigit()) { break } partNumber = partNumber * 10 + potentialPartNumber.char.digitToInt() searchCoordX += 1 } val lastPartNumberCoord = Coord(searchCoordX - 1, searchCoordY) val foundPartNumber = partNumber(partNumber, firstPartNumberCoord, lastPartNumberCoord) for (x in firstPartNumberCoord.x..lastPartNumberCoord.x) { dp[x, searchCoordY] = foundPartNumber } } } data object Part1 : Day3Solution() { override fun solve(input: EngineSchematic): ComputedResult { val solveContext = Part1SolveContext(input) return ComputedResult.Simple(solveContext.solve()) } sealed interface DPCoord { data object Uninitialized : DPCoord data object Empty : DPCoord data class PartNumber(val partNumber: Int, val firstCoord: Coord, val lastCoord: Coord) : DPCoord data object Symbol : DPCoord } private class Part1SolveContext(schematic: EngineSchematic) : SolveContext<DPCoord>( schematic = schematic, uninitialized = DPCoord.Uninitialized, empty = DPCoord.Empty, symbol = DPCoord.Symbol, ) { override fun partNumber(value: Int, firstCoord: Coord, lastCoord: Coord): DPCoord { return DPCoord.PartNumber(value, firstCoord, lastCoord) } override fun visitCoord( coord: Coord, ): Long { return when (dp[coord]) { DPCoord.Uninitialized -> { val initialized = initialize(coord) if (initialized is DPCoord.Symbol) { sumSymbolPartNumbers(coord) } else { 0L } } DPCoord.Symbol -> { sumSymbolPartNumbers(coord) } DPCoord.Empty, is DPCoord.PartNumber -> 0L } } private fun sumSymbolPartNumbers(coord: Coord): Long { initializeNeighbours(coord) var result = 0L val visitedCoords = mutableSetOf<Coord>() coord.forEachNeighbour { x, y -> val neighbourCoord = Coord(x, y) // avoid double adds if (!visitedCoords.add(neighbourCoord)) { return@forEachNeighbour } val dpCoord = dp[neighbourCoord] if (dpCoord is DPCoord.PartNumber) { result += dpCoord.partNumber.toLong() // avoid adding the same part number multiple times for (cx in dpCoord.firstCoord.x..dpCoord.lastCoord.x) { visitedCoords.add(neighbourCoord.copy(x = cx)) } } } return result } } } data object Part2 : Day3Solution() { override fun solve(input: EngineSchematic): ComputedResult { val solveContext = Part2SolveContext(input) return ComputedResult.Simple(solveContext.solve()) } sealed interface DPCoord { data object Uninitialized : DPCoord data object Empty : DPCoord data class PartNumber(val partNumber: Int, val firstCoord: Coord, val lastCoord: Coord) : DPCoord data object Symbol : DPCoord data object Gear : DPCoord } private class Part2SolveContext(schematic: EngineSchematic) : SolveContext<DPCoord>( schematic = schematic, uninitialized = DPCoord.Uninitialized, empty = DPCoord.Empty, symbol = DPCoord.Symbol, ) { override fun partNumber(value: Int, firstCoord: Coord, lastCoord: Coord): DPCoord { return DPCoord.PartNumber(value, firstCoord, lastCoord) } override fun initializeGear(coord: Coord): DPCoord { initializeNeighbours(coord) var partNumberCount = 0 val visitedCoords = mutableSetOf<Coord>() coord.forEachNeighbour { x, y -> val neighbourCoord = Coord(x, y) if (!visitedCoords.add(neighbourCoord)) return@forEachNeighbour val partNumber = dp[x, y] if (partNumber is DPCoord.PartNumber) { partNumberCount += 1 // avoid adding the same part number multiple times for (cx in partNumber.firstCoord.x..partNumber.lastCoord.x) { visitedCoords.add(neighbourCoord.copy(x = cx)) } } } return if (partNumberCount == 2) { DPCoord.Gear } else { DPCoord.Symbol } } override fun visitCoord(coord: Coord): Long { return when (val dpCoord = dp[coord]) { DPCoord.Uninitialized -> { val initialized = initialize(coord) if (initialized is DPCoord.Gear) { computeGearRatio(initialized, coord) } else { 0L } } is DPCoord.Gear -> { computeGearRatio(dpCoord, coord) } else -> 0L } } private fun computeGearRatio( @Suppress("UNUSED_PARAMETER") // witness gear: DPCoord.Gear, coord: Coord, ): Long { var result = 1L val visitedCoords = mutableSetOf<Coord>() coord.forEachNeighbour { x, y -> val neighbourCoord = Coord(x, y) // avoid double adds if (!visitedCoords.add(neighbourCoord)) { return@forEachNeighbour } val dpCoord = dp[neighbourCoord] if (dpCoord is DPCoord.PartNumber) { result *= dpCoord.partNumber.toLong() // avoid adding the same part number multiple times for (cx in dpCoord.firstCoord.x..dpCoord.lastCoord.x) { visitedCoords.add(neighbourCoord.copy(x = cx)) } } } return result } } } override fun parse(lines: Sequence<String>): EngineSchematic { val grid = lines .map { line -> line.mapTo(mutableListOf()) { EngineSchematic.Value(it) } } .toMutableList() return EngineSchematic(Grid(grid)) } @JvmInline value class EngineSchematic( val grid: Grid<Value> ) { operator fun get(coord: Coord): Value = grid[coord] fun getOrNull(coord: Coord): Value? = grid.getOrNull(coord) fun getOrNull(x: Int, y: Int): Value? = grid.getOrNull(x, y) @JvmInline value class Value(val char: Char) } }
0
Kotlin
0
0
4b45e663120ad7beabdd1a0f304023cc0b236255
8,870
advent-of-code-2023
MIT License
src/main/kotlin/com/polydus/aoc18/Day8.kt
Polydus
160,193,832
false
null
package com.polydus.aoc18 class Day8: Day(8){ //https://adventofcode.com/2018/day/8 init { //partOne() partTwo() } fun partOne(){ val list = ArrayList<Int>() input.forEach { println() val chars = it.toCharArray() var i = 0 while (i < chars.size){ var end = i for(j in i until chars.size){ if(chars[j] == ' ' || j == chars.size - 1){ end = j if(j == chars.size - 1) end++ break } } list.add(it.substring(i, end).toInt()) i = end + 1 } } val root = Node(list[0], list[1], null, "a") var current = root var i = 2 while (i < list.size){ if(current.children.size < current.childrenSize){ current.children.add(Node(list[i], list[i + 1], current, i.toString())) current = current.children.last() i += 2 } else if(current.entries.size < current.entriesSize){ current.entries.add(list[i]) i++ } while(current.full()){ current = current.parent?: break } } var value = 0 var node: Node? = root while(node != null){ if(node.index < node.children.size){ node.index++ node = node.children[node.index - 1] } else { value += node.entries.sum() node = node.parent?: break } } println("answer is $value") } fun partTwo(){ val list = ArrayList<Int>() input.forEach { println() val chars = it.toCharArray() var i = 0 while (i < chars.size){ var end = i for(j in i until chars.size){ if(chars[j] == ' ' || j == chars.size - 1){ end = j if(j == chars.size - 1) end++ break } } list.add(it.substring(i, end).toInt()) i = end + 1 } } var nodes = 0 val root = Node(list[0], list[1], null, "0") var current = root var i = 2 while (i < list.size){ if(current.children.size < current.childrenSize){ nodes++ current.children.add(Node(list[i], list[i + 1], current, nodes.toString())) current = current.children.last() i += 2 } else if(current.entries.size < current.entriesSize){ current.entries.add(list[i]) i++ } while(current.full()){ current = current.parent?: break } } var node: Node? = root while(node != null){ //println("node start $node index ${node.index} value ${node.value}") if(node.childrenSize > 0){ if(node.index < node.children.size){ node.index++ node = node.children[node.index - 1] } else { for(j in 0 until node.entries.size){ val index = node.entries[j] if(index < node.children.size + 1){ //value += node.children[entryValue].entries.sum() node.value += node.children[index - 1].value//node[] //node = node.children[entryValue - 1] } } //println("node $node set to ${node.value}") node = node.parent?: break } } else { node.value = node.entries.sum() //println("node $node set to ${node.value}") node = node.parent?: break } } println("answer is ${root.value}") } class Node(val childrenSize: Int, val entriesSize: Int, val parent: Node?, val name: String){ val children = ArrayList<Node>() val entries = ArrayList<Int>() var index = 0 fun header(): Int{ return entriesSize + childrenSize } fun full(): Boolean{ return (header()) == children.size + entries.size } var value = 0 override fun toString(): String { return name } } }
0
Kotlin
0
0
e510e4a9801c228057cb107e3e7463d4a946bdae
4,705
advent-of-code-2018
MIT License
src/main/kotlin/model/method/SecantMethod.kt
Roggired
348,065,860
false
null
package model.method import model.equation.Equation import kotlin.math.abs import kotlin.math.sign class SecantMethod( equation: Equation, private val secondDerivativeInLeftBound: Double, private val secondDerivativeInRightBound: Double, leftBound: Double, rightBound: Double, accuracy: Double ): Method(equation, leftBound, rightBound, accuracy) { private val solutions: ArrayList<Double> = ArrayList() private var step = 1 override fun getTable(): ArrayList<Array<String>> { val table = ArrayList<Array<String>>() val titles = arrayOf("Step №", "xk-1", "f(xk-1)", "xk", "f(xk)", "xk+1", "f(xk+1)", "|xk - xk+1|") table.add(titles) var xk_1 = calcX0() var xk = calcX1() var fxk_1 = equation.evaluate(xk_1) var fxk = equation.evaluate(xk) var dif = abs(xk - xk_1) var xk_next: Double = xk var fxk_next: Double = fxk while (dif > accuracy && abs(fxk) > accuracy) { xk_next = xk - fxk * ((xk - xk_1) / (fxk - fxk_1)) fxk_next = equation.evaluate(xk_next) addToTable(step, xk_1, fxk_1, xk, fxk, xk_next, fxk_next, dif, table) addSolutions(xk_next, fxk_next, dif) step++ xk_1 = xk fxk_1 = fxk xk = xk_next fxk = fxk_next dif = abs(xk - xk_1) } addToTable(step, xk_1, fxk_1, xk, fxk, xk_next, fxk_next, dif, table) addSolutions(xk_next, fxk_next, dif) return table } private fun calcX0(): Double = if (equation.evaluate(rightBound).sign * secondDerivativeInRightBound.sign >= 0) rightBound else leftBound private fun calcX1(): Double = if (equation.evaluate(rightBound).sign * secondDerivativeInRightBound.sign >= 0) rightBound - 2 * accuracy else leftBound - 2 * accuracy private fun addToTable(step: Int, xk_1: Double, fxk_1: Double, xk: Double, fxk: Double, xk_next: Double, fxk_next: Double, dif: Double, table: ArrayList<Array<String>>) = table.add(arrayOf(step.toString(), xk_1.toString(), fxk_1.toString(), xk.toString(), fxk.toString(), xk_next.toString(), fxk_next.toString(), dif.toString())) private fun addSolutions(xk_next: Double, fxk_next: Double, dif: Double) = (abs(fxk_next) <= accuracy || dif <= accuracy) && !solutions.contains(xk_next) && solutions.add(xk_next) override fun getSolutions(): ArrayList<Double> = solutions override fun getStepQuantity(): Int = step }
0
Kotlin
0
2
983935fc1ca2a6da564ff8300c2a53cc85dd8701
2,598
maths_lab2
MIT License
test/src/me/anno/tests/maths/ContinuousMedian.kt
AntonioNoack
456,513,348
false
{"Kotlin": 9845766, "C": 236481, "GLSL": 9454, "Java": 6754, "Lua": 4404}
package me.anno.tests.maths import me.anno.maths.ContinuousMedian import me.anno.maths.Maths import me.anno.utils.types.Floats.f6 import me.anno.utils.types.Floats.f6s import me.anno.utils.types.Strings.withLength import kotlin.math.sqrt fun main() { testDirect() testDiscrete() testContinuous() } fun testDirect() { val instance = ContinuousMedian(0f, 3000f, 6) instance.bucketWeights[0] = 6f instance.bucketWeights[1] = 7f instance.bucketWeights[2] = 9f instance.bucketWeights[3] = 8f instance.bucketWeights[4] = 4f instance.bucketWeights[5] = 6f instance.total = instance.bucketWeights.sum() instance.median = Float.NaN println(instance.median) // shall be 1388.889 } fun testDiscrete() { val instance = ContinuousMedian(0f, 3000f, 6) instance.add(250f, 6f) instance.add(750f, 7f) instance.add(1250f, 9f) instance.add(1750f, 8f) instance.add(2250f, 4f) instance.add(2750f, 6f) instance.total = instance.bucketWeights.sum() instance.median = Float.NaN println(instance.median) // shall be 1388.889 // actual, with sharpness 1.1: 1393.785 -> good enough :) } fun testContinuous() { val samples = 1 val testsEach = 23 val min = 0f val max = 1f for (numBuckets in 3..4) { val thinness = 0.01f / numBuckets val instance = ContinuousMedian(min, max, numBuckets) var errSum = 0f var errSum2 = 0f val t = 0.5f val minValue = t / numBuckets val maxValue = 1f - minValue println("$numBuckets buckets, test values: $minValue .. $maxValue") for (i in 0 until testsEach) { instance.reset() val testValue = Maths.mix(min, max, Maths.mix(minValue, maxValue, i / (testsEach - 1f))) for (j in 0 until samples) { val rv = if (samples == 1) 0.5f else j / (samples - 1f) // random.nextFloat() // instance.add(testValue + (rv - 0.5f) * thinness) } val median = instance.median val error = median - testValue val relErr = error / thinness println( "relErr: ${relErr.f6s().withLength(12)}, " + "got ${median.f6()} instead of ${testValue.f6()}, " + "target index: ${((testValue - min) * instance.scale).f6()}, " + "data: ${instance.bucketWeights.joinToString()}" ) // LOGGER.info("$testValue +/- $thinness*0.5 -> ${instance.bucketWeights.joinToString()}") errSum += relErr * relErr errSum2 += relErr } println("stdDev: ${sqrt(errSum / testsEach)}, bias: ${errSum2 / testsEach}\n") } }
0
Kotlin
3
17
3d0d08566309a84e1e68585593b76844633132c4
2,745
RemsEngine
Apache License 2.0
src/main/kotlin/days/Day5.kt
felix-ebert
433,847,657
false
{"Kotlin": 12718}
package days class Day5 : Day(5) { data class Position(val x: Int, val y: Int) override fun partOne(): Any { val maxPosition = inputList.flatMap { it.split(" -> ", ",").map { str -> str.toInt() } }.maxOrNull()!!.plus(1) val grid = Array(maxPosition) { IntArray(maxPosition) } inputList.forEach { line -> val start = line.substringBefore(" -> ").split(',').zipWithNext() .map { Position(it.first.toInt(), it.second.toInt()) }.first() val end = line.substringAfter(" -> ").split(',').zipWithNext() .map { Position(it.first.toInt(), it.second.toInt()) }.first() if (start.x == end.x) { val y1 = minOf(start.y, end.y) val y2 = maxOf(start.y, end.y) for (y in y1..y2) { grid[y][start.x]++ } } if (start.y == end.y) { val x1 = minOf(start.x, end.x) val x2 = maxOf(start.x, end.x) for (x in x1..x2) { grid[start.y][x]++ } } } return grid.flatMap { it.asIterable() }.count { it >= 2 } } override fun partTwo(): Any { return "todo" } }
0
Kotlin
0
2
cf7535d1c4f8a327de19660bb3a9977750894f30
1,277
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/be/twofold/aoc2021/Day06.kt
jandk
433,510,612
false
{"Kotlin": 10227}
package be.twofold.aoc2021 object Day06 { fun part1(input: List<Int>): Long { return solve(input, 80) } fun part2(input: List<Int>): Long { return solve(input, 256) } private fun solve(input: List<Int>, days: Int): Long { val groups = LongArray(9) input.forEach { groups[it]++ } for (i in 1..days) { val new = groups[0] System.arraycopy(groups, 1, groups, 0, groups.size - 1) groups[6] += new groups[8] = new } return groups.sum() } } fun main() { val input = Util.readFile("/day06.txt") .first() .split(',') .map { it.toInt() } println("Part 1: ${Day06.part1(input)}") println("Part 2: ${Day06.part2(input)}") }
0
Kotlin
0
0
2408fb594d6ce7eeb2098bc2e38d8fa2b90f39c3
784
aoc2021
MIT License
Kotlin/src/PermutationsII.kt
TonnyL
106,459,115
false
null
/** * Given a collection of numbers that might contain duplicates, return all possible unique permutations. * * For example, * [1,1,2] have the following unique permutations: * [ * [1,1,2], * [1,2,1], * [2,1,1] * ] * * Accepted. */ class PermutationsII { fun permuteUnique(nums: IntArray): List<List<Int>> { val results = mutableListOf<List<Int>>() if (nums.isEmpty()) { return results } if (nums.size == 1) { return results.apply { add(mutableListOf(nums[0])) } } val ints = IntArray(nums.size - 1) System.arraycopy(nums, 0, ints, 0, nums.size - 1) val set = mutableSetOf<List<Int>>() for (list in permuteUnique(ints)) { for (i in 0..list.size) { val tmp = mutableListOf<Int>() tmp.addAll(list) tmp.add(i, nums[nums.size - 1]) set.add(tmp) } } return results.apply { addAll(set) } } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,041
Windary
MIT License
common/src/commonMain/kotlin/io/github/opletter/courseevals/common/data/Ratings.kt
opLetter
597,896,755
false
{"Kotlin": 390300}
package io.github.opletter.courseevals.common.data typealias Ratings = List<List<Int>> class RatingStats( val ratings: List<Double>, val numResponses: Int, ) fun Collection<Ratings>.combine(): Ratings { return reduce { accByQuestion, responsesByQ -> // nums from each entry get zipped with each other, by question accByQuestion.zip(responsesByQ) { accRatings, ratings -> accRatings.zip(ratings, Int::plus) } } } fun List<Int>.getRatingStats(): Pair<Double, Int> { val numResponses = sum().takeIf { it > 0 } ?: return 0.0 to 0 val ave = mapIndexed { index, num -> (index + 1) * num }.sum().toDouble() / numResponses return ave to numResponses } fun List<Int>.getRatingAve(): Double = getRatingStats().first fun Ratings.getAvesAndTotal(): RatingStats { // list of aves per question + ave # of responses return RatingStats(ratings = map { it.getRatingAve() }, numResponses = map { it.sum() }.average().toInt()) } fun Map<String, RatingStats>.getAveStats(): RatingStats { val stats = this.values.reduce { acc, pair -> RatingStats( ratings = acc.ratings.zip(pair.ratings) { a, b -> a + b }, numResponses = acc.numResponses + pair.numResponses ) } return RatingStats(ratings = stats.ratings.map { it / this.size }, numResponses = stats.numResponses) }
0
Kotlin
0
3
44077ad89388cead3944975e975840580d2c9d0b
1,384
course-evals
MIT License
atcoder/arc156/c_research.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc156 import kotlin.random.Random fun main() { val n = readInt() val nei = List(n) { mutableListOf<Int>() } repeat(n - 1) { val (u, v) = readInts().map { it - 1 } nei[u].add(v); nei[v].add(u) } val r = Random(566) val byDegree = nei.indices.sortedBy { nei[it].size } val p = IntArray(n) for (i in nei.indices) { p[byDegree[i]] = byDegree[n - 1 - i] } while (true) { var perfect = true for (v in nei.indices) { for (u in nei[v]) if (u < v) { val vv = p[v] val uu = p[u] if (uu in nei[vv]) { if (v == uu && u == vv) continue perfect = false var w: Int while (true) { w = r.nextInt(n) if (w != v && w != u) break } val temp = p[v]; p[v] = p[u]; p[u] = p[w]; p[w] = temp } } } if (perfect) break } println(p.map { it + 1 }.joinToString(" ")) } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,034
competitions
The Unlicense
yandex/y2022/finals/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2022.finals fun main() { val (a, m) = readLongs() val ps = mutableListOf<Long>() var b = a for (p in 2..b) { if (b == 1L) break if (p * p > b) { ps.add(b) break } if (b % p != 0L) continue ps.add(p) while (b % p == 0L) b /= p } var ans = Long.MAX_VALUE for (r in 0..2) { if ((r != 0) and (3 in ps)) continue var cur = 1L for (p in ps) { b = a var k = 0L while (b % p == 0L) { b /= p k++ } k *= m if (p == 3L) { cur = maxOf(cur, searchUsual(k, 3)) continue } if (r == 0) { cur = maxOf(cur, 3 * searchUsual(k, p)) continue } cur = maxOf(cur, searchUnusual(k, p, r)) } ans = minOf(ans, cur) } println(ans) } fun searchUsual(m: Long, p: Long): Long { var low = 0L var high = p * m while (low + 1 < high) { val mid = low + (high - low) / 2 var x = mid / p var count = 0L while (x > 0) { count += x x /= p } if (count >= m) high = mid else low = mid } return high } fun searchUnusual(m: Long, p: Long, r: Int): Long { var low = 0L var high = m * p while (low + 1 < high) { val mid = low + (high - low) / 2 var t = p var count = 0L while (t <= 3 * mid + r) { val f = (if ((t % 3).toInt() == r) t else 2 * t) / 3 if (mid >= f) { count += (mid - f) / t + 1 } // if (t * 3 > 3 * mid + r) break if (t >= mid + 1) break t *= p } if (count >= m) high = mid else low = mid } return 3 * high + r } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun readLongs() = readStrings().map { it.toLong() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,698
competitions
The Unlicense
year2018/src/main/kotlin/net/olegg/aoc/year2018/day19/Day19.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day19 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2018.Command import net.olegg.aoc.year2018.DayOf2018 import net.olegg.aoc.year2018.Ops /** * See [Year 2018, Day 19](https://adventofcode.com/2018/day/19) */ object Day19 : DayOf2018(19) { private val OPS_PATTERN = "(\\w+) (\\d+) (\\d+) (\\d+)".toRegex() override fun first(): Any? { return solve(listOf(0, 0, 0, 0, 0, 0)) } override fun second(): Any? { return solve(listOf(1, 0, 0, 0, 0, 0)) } private fun solve(registers: List<Long>): Long { val pointer = lines .first() .let { it.split(" ")[1].toIntOrNull() ?: 0 } val program = lines .drop(1) .mapNotNull { line -> OPS_PATTERN.matchEntire(line)?.let { match -> val (opRaw, aRaw, bRaw, cRaw) = match.destructured return@mapNotNull Command(Ops.valueOf(opRaw.uppercase()), aRaw.toInt(), bRaw.toInt(), cRaw.toInt()) } } val regs = registers.toLongArray() (0..1_000_000_000_000L).forEach { _ -> val instruction = regs[pointer].toInt() if (instruction !in program.indices) { return regs[0] } program[instruction].apply(regs) regs[pointer]++ } return 0 } } fun main() = SomeDay.mainify(Day19)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,301
adventofcode
MIT License
gcj/y2020/kickstart_b/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.kickstart_b const val M = 1000000000 val DX = intArrayOf(1, 0, M - 1, 0) val DY = intArrayOf(0, 1, 0, M - 1) const val DIR_ROSE = "ESWN" private fun solve(): String { val s = "1(" + readLn() + ")" var i = 0 fun readMove(): Pair<Int, Int> { val c = s[i++] if (c in DIR_ROSE) return DIR_ROSE.indexOf(c).let { DX[it] to DY[it] } i++ var x = 0 var y = 0 while (s[i] != ')') { val (moveX, moveY) = readMove() x = (x + moveX) % M y = (y + moveY) % M } val (moveX, moveY) = listOf(x, y).map { (it.toLong() * (c - '0') % M).toInt() } i++ return moveX to moveY } val (x, y) = readMove() return "${x + 1} ${y + 1}" } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
815
competitions
The Unlicense
kotlin.web.demo.server/examples/Examples/Longer examples/Maze/Maze.kt
JetBrains
3,602,279
false
null
/** * Let's Walk Through a Maze. * * Imagine there is a maze whose walls are the big 'O' letters. * Now, I stand where a big 'I' stands and some cool prize lies * somewhere marked with a '$' sign. Like this: * * OOOOOOOOOOOOOOOOO * O O * O$ O O * OOOOO O * O O * O OOOOOOOOOOOOOO * O O I O * O O * OOOOOOOOOOOOOOOOO * * I want to get the prize, and this program helps me do so as soon * as I possibly can by finding a shortest path through the maze. */ package maze /** * Declare a point class. */ data class Point(val row: Int, val col: Int) /** * This function looks for a path from maze.start to maze.end through * free space (a path does not go through walls). One can move only * straight up, down, left or right, no diagonal moves allowed. */ fun findPath(maze: Maze): List<Point>? { val previous = hashMapOf<Point, Point>() val queue = java.util.ArrayDeque<Point>() val visited = hashSetOf<Point>() queue.offer(maze.start) visited.add(maze.start) while (!queue.isEmpty()) { val cell = queue.poll() if (cell == maze.end) break for (newCell in maze.neighbors(cell)) { if (newCell in visited) continue previous[newCell] = cell queue.offer(newCell) visited.add(newCell) } } val pathToStart = generateSequence(previous[maze.end]) { cell -> previous[cell] } .takeWhile { cell -> cell != maze.start } .toList() .ifEmpty { return null } return pathToStart.reversed() } fun Maze.neighbors(cell: Point): List<Point> = neighbors(cell.row, cell.col) /** * Find neighbors of the ([row], [col]) cell that are not walls and not outside the maze */ fun Maze.neighbors(row: Int, col: Int): List<Point> = listOfNotNull( cellIfFree(row - 1, col), cellIfFree(row, col - 1), cellIfFree(row + 1, col), cellIfFree(row, col + 1) ) fun Maze.cellIfFree(row: Int, col: Int): Point? { if (row !in 0 until height) return null if (col !in 0 until width) return null if (walls[row][col]) return null return Point(row, col) } fun Maze.hasWallAt(point: Point) = walls[point.row][point.col] /** * A data class that represents a maze */ class Maze( // Number or columns val width: Int, // Number of rows val height: Int, // true for a wall, false for free space val walls: Array<BooleanArray>, // The starting point (must not be a wall) val start: Point, // The target point (must not be a wall) val end: Point ) /** A few maze examples here */ fun main(args: Array<String>) { walkThroughMaze("I $") walkThroughMaze("I O $") walkThroughMaze(""" O $ O O O O I """) walkThroughMaze(""" OOOOOOOOOOO O $ O OOOOOOO OOO O O OOOOO OOOOO O O O OOOOOOOOO O OO OOOOOO IO """) walkThroughMaze(""" OOOOOOOOOOOOOOOOO O O O$ O O OOOOO O O O O OOOOOOOOOOOOOO O O I O O O OOOOOOOOOOOOOOOOO """) } // UTILITIES fun walkThroughMaze(input: String) { val maze = makeMaze(input) println("Maze:") val path = findPath(maze) for (row in 0 until maze.height) { for (col in 0 until maze.width) { val cell = Point(row, col) print(when { maze.hasWallAt(cell) -> "O" cell == maze.start -> "I" cell == maze.end -> "$" path != null && cell in path -> "*" else -> " " }) } println("") } println("Result: " + if (path == null) "No path" else "Path found") println("") } /** * A maze is encoded in the string s: the big 'O' letters are walls. * I stand where a big 'I' stands and the prize is marked with * a '$' sign. * * Example: * * OOOOOOOOOOOOOOOOO * O O * O$ O O * OOOOO O * O O * O OOOOOOOOOOOOOO * O O I O * O O * OOOOOOOOOOOOOOOOO */ fun makeMaze(input: String): Maze { val lines = input.split('\n') val longestLine = lines.maxBy { it.length }!! val data = Array(lines.size) { BooleanArray(longestLine.length) } var start: Point? = null var end: Point? = null for (row in lines.indices) { for (col in lines[row].indices) { when ( val cell = lines[row][col]) { 'O' -> data[row][col] = true 'I' -> start = Point(row, col) '$' -> end = Point(row, col) } } } return Maze(longestLine.length, lines.size, data, start ?: throw IllegalArgumentException("No starting point in the maze (should be indicated with 'I')"), end ?: throw IllegalArgumentException("No goal point in the maze (should be indicated with a '$' sign)")) }
2
Kotlin
75
169
74eb79018f3f6b8d023fa0ef1a4b853503fe97a5
5,212
kotlin-web-demo
Apache License 2.0
src/main/kotlin/net/mguenther/adventofcode/day16/Day16.kt
mguenther
115,937,032
false
null
package net.mguenther.adventofcode.day16 /** * @author <NAME> (<EMAIL>) */ val alphabet: Array<String> = arrayOf( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z") class Promenade(size: Int) { private val numberOfPrograms: Int = size.coerceAtMost(25) private var positions: Array<String> = emptyArray() init { positions = alphabet.copyOfRange(0, numberOfPrograms) } private fun spin(size: Int) { val newPositions: Array<String> = Array(numberOfPrograms, { "" }) for (i in 0 until numberOfPrograms) { val newIndex = (i + size).rem(numberOfPrograms) newPositions[newIndex] = positions[i] } positions = newPositions } private fun exchange(positionA: Int, positionB: Int) { val swap = positions[positionA] positions[positionA] = positions[positionB] positions[positionB] = swap } private fun partner(programA: String, programB: String) { var positionA: Int = -1; var positionB: Int = -1; for (i in 0 until positions.size) { if (positions[i].equals(programA)) positionA = i if (positions[i].equals(programB)) positionB = i if (positionA != -1 && positionB != -1) break } exchange(positionA, positionB) } fun dance(moves: List<Move>) { dance(moves, 1) } fun dance(moves: List<Move>, times: Int) { repeat(times, { time -> run { val percentage = ((time.toFloat() / times.toFloat()) * 100).toInt() println("Applying dance #" + time + " (" + percentage + "%)") moves.forEach(this::apply) } }) } private fun apply(move: Move) = when(move) { is Spin -> spin(move.size) is Exchange -> exchange(move.positionA, move.positionB) is Partner -> partner(move.programA, move.programB) } override fun toString(): String { return positions.reduce { l: String, r: String -> l + r } } } sealed class Move data class Spin(val size: Int) : Move() data class Exchange(val positionA: Int, val positionB: Int) : Move() data class Partner(val programA: String, val programB: String) : Move()
0
Kotlin
0
0
c2f80c7edc81a4927b0537ca6b6a156cabb905ba
2,366
advent-of-code-2017
MIT License
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/algorithms/ShortestPathFasterAlgorithm.kt
alexandrepiveteau
630,931,403
false
{"Kotlin": 132267}
@file:JvmName("Algorithms") @file:JvmMultifileClass package io.github.alexandrepiveteau.graphs.algorithms import io.github.alexandrepiveteau.graphs.* import io.github.alexandrepiveteau.graphs.internal.collections.IntDequeue import kotlin.jvm.JvmMultifileClass import kotlin.jvm.JvmName /** * Returns the list of parents for each vertex in the shortest path tree from the [from] vertex. * * @param from the [Vertex] to start the search from. * @return the map of parents for each vertex in the shortest path tree from the [from] vertex. */ private fun <N> N.shortestPathFasterAlgorithmParents( from: Vertex, ): VertexMap where N : SuccessorsWeight { val enqueued = BooleanArray(size) val distances = IntArray(size) { Int.MAX_VALUE } val queue = IntDequeue() val parents = VertexMap(size) { Vertex.Invalid } distances[index(from)] = 0 enqueued[index(from)] = true queue.addLast(index(from)) // TODO : Handle negative cycles and throw an exception when one is found. This will be the case // when the number of relaxations exceeds a certain threshold. while (queue.size > 0) { val v1 = vertex(queue.removeFirst()) enqueued[index(v1)] = false forEachSuccessor(v1) { v2, weight -> val d1 = distances[index(v1)] val d2 = distances[index(v2)] if (d1 != Int.MAX_VALUE && (d2 == Int.MAX_VALUE || d1 + weight < d2)) { distances[index(v2)] = d1 + weight parents[v2] = v1 if (!enqueued[index(v2)]) { enqueued[index(v2)] = true queue.addLast(index(v2)) } } } } return parents } /** * Computes the shortest path from the given [from] vertex to all the other vertices in the network, * using the * [Shortest Path Faster Algorithm](https://en.wikipedia.org/wiki/Shortest_path_faster_algorithm), * which is a variant of the Bellman-Ford algorithm specialized for sparse graphs. * * ## Asymptotic complexity * - **Time complexity**: O(|N| * |E|), where |N| is the number of vertices, and |E| is the number * of edges in this graph. * - **Space complexity**: O(|N|), where |N| is the number of vertices in this graph. * * @param from the source vertex. * @return the subnetwork of the shortest path from the given [from] vertex to all the other * vertices in the network. * @throws NoSuchVertexException if the given [from] vertex is not in this graph. */ public fun <N> N.shortestPathFasterAlgorithm( from: Vertex, ): DirectedNetwork where N : SuccessorsWeight { if (from !in this) throw NoSuchVertexException() return computeNetwork(shortestPathFasterAlgorithmParents(from)) } /** * Computes the shortest path from the given [from] vertex to the given [to] vertex in the network, * using the * [Shortest Path Faster Algorithm](https://en.wikipedia.org/wiki/Shortest_path_faster_algorithm), * which is a variant of the Bellman-Ford algorithm specialized for sparse graphs. * * ## Asymptotic complexity * - **Time complexity**: O(|N| * |E|), where |N| is the number of vertices, and |E| is the number * of edges in this graph. * - **Space complexity**: O(|N|), where |N| is the number of vertices in this graph. * * @param from the source vertex. * @param to the target vertex. * @return the shortest path from the given [from] vertex to the given [to] vertex in the network, * or `null` if no such path exists. * @throws NoSuchVertexException if the given [from] vertex or [to] vertex is not in this graph. */ public fun <N> N.shortestPathFasterAlgorithm( from: Vertex, to: Vertex, ): VertexArray? where N : SuccessorsWeight { if (from !in this) throw NoSuchVertexException() if (to !in this) throw NoSuchVertexException() return computePath(shortestPathFasterAlgorithmParents(from), from, to) }
9
Kotlin
0
6
a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f
3,779
kotlin-graphs
MIT License
app/src/main/kotlin/kotlinadventofcode/2015/2015-09.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.* import com.github.h0tk3y.betterParse.lexer.* import kotlinadventofcode.Day import kotlin.math.max import kotlin.math.min class `2015-09` : Day { data class City(val name: String, val distances: Map<City, Int>) { override fun equals(other: Any?): Boolean = other is City && name == other.name override fun hashCode(): Int = name.hashCode() } fun parse(input: String): Set<City> { val distancesByCityName: MutableMap<String, MutableMap<City, Int>> = mutableMapOf() val cities: MutableSet<City> = mutableSetOf() val grammar = object: Grammar<List<Unit>>() { val newLine by literalToken("\n") val to by literalToken(" to ") val equals by literalToken(" = ") val digits by regexToken("\\d+") val name by regexToken("[a-zA-Z]+") val city by name use { val city = City(text, distancesByCityName.getOrPut(text) { mutableMapOf() }) cities += city city } val distance by digits use { text.toInt() } val line by city and -to and city and -equals and distance map { (leftCity, rightCity, distance) -> fun saveCityMappings(city1: City, city2: City) { distancesByCityName.getOrPut(city1.name) { mutableMapOf() } += city2 to distance } saveCityMappings(leftCity, rightCity) saveCityMappings(rightCity, leftCity) } override val rootParser by separatedTerms(line, newLine) } grammar.parseToEnd(input) return cities } override fun runPartOneNoUI(input: String): String { return run(input, ::min) } fun run(input: String, bestChooser: (Int, Int) -> Int): String { val cities = parse(input) val paths: ArrayDeque<List<City>> = ArrayDeque(cities.map { listOf(it) }) var best: Int? = null while (!paths.isEmpty()) { val path = paths.removeLast() if (path.size == cities.size) { var distance = 0 for (i in 0..path.size - 2) { distance += path[i].distances[path[i + 1]] ?: throw Exception("City distance missing.") } best = best?.let { bestChooser(it, distance) } ?: distance } else { path.last().distances .filterKeys { it !in path } .forEach { (city, _) -> paths.addLast(path + city) } } } return best.toString() } /** * After verifying your solution on the AoC site, run `./ka continue` to add a test for it. */ override fun runPartTwoNoUI(input: String): String { return run(input, ::max) } override val defaultInput = """Tristram to AlphaCentauri = 34 Tristram to Snowdin = 100 Tristram to Tambi = 63 Tristram to Faerun = 108 Tristram to Norrath = 111 Tristram to Straylight = 89 Tristram to Arbre = 132 AlphaCentauri to Snowdin = 4 AlphaCentauri to Tambi = 79 AlphaCentauri to Faerun = 44 AlphaCentauri to Norrath = 147 AlphaCentauri to Straylight = 133 AlphaCentauri to Arbre = 74 Snowdin to Tambi = 105 Snowdin to Faerun = 95 Snowdin to Norrath = 48 Snowdin to Straylight = 88 Snowdin to Arbre = 7 Tambi to Faerun = 68 Tambi to Norrath = 134 Tambi to Straylight = 107 Tambi to Arbre = 40 Faerun to Norrath = 11 Faerun to Straylight = 66 Faerun to Arbre = 144 Norrath to Straylight = 115 Norrath to Arbre = 135 Straylight to Arbre = 127""" }
0
Kotlin
0
3
26ef6b194f3e22783cbbaf1489fc125d9aff9566
3,764
kotlinadventofcode
MIT License
src/main/kotlin/com/askrepps/advent2021/day06/Day06.kt
askrepps
726,566,200
false
{"Kotlin": 302802}
/* * MIT License * * Copyright (c) 2021-2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.askrepps.advent.advent2021.day06 import java.io.File private const val NORMAL_TIMER_VALUE = 6 private const val FIRST_TIMER_VALUE = NORMAL_TIMER_VALUE + 2 fun <K> MutableMap<K, Long>.incrementAtKeyBy(key: K, value: Long?) = put(key, (get(key) ?: 0L) + (value ?: 0L)) fun countFish(initialState: List<Int>, numDays: Int): Long { var timerCounts = mutableMapOf<Int, Long>() for (timerValue in initialState) { timerCounts.incrementAtKeyBy(timerValue, 1L) } repeat(numDays) { val nextTimerCounts = mutableMapOf<Int, Long>() for (timerValue in timerCounts.keys) { if (timerValue > 0) { nextTimerCounts.incrementAtKeyBy(timerValue - 1, timerCounts[timerValue]) } else { nextTimerCounts.incrementAtKeyBy(FIRST_TIMER_VALUE, timerCounts[0]) nextTimerCounts.incrementAtKeyBy(NORMAL_TIMER_VALUE, timerCounts[0]) } } timerCounts = nextTimerCounts } return timerCounts.values.sum() } fun getPart1Answer(initialState: List<Int>) = countFish(initialState, numDays = 80) fun getPart2Answer(initialState: List<Int>) = countFish(initialState, numDays = 256) fun main() { val initialState = File("src/main/resources/2021/input-2021-day06.txt") .readText().trim().split(",").map { it.toInt() } println("The answer to part 1 is ${getPart1Answer(initialState)}") println("The answer to part 2 is ${getPart2Answer(initialState)}") }
0
Kotlin
0
0
89de848ddc43c5106dc6b3be290fef5bbaed2e5a
2,652
advent-of-code-kotlin
MIT License
src/main/kotlin/Problem35.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
/** * Circular primes * * The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves * prime. * * There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. * * How many circular primes are there below one million? * * https://projecteuler.net/problem=35 */ fun main() { println(197.isCircularPrime()) println(countCircularPrimes(limit = 100)) println(countCircularPrimes(limit = 1_000_000)) } private fun countCircularPrimes(limit: Long): Int { return primes(limit).count(Int::isCircularPrime) } private fun Int.isCircularPrime(): Boolean { val digits = digits() for (i in digits.indices) { val nextDigits = digits.subList(fromIndex = i, digits.size) + digits.subList(fromIndex = 0, toIndex = i) if (!isPrime(nextDigits.joinToString(separator = "").toLong())) { return false } } return true }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
915
project-euler
MIT License
src/questions/SetMismatch.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * You have a set of integers s, which originally contains all the numbers from 1 to n. * Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, * which results in repetition of one number and loss of another number. * Find the number that occurs twice and the number that is missing and return them in the form of an array. * [Source](https://leetcode.com/problems/set-mismatch/) */ @UseCommentAsDocumentation private fun findErrorNums(nums: IntArray): IntArray { val result = IntArray(2) { -1 } val seen = HashSet<Int>(nums.size) val possibleMissing = mutableSetOf<Int>() var trueIndex = 0 nums.sorted().forEach { i -> // GOTCHA: you've sorted the array, so you can't use forEachIndexed if (trueIndex + 1 != i) { // out of index so potentially missing possibleMissing.add(trueIndex + 1) // index is the missing element } if (seen.contains(i)) { // seen check result[0] = i } trueIndex++ seen.add(i) } possibleMissing.forEach { // find which element is missing if (!seen.contains(it)) { result[1] = it return result // missing element found return the result } } result[1] = nums.size // no missing element found return result } fun main() { // 2,3,3,4,5,6 findErrorNums(nums = intArrayOf(3, 2, 3, 4, 6, 5)) shouldBe intArrayOf(3, 1) findErrorNums(nums = intArrayOf(1, 5, 3, 2, 2, 7, 6, 4, 8, 9)) shouldBe intArrayOf(2, 10) findErrorNums(nums = intArrayOf(3, 2, 2)) shouldBe intArrayOf(2, 1) findErrorNums(nums = intArrayOf(1, 2, 2, 4)) shouldBe intArrayOf(2, 3) findErrorNums(nums = intArrayOf(1, 2, 3, 4, 5, 6, 7, 7, 9)) shouldBe intArrayOf(7, 8) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,868
algorithms
MIT License
src/main/kotlin/g1201_1300/s1254_number_of_closed_islands/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1201_1300.s1254_number_of_closed_islands // #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #Graph_Theory_I_Day_2_Matrix_Related_Problems // #2023_06_07_Time_177_ms_(89.47%)_Space_36.7_MB_(81.58%) class Solution { private var rows = 0 private var cols = 0 private var isLand = false fun closedIsland(grid: Array<IntArray>): Int { rows = grid.size cols = grid[0].size var result = 0 for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == 0) { isLand = true dfs(grid, r, c) if (isLand) { result++ } } } } return result } private fun dfs(grid: Array<IntArray>, r: Int, c: Int) { if (r == 0 || c == 0 || r == rows - 1 || c == cols - 1) { isLand = false } grid[r][c] = 'k'.code if (r > 0 && grid[r - 1][c] == 0) { dfs(grid, r - 1, c) } if (c > 0 && grid[r][c - 1] == 0) { dfs(grid, r, c - 1) } if (r < rows - 1 && grid[r + 1][c] == 0) { dfs(grid, r + 1, c) } if (c < cols - 1 && grid[r][c + 1] == 0) { dfs(grid, r, c + 1) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,366
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/ginsberg/advent2018/Day16.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 16 - Chronal Classification * * Problem Description: http://adventofcode.com/2018/day/16 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day16/ */ package com.ginsberg.advent2018 typealias Registers = IntArray typealias Instruction = IntArray typealias Operation = (Registers, Instruction) -> Registers class Day16( part1RawInput: List<String>, part2RawInput: List<String> ) { private val part1Input: List<Input> = parsePart1Input(part1RawInput) private val part2Input: List<Instruction> = parsePart2Input(part2RawInput) fun solvePart1(): Int = part1Input.count { countMatchingOperations(it) >= 3 } fun solvePart2(): Int { // Create all possible matches. val functionToOpCodes: MutableMap<Operation, MutableSet<Int>> = part1Input.flatMap { input -> Operations.operations.mapNotNull { operation -> if (operation(input.registersBefore, input.instruction).contentEquals(input.expectedRegisters)) { input.id to operation } else { null } } } .groupBy({ it.second }, { it.first }) .mapValues { (_, list) -> list.toMutableSet() } .toMutableMap() val operations = mutableMapOf<Int, Operation>() while (functionToOpCodes.isNotEmpty()) { // Find all that have only one outcome, map them into the operations map and remove them from contention, functionToOpCodes .filter { (_, codes) -> codes.size == 1 } .map { Pair(it.key, it.value.first()) } .forEach { (op, code) -> operations[code] = op functionToOpCodes.remove(op) functionToOpCodes.forEach { (_, thoseFuncs) -> thoseFuncs.remove(code) } } functionToOpCodes.entries.removeIf { (_, value) -> value.isEmpty() } } // Run the code and return register 0 return part2Input.fold(intArrayOf(0, 0, 0, 0)) { registers, instruction -> operations[instruction[0]]!!.invoke(registers, instruction) }.first() } private fun countMatchingOperations(input: Input): Int = Operations.operations.count { it(input.registersBefore, input.instruction).contentEquals(input.expectedRegisters) } private companion object { val digitsRegex = """[^0-9 ]""".toRegex() fun parsePart1Input(rawInput: List<String>): List<Input> = rawInput.chunked(4) { chunk -> Input( chunk[0].toIntArray(), chunk[1].toIntArray(), chunk[2].toIntArray() ) } fun parsePart2Input(rawInput: List<String>): List<Instruction> = rawInput.map { it.toIntArray() } private fun String.toIntArray(): IntArray = this.replace(digitsRegex, "").trim().split(" ").map { it.toInt() }.toIntArray() } private class Input(val registersBefore: Registers, val instruction: Instruction, val expectedRegisters: Registers) { val id = instruction[0] } private object Operations { val operations: List<Operation> = listOf( ::addr, ::addi, ::mulr, ::muli, ::banr, ::bani, ::borr, ::bori, ::setr, ::seti, ::gtir, ::gtri, ::gtrr, ::eqir, ::eqri, ::eqrr ) fun addr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] + registers[instruction[2]] } fun addi(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] + instruction[2] } fun mulr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] * registers[instruction[2]] } fun muli(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] * instruction[2] } fun banr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] and registers[instruction[2]] } fun bani(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] and instruction[2] } fun borr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] or registers[instruction[2]] } fun bori(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] or instruction[2] } fun setr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = registers[instruction[1]] } fun seti(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = instruction[1] } fun gtir(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = if (instruction[1] > registers[instruction[2]]) 1 else 0 } fun gtri(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = if (registers[instruction[1]] > instruction[2]) 1 else 0 } fun gtrr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = if (registers[instruction[1]] > registers[instruction[2]]) 1 else 0 } fun eqir(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = if (instruction[1] == registers[instruction[2]]) 1 else 0 } fun eqri(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = if (registers[instruction[1]] == instruction[2]) 1 else 0 } fun eqrr(registers: Registers, instruction: Instruction): Registers = registers.copyOf().apply { this[instruction[3]] = if (registers[instruction[1]] == registers[instruction[2]]) 1 else 0 } } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
6,792
advent-2018-kotlin
MIT License
src/Day05.kt
daletools
573,114,602
false
{"Kotlin": 8945}
fun main() { fun parseInput(input: List<String>) { val inventorySize = input.indexOfFirst { it.isEmpty() } var (boxes, commands) = input.partition { input.indexOf(it) <= inventorySize } boxes = boxes.reversed().drop(2) println(boxes) println(commands) } fun part1(input: List<String>): Int { var score = 0 return score } fun part2(input: List<String>): Int { var score = 0 return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") println("Part 1 Test:") println(part1(testInput)) println("Part 2 Test:") println(part2(testInput)) val input = readInput("Day05") println("Part 1:") println(part1(input)) println("Part 2:") println(part2(input)) println(parseInput(testInput)) }
0
Kotlin
0
0
c955c5d0b5e19746e12fa6a569eb2b6c3bc4b355
896
adventOfCode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveDuplicates.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 /** * 26. Remove Duplicates from Sorted Array * @see <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array">Source</a> */ fun interface RemoveDuplicates { operator fun invoke(nums: IntArray): Int } class RemoveDuplicatesSolution : RemoveDuplicates { override fun invoke(nums: IntArray): Int { val n = nums.size if (n < 2) return n var count = 0 for (i in 1 until n) { if (nums[i] == nums[i - 1]) { count++ } else { nums[i - count] = nums[i] } } return n - count } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,261
kotlab
Apache License 2.0
src/bonus/FindIndexOfTarget.kt
develNerd
456,702,818
false
{"Kotlin": 37635, "Java": 5892}
package bonus import array.mergeSort import kotlin.math.absoluteValue class Api(){ companion object{ public var does = "" } } /** * * if you are given an int array [3,1,11,5,10,19]. Find the index of target 10 * if the array was sorted. * * solution * * is to try to sort and while sorting find the target and it's index * * */ data class Target(var targetValue:Int,var index:Int = 0) /*fun main(){ val targetObject = Target(17,0) val array = intArrayOf(3,1,11,5,10,19,17) println(mergeSortFindTarget(array,targetObject).contentToString()) println(targetObject.index) }*/ /** * Time complexity = O(nlogn) * */ fun mergeSortFindTarget(array: IntArray,target: Target):IntArray{ Api() if (array.size == 1) return array val middle = array.size / 2 val left = mergeSortFindTarget(array.copyOfRange(0,middle),target) val right = mergeSortFindTarget(array.copyOfRange(middle,array.size),target) return merge(left,right,target) } fun merge(left:IntArray,right:IntArray,target: Target):IntArray{ var leftIndex = 0 var rightIndex = 0 var currentIndex = 0 var sortedArray = IntArray(size = left.size.plus(right.size)) while (leftIndex < left.size && rightIndex < right.size){ val leftElement = left[leftIndex] val rightElement = right[rightIndex] if (leftElement > rightElement){ sortedArray[currentIndex] = rightElement rightIndex += 1 if (target.targetValue == rightElement){ target.index = currentIndex } }else if (leftElement < rightElement){ sortedArray[currentIndex] = leftElement leftIndex += 1 if (target.targetValue == leftElement){ target.index = currentIndex } }else{ if (leftElement == target.targetValue || rightElement == target.targetValue){ target.index = currentIndex } sortedArray[currentIndex] = rightElement rightIndex += 1 currentIndex++ sortedArray[currentIndex] = leftElement leftIndex += 1 } currentIndex++ } if (leftIndex < left.size){ (leftIndex until left.size).forEach { if (left[it] == target.targetValue){ target.index = currentIndex } sortedArray[currentIndex] = left[it] currentIndex++ } } if (rightIndex < right.size){ (rightIndex until right.size).forEach { if (right[it] == target.targetValue){ target.index = currentIndex } sortedArray[currentIndex] = right[it] currentIndex++ } } return sortedArray } fun main(){ println(findMissing(intArrayOf(2,1,3,4,6,7))) } fun findMissing(array: IntArray):Int{ var mn:String? = "" mn = null val sumOfCurrent = array.sum() val max = array.size + 1 //val sumOfTotal = (max * ((max) + 1)) / 2 var sumTotal = 0 for (i in 0..array.size + 1){ sumTotal += i } return (sumTotal - sumOfCurrent).absoluteValue val m by lazy { } } fun mergeSortFindMissingElement(array: IntArray):Pair<Int,IntArray>{ if (array.size == 1) return Pair(0, array) val middle = array.size / 2 val left = mergeSortFindMissingElement(array.copyOfRange(0,middle)) if (left.first != 0){ return Pair(left.first, array) } val right = mergeSortFindMissingElement(array.copyOfRange(middle,array.size)) if (right.first != 0){ return Pair(right.first, array) } val result = mergeSimple(left.second,right.second) if (result.first != 0){ //found missing return Pair(result.first, intArrayOf()) } return Pair(result.first,result.second) } fun mergeSimple(left: IntArray,right: IntArray):Pair<Int,IntArray>{ val sortedArray = IntArray(left.size.plus(right.size)) var leftIndex = 0 var rightIndex = 0 var currentIndex = 0 while (leftIndex < left.size && rightIndex < right.size){ if (left[leftIndex] > right[rightIndex]){ sortedArray[currentIndex] = right[rightIndex] /*if (right[rightIndex] + 1 != left[leftIndex]){ if (right[rightIndex] + 2 == left[leftIndex]){ return Pair(right[rightIndex] + 1, intArrayOf()) } return Pair(right[rightIndex] + 1, intArrayOf()) }*/ rightIndex++ }else if(left[leftIndex] < right[rightIndex]){ sortedArray[currentIndex] = left[leftIndex] /*if (left[leftIndex] + 1 != right[rightIndex]){ if (left[leftIndex] + 2 == right[rightIndex]){ return Pair(left[leftIndex] + 1, intArrayOf()) } }*/ leftIndex++ }else{ sortedArray[currentIndex] = left[leftIndex] leftIndex++ currentIndex++ sortedArray[currentIndex] = right[rightIndex] rightIndex++ } currentIndex++ } /*Add the remaining items if left or right*/ if (rightIndex < right.size){ (rightIndex until right.size).forEach { index -> /* if (index + 1 < right.size && right[index] + 1 != right[index + 1]){ return Pair(right[index] + 1, intArrayOf()) }*/ sortedArray[currentIndex] = right[index] currentIndex++ } } if (leftIndex < left.size){ (leftIndex until left.size).forEach { index -> /*if (index + 1 < left.size && left[index] + 1 != left[index + 1]){ return Pair(left[index] + 1, intArrayOf()) }*/ sortedArray[currentIndex] = left[index] currentIndex++ } } for (i in sortedArray.indices){ if (i + 1 < sortedArray.size && sortedArray[i] + 1 != sortedArray[i + 1]){ if (sortedArray[i + 1] == sortedArray[i] + 2){ return Pair(sortedArray[i] + 1,sortedArray) } } } return Pair(0,sortedArray) } data class Mom(val m:String)
0
Kotlin
0
0
4e6cc8b4bee83361057c8e1bbeb427a43622b511
6,230
Blind75InKotlin
MIT License
src/Day01.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
fun main() { fun groups(input: List<String>): List<Int> { val groups = mutableListOf<Int>() var current = 0 input.forEach { if (it.isEmpty()) { groups += current current = 0 } else { current += it.toInt() } } groups += current return groups } fun part1(input: List<String>) = groups(input).max() fun part2(input: List<String>) = groups(input).sortedDescending().take(3).sum() // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputLines("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
818
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SearchMatrix.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 /** * 74. Search a 2D Matrix * @see <a href="https://leetcode.com/problems/search-a-2d-matrix/">Source</a> */ fun interface SearchMatrix { operator fun invoke(matrix: Array<IntArray>, target: Int): Boolean } class SearchMatrixBS : SearchMatrix { override operator fun invoke(matrix: Array<IntArray>, target: Int): Boolean { if (matrix.isEmpty()) { return false } var start = 0 val rows: Int = matrix.size val cols: Int = matrix[0].size var end = rows * cols - 1 while (start <= end) { val mid = (start + end) / 2 if (matrix[mid / cols][mid % cols] == target) { return true } if (matrix[mid / cols][mid % cols] < target) { start = mid + 1 } else { end = mid - 1 } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,544
kotlab
Apache License 2.0
app/src/main/java/com/niekam/smartmeter/logic/BalanceCalculator.kt
NieKam
456,935,979
false
{"Kotlin": 108121}
package com.niekam.smartmeter.logic import com.niekam.smartmeter.data.model.INSUFFICIENT_MEASUREMENTS import com.niekam.smartmeter.data.model.Measurement import com.niekam.smartmeter.data.model.NO_BALANCE import com.niekam.smartmeter.tools.now import java.util.concurrent.TimeUnit private const val W1 = 1.0 private const val W2 = 0.1 private const val W3 = 0.05 private const val W4 = 0.0025 fun List<Measurement>.computeRemainingFunds(): Double { return when (this.size) { 0 -> return NO_BALANCE 1 -> return this.first().value else -> { approximateFunds(this) } } } private fun approximateFunds(measurements: List<Measurement>): Double { val last = measurements.last() val diffHours = TimeUnit.MILLISECONDS.toHours(now() - last.timestamp) val usagePerHour = approximateAverageUsagePerHour(measurements) return last.value - (diffHours * usagePerHour) } fun List<Measurement>.computeRemainingTimeMs(): Long { if (this.size < 2) { return INSUFFICIENT_MEASUREMENTS } val last = this.last() val usagePerHour = approximateAverageUsagePerHour(this) val hoursLeft = (last.value / usagePerHour).toLong() return last.timestamp + TimeUnit.HOURS.toMillis(hoursLeft) } fun List<Measurement>.computeAverageUsagePerDay(): Double { if (this.size < 2) { return 0.0 } return this.approximateUsage() } private fun List<Measurement>.approximateUsage(): Double { return approximateAverageUsagePerHour(this) * TimeUnit.DAYS.toHours(1) } private fun approximateAverageUsagePerHour(measurements: List<Measurement>): Double { check(measurements.size > 1) { "Size cannot be less than 2" } return when (measurements.size) { 2 -> averageUsageFor2Measurements(measurements.takeLast(2)) 3 -> averageUsageFor3Measurements(measurements.takeLast(3)) 4 -> averageUsageFor4Measurements(measurements.takeLast(4)) 5 -> averageUsageFor5Measurements(measurements.takeLast(5)) else -> averageUsageFor5Measurements(measurements.takeLast(5)) } } private fun approximateUsage(last: Measurement, secondToLast: Measurement): Double { val diffHours = TimeUnit.MILLISECONDS.toHours(last.timestamp - secondToLast.timestamp) val fundsDiff = ((secondToLast.value - last.value) + last.topUpValue) return fundsDiff / diffHours } private fun averageUsageFor2Measurements(lastElements: List<Measurement>): Double { check(lastElements.size >= 2) val last = lastElements.last() val secondToLast = lastElements[lastElements.lastIndex - 1] return approximateUsage(last, secondToLast) } private fun averageUsageFor3Measurements(lastElements: List<Measurement>): Double { check(lastElements.size >= 3) val lastIndex = lastElements.lastIndex val last = lastElements.last() val secondToLast = lastElements[lastIndex - 1] val thirdToLAst = lastElements[lastIndex - 2] val lastApproximateUsage = approximateUsage(last, secondToLast) val secondApproximateUsage = approximateUsage(secondToLast, thirdToLAst) return ((secondApproximateUsage * W2) + (lastApproximateUsage * W1)) / (W1 + W2) } private fun averageUsageFor4Measurements(lastElements: List<Measurement>): Double { check(lastElements.size >= 4) val lastIndex = lastElements.lastIndex val last = lastElements.last() val secondToLast = lastElements[lastIndex - 1] val thirdToLAst = lastElements[lastIndex - 2] val fourthToLast = lastElements[lastIndex - 3] val lastApproximateUsage = approximateUsage(last, secondToLast) val secondApproximateUsage = approximateUsage(secondToLast, thirdToLAst) val thirdApproximateUsage = approximateUsage(thirdToLAst, fourthToLast) return ((thirdApproximateUsage * W3) + (secondApproximateUsage * W2) + (lastApproximateUsage * W1)) / (W1 + W2 + W3) } private fun averageUsageFor5Measurements(lastElements: List<Measurement>): Double { check(lastElements.size >= 5) val lastIndex = lastElements.lastIndex val last = lastElements.last() val secondToLast = lastElements[lastIndex - 1] val thirdToLAst = lastElements[lastIndex - 2] val fourthToLast = lastElements[lastIndex - 3] val fifthToLast = lastElements[lastIndex - 4] val lastApproximateUsage = approximateUsage(last, secondToLast) val secondApproximateUsage = approximateUsage(secondToLast, thirdToLAst) val thirdApproximateUsage = approximateUsage(thirdToLAst, fourthToLast) val fourthApproximateUsage = approximateUsage(fourthToLast, fifthToLast) return ((fourthApproximateUsage * W4) + (thirdApproximateUsage * W3) + (secondApproximateUsage * W2) + (lastApproximateUsage * W1)) / (W1 + W2 + W3 + W4) }
0
Kotlin
0
0
d7a5e0c5c243b6f1e3c41ff398ed8e1d6eda7eb1
4,741
smart-meter
Apache License 2.0
app/src/main/kotlin/me/mataha/misaki/solutions/adventofcode/aoc2015/d02/Day.kt
mataha
302,513,601
false
{"Kotlin": 92734, "Gosu": 702, "Batchfile": 104, "Shell": 90}
package me.mataha.misaki.solutions.adventofcode.aoc2015.d02 import me.mataha.misaki.domain.adventofcode.AdventOfCode import me.mataha.misaki.domain.adventofcode.AdventOfCodeDay /** See the puzzle's full description [here](https://adventofcode.com/2015/day/2). */ @AdventOfCode("I Was Told There Would Be No Math", 2015, 2) class ThereWouldBeNoMath : AdventOfCodeDay<List<Box>, Int>() { override fun parse(input: String): List<Box> = input .lines() .map { line -> line.split(DELIMITER).map { dimension -> dimension.toInt() } } .map { dimensions -> Box.create(dimensions) } override fun solvePartOne(input: List<Box>): Int = input.sumOf { box -> getSquareFeetOfWrappingPaper(box) } override fun solvePartTwo(input: List<Box>): Int = input.sumOf { box -> getFeetOfRibbon(box) } private companion object { private const val DELIMITER = 'x' } } private fun getSquareFeetOfWrappingPaper(box: Box): Int = box.smallestSideArea + box.surfaceArea private fun getFeetOfRibbon(box: Box): Int = box.smallestSidePerimeter + box.volume
0
Kotlin
0
0
748a5b25a39d01b2ffdcc94f1a99a6fbc8a02685
1,124
misaki
MIT License
src/main/kotlin/model/Grammar.kt
Furetur
439,579,145
false
{"Kotlin": 21223, "ANTLR": 246}
package model import java.util.* // Symbols sealed class Symbol { abstract val name: String } data class Term(override val name: String) : Symbol() { override fun toString(): String = name } data class NonTerm(override val name: String): Symbol() { override fun toString(): String = name } typealias SymbolString = List<Symbol> typealias TermString = List<Term> typealias Lang = Set<TermString> val EPSILON: TermString = emptyList() // Rules data class Rule(val def: NonTerm, val value: SymbolString) { override fun toString(): String = "$def := ${value.joinToString(" ")}" } data class Grammar(val main: NonTerm, val rules: Map<NonTerm, Set<Rule>>) { val allRules = rules.flatMap { it.value } val allNonTerms = rules.keys.toList() val allRightNonTerms = allRules.flatMap { rule -> rule.value.filterIsInstance<NonTerm>() } init { // verify that every mentioned nonterminal is defined require(main in rules) { "Main nonterminal $main is not defined" } for (nonTerm in allRightNonTerms) { require(nonTerm in rules) { "Nonterminal $nonTerm is referenced but is not defined" } } } fun removeUselessSymbols(): Grammar { val visitedNonTerms = mutableSetOf<NonTerm>() val queue: Queue<NonTerm> = LinkedList<NonTerm>().also { it.add(main) } while (queue.isNotEmpty()) { val cur = queue.poll() val neighbourNonTerms = rules[cur]?.flatMap { it.value.filterIsInstance<NonTerm>() }?.toSet() ?: emptySet() neighbourNonTerms.filter { it !in visitedNonTerms }.forEach { neighbourNonTerm -> queue.add(neighbourNonTerm) } visitedNonTerms.add(cur) } return Grammar(main, rules.filter { it.key in visitedNonTerms }) } override fun toString(): String = "Main nonterminal: $main\n" + allRules.joinToString("\n") }
0
Kotlin
0
1
002cc53bcca6f9b591c4090d354f03fe3ffd3ed6
1,887
LLkChecker
MIT License
buildSrc/src/main/kotlin/kotlinx/html/generate/parent-ifaces-gen.kt
Kotlin
33,301,379
false
{"Kotlin": 554316}
package kotlinx.html.generate import java.io.* import java.util.* fun generateParentInterfaces(repository: Repository, todir: String, packg: String) { val allParentIfaces = repository.tags.values.filterIgnored().map { tag -> val parentAttributeIfaces = tag.attributeGroups.map { it.name.humanize().capitalize() + "Facade" } val parentElementIfaces = tag.tagGroupNames.map { it.humanize().capitalize() } val sum = parentAttributeIfaces + parentElementIfaces sum.toSet() }.filter { it.isNotEmpty() }.toSet() val allIntroduced = HashSet<Set<String>>(allParentIfaces.size) do { val introduced = HashSet<Set<String>>() allParentIfaces.toList().allPairs().forEach { pair -> val intersection = pair.first.intersect(pair.second) if (intersection.size > 1 && intersection !in allIntroduced && intersection !in allParentIfaces) { introduced.add(intersection) } } if (introduced.isEmpty()) { break } allIntroduced.addAll(introduced) } while (true) FileOutputStream("$todir/gen-parent-traits.kt").writer(Charsets.UTF_8).use { it.with { packg(packg) emptyLine() // import("kotlinx.html.*") emptyLine() doNotEditWarning() emptyLine() emptyLine() (allIntroduced.map { it.sorted() } + allParentIfaces.filter { it.size > 1 }.map { it.sorted() }).distinct().sortedBy { it.sorted().joinToString("").let { renames[it] ?: it } }.forEach { iface -> val ifaceName = humanizeJoin(iface) val subs = allIntroduced.map { it.sorted() }.filter { other -> other != iface && other.all { it in iface } } + allParentIfaces.map { it.sorted() }.filter { other -> other != iface && other.all { it in iface } } val computedParents = (iface - subs.flatMap { it } + subs.map(::humanizeJoin) - ifaceName) .distinct() .map { renames[it] ?: it } .sorted() clazz(Clazz(name = renames[ifaceName] ?: ifaceName, parents = computedParents, isInterface = true)) { } emptyLine() } } } } /** * Returns a sequence that consists of all possible pair of original list elements, does nothing with potential duplicates * @param skipSamePairs indicates whether it should produce pairs from the same element at both first and second positions */ fun <T> List<T>.allPairs(skipSamePairs: Boolean = true): Sequence<Pair<T, T>> = PairsSequence(this, skipSamePairs) private class PairsSequence<T>(val source: List<T>, val skipSamePairs: Boolean) : Sequence<Pair<T, T>> { override fun iterator(): Iterator<Pair<T, T>> = PairsIterator(source, skipSamePairs) } private class PairsIterator<T>(val source: List<T>, val skipSamePairs: Boolean) : AbstractIterator<Pair<T, T>>() { private var index = 0 override fun computeNext() { if (source.isEmpty()) { done() return } index++ val i1 = index / source.size val i2 = index % source.size if (i1 >= source.lastIndex) { done() return } if (skipSamePairs && i1 == i2) { return computeNext() } setNext(Pair(source[i1], source[i2])) } }
89
Kotlin
177
1,514
6c926dda0567d765fe84239e13606e43ff2e3657
3,530
kotlinx.html
Apache License 2.0
src/day7/fr/Day07_1.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day7.fr import java.io.File import kotlin.math.abs private fun readChars(): CharArray = readLn().toCharArray() private fun readLn() = readLine()!! // string line private fun readSb() = StringBuilder(readLn()) private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs fun readInput(name: String) = File("src", "$name.txt").readLines() fun main() { var rep = 0 //val vIn = readInput("test7") val vIn = readInput("input7") var lstIn = vIn[0].split(',').map { it.toInt() } as MutableList lstIn.sort() var min = Int.MAX_VALUE var deb = lstIn.first() var fin = lstIn.last() for (i in deb..fin) { for (it in lstIn) { val dif = abs(i - it) rep += dif } min = minOf(min, rep) rep = 0 } println(min) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
1,424
Advent-of-Code-2021
Apache License 2.0
src/test/kotlin/com/igorwojda/pochallenges/6-13-2022.kt
RyanKCox
498,808,938
false
{"Kotlin": 254610}
package com.igorwojda.pochallenges import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test import kotlin.math.max import kotlin.math.min /** * Median of sorted array challenge */ private fun medianSortedArray(num1:IntArray,num2:IntArray):Double { if(num1.size > num2.size) return medianSortedArray(num2,num1) val num1Size = num1.size val num2Size = num2.size var start = 0 var end = num1Size while (start <= end){ val part1 = (start + end) /2 val part2 = (num1Size + num2Size+1)/2 - part1 val left1 = if(part1 == 0) Int.MIN_VALUE else num1[part1-1] val left2 = if(part2 == 0) Int.MIN_VALUE else num2[part2-1] val right1 = if(part1 == num1Size) Int.MAX_VALUE else num1[part1] val right2 = if(part2 == num2Size) Int.MAX_VALUE else num2[part2] if(left1 <= right2 && left2 <= right1){ return if((num1Size + num2Size)%2 == 0) (max(left1,left2) + min(right1, right2))/2.0 else max(left1,left2).toDouble() } else if(left1 > right2){ end = part1 -1 } else{ start = part1 + 1 } } throw java.lang.IllegalArgumentException() } private class MedianTest { @Test fun `MedianTest 1`(){ val num1 = intArrayOf(1,3) val num2 = intArrayOf(2) medianSortedArray(num1,num2) shouldBeEqualTo 2.0 } @Test fun `MedianTest 2`(){ val num1 = intArrayOf(1,2) val num2 = intArrayOf(3,4) medianSortedArray(num1,num2) shouldBeEqualTo 2.5 } } /** * Link List Merge Challenge */ class Link(val value:Int){ // var prev:Link? = null var next:Link? = null fun toList():List<Int>{ val list = mutableListOf(value) var pointer:Link? = this while(pointer!!.next != null){ list.add(pointer.next!!.value) pointer = pointer.next } return list } } private fun linkListOf(vararg elements:Int):Link?{ var header:Link? = null if(elements.isNotEmpty()){ var prev:Link? = null elements.forEach { value-> if(header == null){ header = Link(value) prev = header } else{ prev!!.next = Link(value) prev = prev!!.next } } } return header } private fun mergeLinkListSort(vararg elements:Link?):Link?{ //Head of link list to return var header:Link? = null //List of the different links for iteration val linkLists = mutableListOf<Link?>() elements.forEach { list -> linkLists.add(list) } //While loop variables //current position and boolean for completion var position:Link? = null var bContinue = true while (bContinue){ //Stop the loop on next iteration unless changed bContinue = false //Find the location of the min value var min = Int.MAX_VALUE var minIndex = 0 linkLists.forEachIndexed { index,list-> //If the list is null we continue if(list != null){ //If not null, do the while loop again bContinue = true //check the first value of the link list against our current min if(list.value < min) { min = list.value minIndex = index } } } //If we found a value in the lists, add to the resulting link list if(bContinue){ //check if Header has been assigned. //assign current position if(header == null) { header = Link(min) position = header } else{ position!!.next = Link(min) position = position.next } //move the head of the selected link list to it's next element linkLists[minIndex] = linkLists[minIndex]!!.next } } //When finished, return the head of the new link list return header } private class LinkListSortTest { @Test fun `LinkListTest 1`(){ val list1 = linkListOf(1,4,5) val list2 = linkListOf(1,3,4) val list3 = linkListOf(2,6) mergeLinkListSort(list1,list2,list3)?.toList() shouldBeEqualTo listOf(1,1,2,3,4,4,5,6) } @Test fun `LinkListTest 2`(){ val list1 = linkListOf(1,6,7) val list2 = linkListOf(3,9,20) mergeLinkListSort(list1,list2)?.toList() shouldBeEqualTo listOf(1,3,6,7,9,20) } @Test fun `LinkListTest 3`(){ val list1 = linkListOf(12,41,322) mergeLinkListSort(list1)?.toList() shouldBeEqualTo listOf(12,41,322) } @Test fun `LinkListTest 4`(){ mergeLinkListSort()?.toList() shouldBeEqualTo null } @Test fun `LinkListTest 5`(){ val list1 = linkListOf(1,6,9,38,234,999) val list2 = linkListOf(11,15,56) val list3 = linkListOf(167,452,888,1234) val list4 = linkListOf(25,76,786) mergeLinkListSort(list1,list2,list3,list4)?.toList() shouldBeEqualTo listOf(1,6,9,11,15,25,38,56,76,167,234,452,786,888,999,1234) } }
0
Kotlin
0
0
f7657f9a60cd20f98c2da95bf65a7981758e8337
5,292
kotlin-coding-challenges
MIT License
src/Day06.kt
arisaksen
573,116,584
false
{"Kotlin": 42887}
import org.assertj.core.api.Assertions.assertThat import java.util.LinkedList // https://adventofcode.com/2022/day/6 fun main() { val moreThanTwoEqual = """^.*(.).*\1.*${'$'}""".toRegex() fun part1(input: String): Int { val limitedQue = LinkedList<Char>() val queSize = 4 input.forEachIndexed { index, char -> limitedQue.addNew(char, queSize) if (limitedQue.size == queSize && limitedQue.joinToString("").contains(moreThanTwoEqual).not()) { println("true after: ${limitedQue.joinToString("")}($index)") return index + 1 } } return 0 } fun part2(input: String): Int { val limitedQue = LinkedList<Char>() val queSize = 14 input.forEachIndexed { index, char -> limitedQue.addNew(char, queSize) if (limitedQue.size == queSize && limitedQue.joinToString("").contains(moreThanTwoEqual).not()) { println("true after: ${limitedQue.joinToString("")}($index)") return index + 1 } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readText("Day06_test") assertThat(part1(testInput)).isEqualTo(10) assertThat(part2(testInput)).isEqualTo(29) // print the puzzle answer val input = readText("Day06") println(part1(input)) println(part2(input)) } fun LinkedList<Char>.addNew(char: Char, max: Int) { this.add(char) if (this.size > max) { this.removeFirst() } }
0
Kotlin
0
0
85da7e06b3355f2aa92847280c6cb334578c2463
1,583
aoc-2022-kotlin
Apache License 2.0
src/day07/day07.kt
mahmoud-abdallah863
572,935,594
false
{"Kotlin": 16377}
package day07 import assertEquals import readInput import readTestInput import kotlin.math.min fun main() { fun calculateShit(directory: MyDirectory): Int { val currentDirSize = directory.calculateSize() val currentSize = if (currentDirSize < 100_000) currentDirSize else 0 return currentSize + directory.directories.sumOf{ calculateShit(it) } } fun part1(input: List<String>): Int { val terminalParser = TerminalParser() val parentDirectory = terminalParser.parse(input) return calculateShit(parentDirectory) } fun part2(input: List<String>): Int { val terminalParser = TerminalParser() val rootDir = terminalParser.parse(input) val parentDirectorySize = rootDir.calculateSize() val freeSpace = 70_000_000 - parentDirectorySize val minSizeToBeDeleted = kotlin.math.abs(min(0, freeSpace - 30_000_000)) val directorySizesList = rootDir.getDirectoriesSizesList().sorted() return directorySizesList.find { it >= minSizeToBeDeleted } ?: -1 } // test if implementation meets criteria from the description, like: val testInput = readTestInput() assertEquals(part1(testInput), 95437) assertEquals(part2(testInput), 24933642) val input = readInput() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f6d1a1583267e9813e2846f0ab826a60d2d1b1c9
1,356
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day23/Day23.kt
Jessevanbekkum
112,612,571
false
null
package day23 import util.readLines class Day23(input: String, a: Long) { val set = Regex("set (\\w) ([\\w-]*)") val mul = Regex("mul (\\w) ([\\w-]*)") val sub = Regex("sub (\\w) ([\\w-]*)") val jnz = Regex("jnz (\\w) ([\\w-]*)") val reg = mutableMapOf<String, Long>() val regex = listOf<Regex>(set, mul, sub, jnz) var count = 0 var running = true; var pos = 0; val code: List<String>; init { "abcdefgh".forEach { it -> reg.put(it.toString(), 0) } reg["a"] = a code = readLines(input) } fun run() { while (pos in (0 until code.size)) { if ( pos==19) { println(pos.toString() + " - " + reg) } val s = code[pos] running = true val caps = regex.map { r -> r.matchEntire(s) }.filterNotNull().first().groupValues when (caps[0].subSequence(0, 3)) { "set" -> setRegister(caps) "sub" -> subtract(caps) "mul" -> multiply(caps) "jnz" -> jump(caps) } } } private fun subtract(caps: List<String>) { reg[caps[1]] = reg[caps[1]]!! - read(caps[2]) pos++ } private fun add(caps: List<String>) { reg[caps[1]] = reg[caps[1]]!! + read(caps[2]) pos++ } private fun modulo(caps: List<String>) { reg[caps[1]] = reg[caps[1]]!! % read(caps[2]) pos++ } private fun multiply(caps: List<String>) { count++ reg[caps[1]] = reg[caps[1]]!! * read(caps[2]) pos++ } private fun setRegister(caps: List<String>) { reg[caps[1]] = read(caps[2]) pos++ } private fun jump(caps: List<String>) { if (read(caps[1]) != 0L) { pos += read(caps[2]).toInt() } else { pos++ } } fun read(s: String): Long { return s.toLongOrNull() ?: reg[s]!! } }
0
Kotlin
0
0
1340efd354c61cd070c621cdf1eadecfc23a7cc5
1,974
aoc-2017
Apache License 2.0
src/main/kotlin/endredeak/aoc2022/Day25.kt
edeak
571,891,076
false
{"Kotlin": 44975}
package endredeak.aoc2022 fun main() { solve( "Full of Hot Air") { fun Long.pow(i: Int): Long { var ret = 1L repeat(i) { ret *= this } return ret } fun String.toSnofuDigit() = this.reversed().mapIndexed { i, c -> when(c) { '=' -> -2 '-' -> -1 else -> c.digitToInt().toLong() } * (5L.pow(i)) }.sum() val DIGITS = "=-012" fun Long.toSnofu() = run { if (this == 0L) "0" else { var b = this buildString { while (b > 0) { val m = (b + 2) % 5 b = (b + 2) / 5 append(DIGITS[m.toInt()]) } }.reversed() } } val input = lines part1("2-=2==00-0==2=022=10") { input .map { it to it.toSnofuDigit() } .sumOf { it.second } .toSnofu() } part2 { } } }
0
Kotlin
0
0
e0b95e35c98b15d2b479b28f8548d8c8ac457e3a
1,150
AdventOfCode2022
Do What The F*ck You Want To Public License
src/main/kotlin/Day01.kt
SimonMarquis
724,825,757
false
{"Kotlin": 30983}
class Day01(private val input: List<String>) { fun part1() = input.asSequence() .map { it.filter(Char::isDigit) } .sumOf { "${it.first()}${it.last()}".toInt() } private val replacements = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") fun part2() = input.asSequence() .map { line -> line.foldIndexed(StringBuilder()) { accIndex, acc, c -> if (c.isDigit()) return@foldIndexed acc.append(c) replacements.forEachIndexed { index, replacement -> if (line.startsWith(replacement, startIndex = accIndex)) return@foldIndexed acc.append(index + 1) } return@foldIndexed acc } } .sumOf { "${it.first()}${it.last()}".toInt() } }
0
Kotlin
0
1
043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e
814
advent-of-code-2023
MIT License
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/Search.kt
scientificCommunity
352,868,267
false
{"Java": 154453, "Kotlin": 69817}
package org.baichuan.sample.algorithms.leetcode.middle /** * https://leetcode.cn/problems/search-in-rotated-sorted-array/ * 33. 搜索旋转排序数组 */ class Search { fun search(nums: IntArray, target: Int): Int { val first = nums[0] if (target == first) { return 0 } var i = nums.size / 2 var left = 0 var right = nums.size - 1 while (right > left) { if (target == nums[i]) { return i } if (target > nums[i]) { if (nums[i] < first && target > first) { right = i i = (right + left) / 2 } else { if (i == nums.size - 1) return -1 left = i + 1 i = (right + left) / 2 } } else { if (nums[i] > first) { if (target > first) { right = i i = (right + left) / 2 } else { if (i == nums.size - 1) return -1 left = i + 1 i = (right + left) / 2 } } else { right = i i = (right + left) / 2 } } } if (nums[left] == target) { return left } return -1 } } fun main() { Search().search(arrayOf(8, 9, 2, 3, 4).toIntArray(), 9) }
1
Java
0
8
36e291c0135a06f3064e6ac0e573691ac70714b6
1,534
blog-sample
Apache License 2.0
src/main/kotlin/com/dood/kotlin/basicstuff/iteration/7_Iteration.kt
coderdude1
164,117,770
false
null
package com.dood.kotlin.basicstuff.iteration import java.util.* fun main(args: Array<String>) { simpleLoop() countDownwardEvenOnly() countDownToLimit() populateAndIterateOverMap() iterateListWithIndex() rangeMembership() } /** * while and do-while loops are the same as java * * the for loop is like the c# for, ie for <item> in <elements>. The for loop is very flexible, offering * several variations (use it to iterate over a Collection, iterate over a collection with an index, iterate * ranges with or without stepping, iterate down (downTo) * * range modifiers can be found here https://kotlinlang.org/docs/reference/ranges.html * * Note that there are integral ranges that w can interate over, IntRange, LongRange, CharRange * * note this is expression syntax where when{} is the block */ fun fizzBuzz(i: Int) = when { i % 25 == 0 -> "FizzBuzz\n " i % 3 == 3 -> "Fizz\n " i % 5 == 0 -> "Buzz\n " else -> "$i " //return the input int as a string using stringTemplate } fun recognize(c: Char) = when (c) { in '0'..'9' -> "Its a digit" in 'a'..'z', in 'A'..'Z' -> "Its a letter" //note combining two in statements else -> "no damn clue" } private fun rangeMembership() { println("\nRange Membership") println("3 is letter ${isLetter('3')}") println("z is letter ${isLetter('z')}") println("3 is not digit ${isNotDigit('3')}") println("kotlin" in "java".."scala") //prints true same as "java" <= "kotlin" <= scala case sensitive println("kotlin" in setOf("java", "scala")) //can use in on a collection println("Recognize a ${recognize('a')}") println("Recognize 8 ${recognize('8')}") } //note the next two appear to be predicates, private fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z' private fun isNotDigit(c: Char) = c !in '0'..'9' private fun iterateListWithIndex() { println("\niterate list with index") val list = arrayListOf("10", "11", "13", "2") //note no <> type, it uses type inference (future thingy) for ((index, element) in list.withIndex()) { println("$index, $element") } } private fun populateAndIterateOverMap() { println("\niterate over TreeMap") val binaryReps = TreeMap<Char, String>() //java treeMap for (c in 'A'..'F') { //note we can iterateo over characters val binary = Integer.toBinaryString(c.toInt()) binaryReps[c] = binary } for ((letter, binary) in binaryReps) { //iterate over the map, letter is key, binary is value println("$letter = $binary") } } private fun countDownToLimit() { println("Count up to but not including the end limit") for (i in 1 until 10) { //count up to 10 but not inclding 10 print(fizzBuzz(i)) } } private fun countDownwardEvenOnly() { println("Count Down to by two's") for (i in 100 downTo 1 step 2) { //basic for loop couting down by 2s print(fizzBuzz(i)) } println() } private fun simpleLoop() { println("Count up to limit") for (i in 1..100) { //here is a basic for loop print(fizzBuzz(i)) } println() }
0
Kotlin
0
0
5f5dcb954152b81f458bf614c79a5116dd554385
3,127
KotlinBasicExperiments
Apache License 2.0
src/main/java/challenges/educative_grokking_coding_interview/merge_intervals/_5/MeetingRooms.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.merge_intervals._5 import challenges.educative_grokking_coding_interview.merge_intervals.Interval object MeetingRooms { private fun minMeetingRooms(intervals: List<Interval>): Int { if (intervals.isEmpty()) { return 0 } // Create two arrays to store the start times and end times of the intervals val startTimes = intervals.map { it.start }.sorted().toIntArray() val endTimes = intervals.map { it.end }.sorted().toIntArray() // Use two pointers to keep track of the current meetings and the maximum number of meetings var currentMeetings = 0 var maxMeetings = 0 var i = 0 var j = 0 // Iterate over the start times and end times arrays together while (i < startTimes.size && j < endTimes.size) { // If the current meeting has started before the earliest ending meeting has ended, we need an extra meeting room if (startTimes[i] < endTimes[j]) { currentMeetings++ i++ } else { // Otherwise, we can reuse a meeting room currentMeetings-- j++ } // Update the maximum number of meetings maxMeetings = maxOf(maxMeetings, currentMeetings) } return maxMeetings } @JvmStatic fun main(args: Array<String>) { val intervals = listOf( Interval(2, 8), Interval(3, 4), Interval(3, 9), Interval(5, 11), Interval(8, 20), Interval(11, 15) ) val minRooms = minMeetingRooms(intervals) println("Minimum number of meeting rooms required: $minRooms") } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
1,795
CodingChallenges
Apache License 2.0
src/main/kotlin/g1001_1100/s1081_smallest_subsequence_of_distinct_characters/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1081_smallest_subsequence_of_distinct_characters // #Medium #String #Greedy #Stack #Monotonic_Stack // #2023_06_02_Time_146_ms_(100.00%)_Space_34_MB_(100.00%) import java.util.Arrays import java.util.Deque import java.util.LinkedList class Solution { fun smallestSubsequence(s: String): String { val n = s.length val stk: Deque<Char> = LinkedList() val freq = IntArray(26) val exist = BooleanArray(26) Arrays.fill(exist, false) for (ch in s.toCharArray()) { freq[ch.code - 'a'.code]++ } for (i in 0 until n) { val ch = s[i] freq[ch.code - 'a'.code]-- if (exist[ch.code - 'a'.code]) { continue } while (stk.isNotEmpty() && stk.peek() > ch && freq[stk.peek().code - 'a'.code] > 0) { val rem = stk.pop() exist[rem.code - 'a'.code] = false } stk.push(ch) exist[ch.code - 'a'.code] = true } val ans = CharArray(stk.size) var index = 0 while (stk.isNotEmpty()) { ans[index] = stk.pop() index++ } return StringBuilder(String(ans)).reverse().toString() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,272
LeetCode-in-Kotlin
MIT License