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
2020/src/year2021/day07/code.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2021.day07 import util.readAllLines import kotlin.math.abs import kotlin.math.min fun main() { run(false) run(true) } private fun run(incrementCost: Boolean) { val input = readAllLines("input.txt").first().split(",").map { it.toInt() }.sorted() var result = Int.MAX_VALUE (input.first()..input.last()).forEach { result = min(result, calcFuel(input, it, incrementCost)) } println(result) } private fun calcFuel(list: List<Int>, testValue: Int, incrementCost: Boolean): Int { if (list.isEmpty()) { return 0 } var result: Int = Int.MAX_VALUE val size = list.size val mid = size / 2 if (size == 1) { result = list.sumOf { val distance = abs(it - testValue) if (incrementCost) (distance * (distance + 1)) / 2 else distance } } else { val left = calcFuel(list.subList(0, mid), testValue, incrementCost) val right = calcFuel(list.subList(mid, size), testValue, incrementCost) result = min(result, left + right) } return result }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
1,084
adventofcode
MIT License
src/main/kotlin/days/Day3.kt
MisterJack49
574,081,723
false
{"Kotlin": 35586}
package days class Day3 : Day(3) { override fun partOne(): Any { return inputList.map { it.take(it.length / 2) to it.takeLast(it.length / 2) } .map { groups -> groups.first[groups.first.indexOfAny(groups.second.toCharArray())] } .sumOf { Alphabet.valueOf(it.toString()).ordinal + 1 } } override fun partTwo(): Any { return inputList.chunked(3) .map { group -> val one = group.component1().toList().distinct() val two = group.component2().toList().distinct() val three = group.component3().toList().distinct() one.first { two.contains(it) && three.contains(it) } } .sumOf { Alphabet.valueOf(it.toString()).ordinal + 1 } } } private enum class Alphabet { 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, 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 }
0
Kotlin
0
0
e82699a06156e560bded5465dc39596de67ea007
980
AoC-2022
Creative Commons Zero v1.0 Universal
2022/05 - Supply Stacks/src/Main.kt
jamesrweb
318,272,685
false
{"Rust": 53359, "Python": 47359, "Elm": 45736, "PHP": 29791, "C#": 23894, "TypeScript": 22904, "JavaScript": 12689, "F#": 6885, "C": 4658, "Haskell": 4028, "Ruby": 3540, "Kotlin": 3305, "EJS": 574, "HTML": 363}
import java.io.File import java.util.* data class Crate constructor(val value: String) data class Stacks constructor(val list: HashMap<Int, MutableList<Crate>>) { fun viewResult(): String { return this.list.tops().joinToString("") } companion object Static { fun fromCrates(crates: String): Stacks { val stacksList = hashMapOf<Int, MutableList<Crate>>() val stackKeys = crates.lines().last().filterNot { it.isWhitespace() }.map { it.digitToInt() } crates.lines().dropLast(1).map { line -> line.chunked(4).toMutableList().insertWhile({ chunk -> chunk.size < stackKeys.size }, "").map { item -> if (item.trim() == "") { Optional.empty<Crate>() } else { val char = item.replace("[", "").replace("]", "").trim().take(1) val crate = Crate(char) Optional.of<Crate>(crate) } } }.forEach { it.forEachIndexed { index, optional -> if (optional.isPresent) { stacksList.getOrPut(index + 1) { mutableListOf() }.add(optional.get()) } } } return Stacks(stacksList) } } } fun executeMoves(moves: List<String>, stacks: Stacks, retainOrder: Boolean): Stacks { moves.forEach { line -> val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") val result = regex.find(line)?.destructured val count = result?.component1()?.toInt() val from = result?.component2()?.toInt() val to = result?.component3()?.toInt() if (count == null || from == null || to == null) { throw Exception("Something went wrong. count = $count, from = $from, to = $to") } val lastFrom = stacks.list.getOrDefault(from, mutableListOf()) val nextFrom = lastFrom.drop(count).toMutableList() val nextTo = stacks.list.getOrDefault(to, mutableListOf()) if (retainOrder) { nextTo.prependAll(lastFrom.take(count)) } else { nextTo.prependAll(lastFrom.take(count).reversed()) } stacks.list[to] = nextTo.toMutableList() stacks.list[from] = nextFrom } return stacks } fun main() { val path = System.getProperty("user.dir") val contents = File("${path}/src/input.txt").readText(Charsets.UTF_8) val (crates, instructions) = contents.split("\n\n") val moves = instructions.lines().filterNot { it.trim() == "" } val partOne = executeMoves(moves, Stacks.fromCrates(crates), false) val partTwo = executeMoves(moves, Stacks.fromCrates(crates), true) println("Part One: ${partOne.viewResult()}") println("Part Two: ${partTwo.viewResult()}") } private fun <T> MutableList<T>.prependAll(elements: List<T>) { addAll(0, elements) } private fun <K> HashMap<K, MutableList<Crate>>.tops(): List<String> { return this.values.flatMap { it.take(1) }.map { it.value } } private fun <E> MutableList<E>.insertWhile(transform: (MutableList<E>) -> Boolean, value: E): MutableList<E> { while (transform(this)) { this.add(this.size, value) } return this }
0
Rust
0
0
1180a7f55b2f46dba4e5d17b4b67229dfc9ed655
3,305
advent-of-code
MIT License
src/Day11.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
fun main() { class Monkey (startingItems: MutableList<Long>, operation: String, testDivisor: Int, testTruth: Int, testFalse: Int) { val operation = operation var items = startingItems val testDivisor = testDivisor val testTrueMonkeyNumber = testTruth val testFalseMonkeyNumber = testFalse var inspectionCount = 0L lateinit var worrySubsidingFunction: (Long) -> Long fun inspectNextItem(): Boolean { if (items.size == 0) { return false } inspectionCount++ var amount = operation.split(" ").last().toLongOrNull() if (amount == null) { amount = items.first() } if (operation.contains("*")) { var newItem = worrySubsidingFunction(items.first() * amount) items.removeFirst() items.add(0, newItem) } if (operation.contains("+")) { var newItem = worrySubsidingFunction(items.first() + amount) items.removeFirst() items.add(0, newItem) } return true } fun determineNextMonkey(): Int { if ((items.first() % testDivisor) == 0L) { return testTrueMonkeyNumber } else { return testFalseMonkeyNumber } } fun receiveItem(item: Long) { items.add(item) } } fun part1(input: String): Long { var monkeys = input.split("\n\n") .map { var items = mutableListOf<Long>() var operation = "" var testDivisor = -1 var testTrueMonkeyNumber = -1 var testFalseMonkeyNumber = -1 it.split("\n") .drop(1) .forEachIndexed { index, s -> if (index == 0) { items = s.plus(",").split(" ").filter { it.contains(",") }.map { it.dropLast(1).toLong() }.toMutableList() } else if (index == 1) { operation = s } else if (index == 2) { testDivisor = s.split(" ").last().toInt() } else if (index == 3) { testTrueMonkeyNumber = s.split(" ").last().toInt() } else if (index == 4) { testFalseMonkeyNumber = s.split(" ").last().toInt() } } Monkey(items, operation, testDivisor, testTrueMonkeyNumber, testFalseMonkeyNumber) } monkeys.forEach { it.worrySubsidingFunction = { it /3L } } repeat(20){ monkeys.forEach { while (it.inspectNextItem()) { var newMonkeyIndex = it.determineNextMonkey() monkeys[newMonkeyIndex].receiveItem(it.items.removeFirst()) } } } return monkeys.map { it.inspectionCount }.sortedDescending().take(2).reduce { acc, i -> i*acc } } fun part2(input: String): Long { var monkeys = input.split("\n\n") .map { var items = mutableListOf<Long>() var operation = "" var testDivisor = -1 var testTrueMonkeyNumber = -1 var testFalseMonkeyNumber = -1 it.split("\n") .drop(1) .forEachIndexed { index, s -> if (index == 0) { items = s.plus(",").split(" ").filter { it.contains(",") }.map { it.dropLast(1).toLong() }.toMutableList() } else if (index == 1) { operation = s } else if (index == 2) { testDivisor = s.split(" ").last().toInt() } else if (index == 3) { testTrueMonkeyNumber = s.split(" ").last().toInt() } else if (index == 4) { testFalseMonkeyNumber = s.split(" ").last().toInt() } } Monkey(items, operation, testDivisor, testTrueMonkeyNumber, testFalseMonkeyNumber) } var worryingSpace = monkeys.map { it.testDivisor.toLong() }.reduce(Long::times) monkeys.forEach { it.worrySubsidingFunction = { it % worryingSpace } } repeat(10000){ monkeys.forEach { while (it.inspectNextItem()) { var newMonkeyIndex = it.determineNextMonkey() monkeys[newMonkeyIndex].receiveItem(it.items.removeFirst()) } } } return monkeys.map { it.inspectionCount }.sortedDescending().take(2).reduce { acc, i -> i*acc } } val testInput = readInput("Day11_test") val output = part1(testInput) check(output == 10605L) val outputTwo = part2(testInput) check(outputTwo == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
5,581
aoc-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SpecialPositionsInBinaryMatrix.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 /** * 1582. Special Positions in a Binary Matrix * @see <a href="https://leetcode.com/problems/special-positions-in-a-binary-matrix">Source</a> */ fun interface SpecialPositionsInBinaryMatrix { operator fun invoke(mat: Array<IntArray>): Int } class SpecialPositionsInBinaryMatrixBF : SpecialPositionsInBinaryMatrix { override fun invoke(mat: Array<IntArray>): Int { var ans = 0 val m: Int = mat.size val n: Int = mat[0].size for (row in 0 until m) { for (col in 0 until n) { if (mat[row][col] == 1 && isSpecialPosition(mat, row, col, m, n)) { ans++ } } } return ans } private fun isSpecialPosition(mat: Array<IntArray>, row: Int, col: Int, m: Int, n: Int): Boolean { for (r in 0 until m) { if (r != row && mat[r][col] == 1) { return false } } for (c in 0 until n) { if (c != col && mat[row][c] == 1) { return false } } return true } } class SpecialPositionsInBinaryMatrixPrecompute : SpecialPositionsInBinaryMatrix { override fun invoke(mat: Array<IntArray>): Int { val rowCount = computeRowCount(mat) val colCount = computeColCount(mat) return countSpecialPositions(mat, rowCount, colCount) } private fun computeRowCount(mat: Array<IntArray>): IntArray { val m = mat.size val rowCount = IntArray(m) for (row in 0 until m) { for (col in mat[row].indices) { if (mat[row][col] == 1) { rowCount[row]++ } } } return rowCount } private fun computeColCount(mat: Array<IntArray>): IntArray { val n = mat[0].size val colCount = IntArray(n) for (row in mat.indices) { for (col in 0 until n) { if (mat[row][col] == 1) { colCount[col]++ } } } return colCount } private fun countSpecialPositions(mat: Array<IntArray>, rowCount: IntArray, colCount: IntArray): Int { var ans = 0 for (row in mat.indices) { for (col in mat[row].indices) { if (mat[row][col] == 1 && rowCount[row] == 1 && colCount[col] == 1) { ans++ } } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,143
kotlab
Apache License 2.0
102_-_Ecological_Bin_Packing/src/Packing.kt
JeanCarlosSC
274,552,136
false
null
import java.util.Scanner fun main() { val frame = Window() } fun calculate(num1: Int, num2: Int, num3: Int, num4: Int, num5: Int, num6: Int, num7: Int, num8: Int, num9: Int): String{ val packing1 = Packing(num1, num2, num3) val packing2 = Packing(num4, num5, num6) val packing3 = Packing(num7, num8, num9) var total: Int var min = 0 val combinations: MutableList<String> = mutableListOf() for(a in 1..3){ for(b in 1..3){ for(c in 1..3){ if(a != b && b != c && a != c) { total = when(a) { 1 -> packing2.brownBottles + packing3.brownBottles 2 -> packing2.greenBottles + packing3.greenBottles else -> packing2.clearBottles + packing3.clearBottles } + when(b) { 1 -> packing1.brownBottles + packing3.brownBottles 2 -> packing1.greenBottles + packing3.greenBottles else -> packing1.clearBottles + packing3.clearBottles } + when(c) { 1 -> packing1.brownBottles + packing2.brownBottles 2 -> packing1.greenBottles + packing2.greenBottles else -> packing1.clearBottles + packing2.clearBottles } when { combinations.isEmpty() -> { min = total combinations.add(code(a, b, c)) } min > total -> { min = total combinations.clear() combinations.add(code(a, b, c)) } min == total -> { combinations.add(code(a, b, c)) } } } } } } combinations.sort() return "${combinations[0]} $min" } fun code(a: Int, b: Int, c: Int): String { return (when (a) { 1 -> "B" 2 -> "G" else -> "C" } + when (b) { 1 -> "B" 2 -> "G" else -> "C" } + when (c) { 1 -> "B" 2 -> "G" else -> "C" }) } class Packing { val brownBottles: Int val greenBottles: Int val clearBottles: Int constructor (a: Int, b: Int, c: Int){ brownBottles = a greenBottles = b clearBottles = c } }
0
Kotlin
0
0
82f43d45aa5c5bf570691f9c811a286e27b39a0e
2,632
problem-set-volume1
Apache License 2.0
src/main/kotlin/algorithms/GreedyMotifSearch.kt
jimandreas
377,843,697
false
null
@file:Suppress("UnnecessaryVariable", "unused", "KotlinConstantConditions") package algorithms /** Code Challenge: Implement GreedyMotifSearch. Input: Integers k and t, followed by a space-separated collection of strings Dna. Output: A collection of strings BestMotifs resulting from applying GreedyMotifSearch(Dna, k, t). If at any step you find more than one Profile-most probable k-mer in a given string, use the one occurring first. * reference: * https://www.bioinformaticsalgorithms.org/bioinformatics-chapter-2 * See also: * stepik: @link: https://stepik.org/lesson/240241/step/5?unit=212587 * rosalind: @link: http://rosalind.info/problems/ba2d/ */ fun greedyMotifSearch(dnaList: List<String>, kmerLength: Int, applyLaplace: Boolean = false): List<String> { // initial conditions - just take the first kmer of each dna in the dnaList var bestMotifs: MutableList<String> = mutableListOf() for (d in dnaList) { bestMotifs.add(d.substring(0, kmerLength)) } /* * now loop through each kmer substring in the first dnaList string. * make a profile for it and then use the profile to get the most * probable match in each of the following strings in the dnaList. */ for (i in 0..dnaList[0].length - kmerLength) { val motifs: MutableList<String> = mutableListOf() val currentMotif = dnaList[0].substring(i, i + kmerLength) motifs.add(currentMotif) var probabilityList = createProfile(motifs, applyLaplace) for (j in 1 until dnaList.size) { val bestMotifInThisString = mostProbableKmerGivenProbList(dnaList[j], kmerLength, probabilityList.toList()) //println("best is $bestMotifInThisString for string ${dnaList[j]}") motifs.add(bestMotifInThisString) probabilityList = createProfile(motifs, applyLaplace) } //println("new best: $motifs score ${scoreTheMotifs(motifs)} vs ${scoreTheMotifs(bestMotifs)}") if (scoreTheMotifs(motifs) < scoreTheMotifs(bestMotifs)) { bestMotifs = motifs } } return bestMotifs } /** * for a list of candidate motif strings, * accumulate a 4 row matrix where each column contains the count * of the ACGT occurrences in the strings. This count is then * normalized by the number of motifs in the list. * * Added: pseudoCounts - * @link: https://en.wikipedia.org/wiki/Additive_smoothing#Pseudocount * "In order to improve this unfair scoring, bioinformaticians often * substitute zeroes with small numbers called pseudocounts." */ fun createProfile(motifsList: List<String>, applyLaplace: Boolean = false): FloatArray { val kmerLength = motifsList[0].length val profile = FloatArray(4 * kmerLength) if (applyLaplace) { for (i in profile.indices) { profile[i] = 1.0f // all entries have a base probability } } for (motif in motifsList) { for (i in motif.indices) { val nucleotide = motif[i].fromNucleotide() profile[nucleotide * kmerLength + i]++ } } var divisor = motifsList.size.toFloat() if (applyLaplace) { divisor += 4.0f } for (i in profile.indices) { profile[i] = profile[i] / divisor } return profile } fun Char.fromNucleotide(): Int { return when (this) { 'A' -> 0 'C' -> 1 'G' -> 2 'T' -> 3 else -> 0 } } fun Int.fromIdentifier(): Char { return when (this) { 0 -> 'A' 1 -> 'C' 2 -> 'G' 3 -> 'T' else -> ' ' } } /** * the [scoreTheMotifs] of a set of motif candidates is the sum * of the mismatches across all letters. * The mismatches are determined by what is left over after subtracting * the dominant fraction in the profile. * @param motifs - the list of candidate motif strings */ fun scoreTheMotifs(motifs: List<String>): Int { val profileMatrix = createProfile(motifs) val mlen = motifs[0].length var score = 0 for (i in 0 until motifs[0].length) { val maxVal = maxValueForColumn(profileMatrix, mlen, i) score += (motifs.size.toFloat() * (1.0f - maxVal)+0.00001).toInt() } return score } /** * return the max value in the profile matrix for [column] * @param len - the length of a rwo in the profile matrix */ private fun maxValueForColumn(profileMatrix: FloatArray, len: Int, column: Int): Float { val anuc = profileMatrix[len * 0 + column] val cnuc = profileMatrix[len * 1 + column] val gnuc = profileMatrix[len * 2 + column] val tnuc = profileMatrix[len * 3 + column] val maxVal = maxOf(anuc, maxOf(cnuc, maxOf(gnuc, tnuc))) return maxVal }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
4,720
stepikBioinformaticsCourse
Apache License 2.0
kotlin/src/main/kotlin/dev/mikeburgess/euler/sequences/PrimeSequence.kt
mddburgess
261,028,925
false
null
package dev.mikeburgess.euler.sequences import dev.mikeburgess.euler.common.isEven import kotlin.math.sqrt @OEIS("A000040") class PrimeSequence : Sequence<Long> { override fun iterator(): Iterator<Long> = object : Iterator<Long> { private var index = 0 override fun hasNext() = true override fun next() = when { index < primes.size -> primes[index] else -> computeNext() }.also { ++index } private fun computeNext() = generateSequence(primes.last() + 2) { it + 2 } .filter { isPrime(it) } .first() .also { primes.add(it) } .also { primeSet.add(it) } private fun isPrime(n: Long) = primes.asSequence() .takeWhile { it <= sqrt(n.toDouble()) } .none { n % it == 0L } } companion object { val primes = mutableListOf(2L, 3L) val primeSet = mutableSetOf(2L, 3L) } } fun Long.isPrime(): Boolean = when { this <= PrimeSequence.primes.last() -> PrimeSequence.primeSet.contains(this) else -> PrimeSequence().takeWhile { it <= this }.last() == this }
0
Kotlin
0
0
86518be1ac8bde25afcaf82ba5984b81589b7bc9
1,206
project-euler
MIT License
src/Day01.kt
alexdesi
575,352,526
false
{"Kotlin": 9824}
import java.io.File fun main() { fun sortedCalories(input: List<String>): List<Int> { val elvesCalories = mutableListOf( mutableListOf<Int>() ) input.forEach { if (it == "") elvesCalories.add(mutableListOf()) else elvesCalories.last().add(it.toInt()) } return elvesCalories .map { it.sum() } .sortedDescending() } fun part1(input: List<String>): Int { return sortedCalories(input).first() } fun part2(input: List<String>): Int { return sortedCalories(input) .subList(0, 3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
56a6345e0e005da09cb5e2c7f67c49f1379c720d
930
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2015/Day15.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2015 import me.grison.aoc.* // not parsing the input class Day15 : Day(15, 2015) { override fun title() = "Science for Hungry People" private val attributes = mutableMapOf("Sugar" to Attributes(3, 0, 0, -3, 2), "Sprinkles" to Attributes(-3, 3, 0, 0, 9), "Candy" to Attributes(-1, 0, 4, 0, 1), "Chocolate" to Attributes(0, 0, -2, 2, 8)) override fun partOne() = allCookies().map { it.first }.maxOrNull() override fun partTwo() = allCookies().filter { it.second == 500 }.maxByOrNull { it.first }?.first fun allCookies(): List<Pair<Int, Int>> { val allCookies = mutableListOf<Pair<Int, Int>>() (0..99).forEach { sugar -> (0..99).forEach { sprinkles -> (0..99).forEach { candy -> val chocolate = 100 - sugar - sprinkles - candy allCookies.add(makeCookie( mapOf("Sugar" to sugar, "Sprinkles" to sprinkles, "Candy" to candy, "Chocolate" to chocolate))) } } } return allCookies } fun makeCookie(teaspoons: Map<String, Int>): Pair<Int, Int> { val m = mutableMapOf<String, Int>() attributes.keys.forEach { ingredient -> val attr = attributes[ingredient]!! val ts = teaspoons[ingredient]!! m["capacity"] = (m["capacity"] ?: 0) + attr.capacity * ts m["durability"] = (m["durability"] ?: 0) + attr.durability * ts m["flavor"] = (m["flavor"] ?: 0) + attr.flavor * ts m["texture"] = (m["texture"] ?: 0) + attr.texture * ts m["calories"] = (m["calories"] ?: 0) + attr.calories * ts } if (m.values.count { e -> e <= 0 } > 0) return Pair(0, m["calories"]!!) return Pair(m.filter { it.key != "calories" }.values.fold(1) { a, b -> a * b }, m["calories"]!!) } } data class Attributes(val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int)
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,168
advent-of-code
Creative Commons Zero v1.0 Universal
implementation/src/main/kotlin/io/github/tomplum/aoc/map/hill/HillHeightMap.kt
TomPlum
572,260,182
false
{"Kotlin": 224955}
package io.github.tomplum.aoc.map.hill import io.github.tomplum.libs.math.map.AdventMap2D import io.github.tomplum.libs.math.point.Point2D import java.util.PriorityQueue /** * The heightmap shows the local area from above broken into a grid; * the elevation of each square of the grid is given by a single lowercase * letter, where a is the lowest elevation, b is the next-lowest, and so * on up to the highest elevation, z. * * Also included on the heightmap are marks for your current position (S) * and the location that should get the best signal (E). Your current position (S) * has elevation a, and the location that should get the best signal (E) has elevation z. * * @param data A collection of lines that represent the map */ class HillHeightMap(data: List<String>) : AdventMap2D<HillTile>() { private val adjacencyMatrix = mutableMapOf<Point2D, Set<Point2D>>() private lateinit var bestSignalPosition: Point2D init { var x = 0 var y = 0 data.forEach { row -> row.forEach { column -> val tile = HillTile(column) val position = Point2D(x, y) if (tile.isBestSignal) { bestSignalPosition = position } addTile(position, tile) x++ } x = 0 y++ } } /** * Finds the shortest route from the current position (S) * and the best signal position (E). * @return The number of steps taken to reach the target position */ fun findShortestRouteToBestSignal(): Int { return searchForBestSignalFrom { tile -> tile.isCurrentPosition } } /** * Finds the shortest route from any of the lowest points of * elevation (a) or the current position (S) to the best signal * position (E). * @return The number of steps taken to reach the target position */ fun findShortestRouteFromLowestElevationToBestSignal(): Int { return searchForBestSignalFrom { tile -> tile.isLowestPossibleElevation } } /** * Uses Dijkstra's algorithm to traverse the map and * find the shortest path from all the given tiles * that are yielded by the [startingTileFilter]. * @param startingTileFilter A filter to produce the starting positions * @return The number of steps in the shortest path */ private fun searchForBestSignalFrom(startingTileFilter: (tile: HillTile) -> Boolean): Int { val distances = mutableMapOf<Point2D, Int>() val next = PriorityQueue<Point2D>() filterTiles { tile -> startingTileFilter(tile) }.keys.forEach { position -> next.offer(position) distances[position] = 0 } while(next.isNotEmpty()) { val currentPos = next.poll() val distance = distances[currentPos]!! currentPos.traversableAdjacent().forEach { adjacentPos -> val updatedDistance = distance + 1 if (updatedDistance < distances.getOrDefault(adjacentPos, Int.MAX_VALUE)) { distances[adjacentPos] = updatedDistance next.add(adjacentPos) } } } return distances.filterKeys { pos -> pos == bestSignalPosition }.values.min() } /** * Finds all the traversable positions that are * orthogonally adjacent to this one. * * To avoid needing to get out your climbing gear, * the elevation of the destination square can be at * most one higher than the elevation of your current * square; that is, if your current elevation is m, you * could step to elevation n, but not to elevation o. * (This also means that the elevation of the destination * square can be much lower than the elevation of your * current square.) * * @return A collection of traversable adjacent points */ private fun Point2D.traversableAdjacent(): Set<Point2D> { val cached = adjacencyMatrix[this] if (cached == null) { val adjacent = this.orthogonallyAdjacent() .filter { pos -> hasRecorded(pos) } .filter { dest -> getTile(this).canTraverseTo(getTile(dest)) } .toSet() adjacencyMatrix[this] = adjacent return adjacent } return cached } }
0
Kotlin
0
0
703db17fe02a24d809cc50f23a542d9a74f855fb
4,419
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0857_minimum_cost_to_hire_k_workers // #Hard #Array #Sorting #Greedy #Heap_Priority_Queue // #2023_03_31_Time_302_ms_(100.00%)_Space_39.4_MB_(100.00%) import java.util.PriorityQueue class Solution { fun mincostToHireWorkers(quality: IntArray, wage: IntArray, k: Int): Double { val n = quality.size val workers = arrayOfNulls<Worker>(n) for (i in 0 until n) { workers[i] = Worker(wage[i], quality[i]) } workers.sortBy { it!!.ratio() } val maxHeap = PriorityQueue { a: Int, b: Int -> b.compareTo(a) } var sumQuality = 0 var result = Double.MAX_VALUE for (i in 0 until n) { val worker = workers[i] sumQuality += worker!!.quality maxHeap.add(worker.quality) if (maxHeap.size > k) { sumQuality -= maxHeap.remove()!! } val groupRatio = worker.ratio() if (maxHeap.size == k) { result = Math.min(sumQuality * groupRatio, result) } } return result } internal class Worker(var wage: Int, var quality: Int) { fun ratio(): Double { return wage.toDouble() / quality } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,275
LeetCode-in-Kotlin
MIT License
semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/graph/util.kt
justnero
43,222,066
false
null
package bellman.graph val INFINITE = Int.MAX_VALUE val NO_EDGE = INFINITE typealias AdjacencyMatrix = Array<IntArray> typealias AdjacencyMatrix1D = IntArray typealias AdjacencyList = Array<Adjacency> typealias PlainAdjacencyList = IntArray typealias Adjacency = Triple<Int, Int, Int> data class InputGraph(val adjacencyMatrix: AdjacencyMatrix, val sourceVertex: Int, val vertexNumber: Int = adjacencyMatrix.size) enum class PlainAdjacency(val number: Int) { SOURCE(0), DESTINATION(1), WEIGHT(2) } object Util { object AdjacencyUtil { val Adjacency.source: Int get() = this.first val Adjacency.destination: Int get() = this.second val Adjacency.weight: Int get() = this.third } object AdjacencyMatrixUtil { inline fun AdjacencyMatrix.vertexNumber() = this.size fun AdjacencyMatrix.toPlainAdjacencyList(): PlainAdjacencyList = this.mapIndexed { rowNum, row -> row.mapIndexed { colNum, weight -> if (weight != INFINITE) intArrayOf(rowNum, colNum, weight) else null } .filterNotNull() .reduce { acc, ints -> acc + ints } } .reduce { acc, list -> acc + list } fun AdjacencyMatrix.toAdjacencyList() = this.mapIndexed { row, ints -> ints.mapIndexed { col, w -> if (w != INFINITE) Triple(row, col, w) else null } .filterNotNull() } .reduce { acc, list -> acc + list } .toTypedArray() } object PlainAdjacencyListUtil { inline operator fun PlainAdjacencyList.get(index: Int, col: Int) = this[3 * index + col] inline operator fun PlainAdjacencyList.get(index: Int, content: PlainAdjacency) = this[index, content.number] val PlainAdjacencyList.edgeNumber: Int get() = (this.size + 1) / 3 } }
0
Java
6
16
14f58f135e57475b98826c4128b2b880b6a2cb9a
1,991
university
MIT License
Problem Solving/Algorithms/Medium - The Time in Words.kt
MechaArms
525,331,223
false
{"Kotlin": 30017}
/* Given the time in numerals we may convert it into words, as shown below: 5:00 -> five o' clock 5:01 -> one minute past five 5:10 -> ten minutes past five 5:15 -> quarter past five 5:30 -> half past five 5:40 -> twenty minutes to six 5:45 -> quarter to six 5:47 -> thirteen minutes to six 5:28 -> twenty eight minutes past five At minutes = 0, use o' clock. For 1 <= minutes <= 30, use past, and for use to. Note the space between the apostrophe and clock in o' clock. Write a program which prints the time in words for the input given in the format described. Function Description Complete the timeInWords function in the editor below. timeInWords has the following parameter(s): int h: the hour of the day int m: the minutes after the hour Returns string: a time string as described Input Format The first line contains h, the hours portion The second line contains m, the minutes portion Sample Input 0 5 47 Sample Output 0 thirteen minutes to six Sample Input 1 3 00 Sample Output 1 three o' clock Sample Input 2 7 15 Sample Output 2 quarter past seven */ fun timeInWords(h: Int, m: Int): String { val a = arrayOf( "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine" ) return when { m == 0 -> "${a[h]} o' clock" m == 1 -> "${a[m]} minute past ${a[h]}" m == 15 -> "quarter past ${a[h]}" m == 30 -> "half past ${a[h]}" m == 45 -> "quarter to ${a[h + 1]}" m == 59 -> "${a[60 - m]} minute to ${a[h + 1]}" m < 30 -> "${a[m]} minutes past ${a[h]}" else -> "${a[60 - m]} minutes to ${a[h + 1]}" } } fun main(args: Array<String>) { val h = readLine()!!.trim().toInt() val m = readLine()!!.trim().toInt() val result = timeInWords(h, m) println(result) }
0
Kotlin
0
1
eda7f92fca21518f6ee57413138a0dadf023f596
2,142
My-HackerRank-Solutions
MIT License
src/day03/Day03.kt
tiginamaria
573,173,440
false
{"Kotlin": 7901}
package day03 import readInput private fun priority(c: Char): Int { if (c.isLowerCase()) return c - 'a' + 1 return c - 'A' + 27 } fun main() { fun part1(input: List<String>) = input.sumOf { val n = it.length / 2 val firstComp = it.take(n).toSet() val lastComp = it.takeLast(n).toSet() firstComp.intersect(lastComp).sumOf { shareComp -> priority(shareComp) } } fun part2(input: List<String>) = input.chunked(3).sumOf { group -> group[0].toSet().intersect(group[1].toSet()).intersect(group[2].toSet()).sumOf { priority(it) } } val input = readInput("Day03", 3) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bf81cc9fbe11dce4cefcb80284e3b19c4be9640e
704
advent-of-code-kotlin
Apache License 2.0
src/Day06.kt
ktrom
573,216,321
false
{"Kotlin": 19490, "Rich Text Format": 2301}
fun main() { fun part1(input: List<String>): Int { return getStartWithDistinctMarker(input.get(0), 4) } fun part2(input: List<String>): Int { return getStartWithDistinctMarker(input.get(0), 14) } // test if implementation meets criteria from the description val testInput = readInput("Day06_test") println(part1(testInput) == 5) val input = readInput("Day06") println(part1(input)) println(part2(testInput) == 23) println(part2(input)) } fun getStartWithDistinctMarker(datastream: String, markerSize: Int): Int{ val precedingCharacters: MutableList<Char> = datastream.subSequence(0, markerSize).toMutableList() var pos = markerSize datastream.substring(markerSize).forEach { if(precedingCharacters.distinct().size == markerSize){ return pos } precedingCharacters.set(pos % markerSize, it) pos++ } return -1 }
0
Kotlin
0
0
6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd
941
kotlin-advent-of-code
Apache License 2.0
src/main/kotlin/days/aoc2023/Day6.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2023 import days.Day class Day6 : Day(2023, 6) { override fun partOne(): Any { return calculatePartOne(inputList) } fun calculatePartOne(inputList: List<String>): Int { val timesAndDistances = inputList[0].split("\\s+".toRegex()).drop(1).map { it.toInt() }.zip( inputList[1].split("\\s+".toRegex()).drop(1).map { it.toInt() }) return timesAndDistances.fold(1) { current, race -> current * calculateWaysToWin(race.first.toLong(), race.second.toLong()) } } private fun calculateWaysToWin(time: Long, distance: Long): Int { return (0..time).count { millisHeldDown -> millisHeldDown * (time - millisHeldDown) > distance } } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartTwo(inputList: List<String>): Int { val time = inputList[0].dropWhile { it != ':' }.drop(1).replace("\\s+".toRegex(), "").toLong() val distance = inputList[1].dropWhile { it != ':' }.drop(1).replace("\\s+".toRegex(), "").toLong() return calculateWaysToWin(time, distance) } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,180
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/SplitArraySameAverage.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode private fun IntArray.check(leftSum: Int, leftNum: Int, startIndex: Int): Boolean { if (leftNum == 0) return leftSum == 0 if (this[startIndex] > leftSum / leftNum) return false for (i in startIndex until this.size - leftNum + 1) { if (i > startIndex && this[i] == this[i - 1]) continue if (this.check(leftSum - this[i], leftNum - 1, i + 1)) return true } return false } fun IntArray.splitArraySameAverage(): Boolean { if (this.size == 1) return false var sumA = 0 for (a in this) { sumA += a } this.sort() for (lenOfB in 1..this.size / 2) { if (sumA * lenOfB % this.size == 0 && this.check(sumA * lenOfB / this.size, lenOfB, 0)) { return true } } return false }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,408
kotlab
Apache License 2.0
src/main/kotlin/leetCode/40.kt
wenvelope
692,706,194
false
{"Kotlin": 11474, "Java": 7490}
package leetCode fun main() { val candidates = intArrayOf( 10, 1, 2, 7, 6, 1, 5 ) val result = combinationSum2(candidates, 8) println(result.toString()) } fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { val resultList = arrayListOf<ArrayList<Int>>() val tempList = arrayListOf<Int>() val hashMap = HashMap<Int, Int>().apply { candidates.forEach { put(it, if (get(it) == null) 1 else get(it)!! + 1) } } combineChange(tempList, resultList, 0, candidates.distinct().sorted(), target, hashMap) return resultList } fun combineChange( tempList: ArrayList<Int>, resultList: ArrayList<ArrayList<Int>>, index: Int, candidates: List<Int>, target: Int, dataMap: HashMap<Int, Int> ) { val sum = tempList.sum() if (sum >= target) { if (sum == target) { val list = ArrayList(tempList) resultList.add(list) return } return } for (item in candidates) { if (dataMap[item] == 0) { continue } if (tempList.size >= 1 && item < tempList[tempList.size - 1]) { continue } tempList.add(item) dataMap[item] = dataMap[item]!! - 1 combineChange(tempList, resultList, index + 1, candidates, target, dataMap) tempList.removeAt(index) dataMap[item] = dataMap[item]!! + 1 } }
0
Kotlin
0
1
4a5b2581116944c5bf8cf5ab0ed0af410669b9b6
1,450
OnlineJudge
Apache License 2.0
src/main/kotlin/days/Day4.kt
felix-ebert
317,592,241
false
null
package days class Day4 : Day(4) { override fun partOne(): Any { val passwords = inputString.split("\n\n") return passwords.count { validatePolicyOne(it) } } override fun partTwo(): Any { val passwords = inputString.split("\n\n") return passwords.count { validatePolicyTwo(it) } } private fun validatePolicyOne(password: String): Boolean { val policies = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") return policies.stream().allMatch(password::contains) } private fun validatePolicyTwo(password: String): Boolean { val fields = password.replace("\n", " ") .split(" ") .map { it.split(":") } .map { it.first() to it.last() } .toMap() return isValidYear(fields.getOrDefault("byr", "0"), 1920, 2002) && isValidYear(fields.getOrDefault("iyr", "0"), 2010, 2020) && isValidYear(fields.getOrDefault("eyr", "0"), 2020, 2030) && isValidHeight(fields.getOrDefault("hgt", "")) && isValidHairColor(fields.getOrDefault("hcl", "")) && isValidEyeColor(fields.getOrDefault("ecl", "")) && isValidPassportId(fields.getOrDefault("pid", "")) } private fun isValidYear(year: String, least: Int, most: Int): Boolean { return year.toInt() in least..most } private fun isValidHeight(height: String): Boolean { return (height.contains("cm") && height.substringBefore("cm").toInt() in 150..193) || (height.contains("in") && height.substringBefore("in").toInt() in 59..76) } private fun isValidHairColor(color: String): Boolean { return color.matches(Regex("#-?[0-9a-fA-F]+")) } private fun isValidEyeColor(color: String): Boolean { return listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(color) } private fun isValidPassportId(id: String): Boolean { return id.matches(Regex("^(?=\\d{9}\$)\\d*[1-9]\\d*")) } }
0
Kotlin
0
4
dba66bc2aba639bdc34463ec4e3ad5d301266cb1
2,056
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day02_part2.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part2(input: List<String>): Int { val rock = 1 val paper = 2 val scissors = 3 val lose = 0 val draw = 3 val win = 6 fun convertLeft(input: Char): Int { return when (input) { 'A' -> rock 'B' -> paper else -> scissors } } fun convertRight(input: Char): Int { return when (input) { 'X' -> lose 'Y' -> draw else -> win } } fun normalise(result: Int): Int { if (result < 1) { return result + 3 } if (result > 3) { return result - 3 } return result } var total = 0 for (it in input) { val left = convertLeft(it[0]) val right = convertRight(it[2]) total += when (right) { lose -> normalise(left - 1) win -> normalise(left + 1) else -> left } total += right } return total } val testInput = readInput("Day02_test") check(part2(testInput) == 12) val input = readInput("Day02") println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
1,310
advent-of-code-2022
Apache License 2.0
src/Day19.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
import kotlin.math.ceil import kotlin.math.min fun main() { data class Blueprint( val id: Int, val oreRobotCost: Int, val clayRobotCost: Int, val obsidianRobotCost: Pair<Int, Int>, val geodeRobotCost: Pair<Int, Int> ) data class Resources( var ore: Int = 0, var clay: Int = 0, var obsidian: Int = 0, var geode: Int = 0 ) data class State( val timeLimit: Int, var timer: Int = 0, var robots: Resources = Resources(1, 0, 0, 0), var materials: Resources = Resources(0, 0, 0, 0) ) { fun tick(minutes: Int): State { val time = min(timeLimit - timer, minutes) return this.copy( materials = materials.copy( ore = materials.ore + robots.ore * time, clay = materials.clay + robots.clay * time, obsidian = materials.obsidian + robots.obsidian * time, geode = materials.geode + robots.geode * time ), timer = timer + time ) } } // Some ideas taken from https://github.com/ckainz11/AdventOfCode2022/blob/main/src/main/kotlin/days/day19/Day19.kt class Simulator( val blueprint: Blueprint, var maxGeodeOutput: Int = 0 ) { val maxCosts = Resources( maxOf(blueprint.oreRobotCost, blueprint.clayRobotCost, blueprint.obsidianRobotCost.first), blueprint.obsidianRobotCost.second, blueprint.geodeRobotCost.second ) fun run(state: State): Int { // Return the blueprint's maximum geode output when the timer ends if (state.timer >= state.timeLimit) { maxGeodeOutput = maxOf(maxGeodeOutput, state.materials.geode) return state.materials.geode } // Bail if it's impossible to improve the output (using every remaining minute to build a geode robot) if (state.materials.geode + (0 until state.timeLimit - state.timer).sumOf { it + state.robots.geode } < maxGeodeOutput) { return 0 } // Find the best branch return maxOf( if (state.robots.obsidian > 0) run(buildGeodeRobot(state)) else 0, if (state.robots.clay > 0 && state.robots.obsidian < maxCosts.obsidian) run(buildObsidianRobot(state)) else 0, if (state.robots.ore > 0 && state.robots.clay < maxCosts.clay) run(buildClayRobot(state)) else 0, if (state.robots.ore in 1 until maxCosts.ore) run(buildOreRobot(state)) else 0 ) } fun buildOreRobot(state: State): State { val requiredOre = maxOf(blueprint.oreRobotCost - state.materials.ore, 0).toFloat() return state.tick( if (requiredOre > 0) ceil(requiredOre / state.robots.ore).toInt() + 1 else 1 ).let { it.copy( materials = it.materials.copy(ore = it.materials.ore - blueprint.oreRobotCost), robots = it.robots.copy(ore = it.robots.ore + 1) ) } } fun buildClayRobot(state: State): State { val requiredOre = maxOf(blueprint.clayRobotCost - state.materials.ore, 0).toFloat() return state.tick( if (requiredOre > 0) ceil(requiredOre / state.robots.ore).toInt() + 1 else 1 ).let { it.copy( materials = it.materials.copy(ore = it.materials.ore - blueprint.clayRobotCost), robots = it.robots.copy(clay = it.robots.clay + 1) ) } } fun buildObsidianRobot(state: State): State { val requiredOre = maxOf(blueprint.obsidianRobotCost.first - state.materials.ore, 0).toFloat() val requiredClay = maxOf(blueprint.obsidianRobotCost.second - state.materials.clay, 0).toFloat() return state.tick( if (requiredOre > 0 || requiredClay > 0) { maxOf( ceil(requiredOre / state.robots.ore), ceil(requiredClay / state.robots.clay) ).toInt() + 1 } else 1 ).let { it.copy( materials = it.materials.copy( ore = it.materials.ore - blueprint.obsidianRobotCost.first, clay = it.materials.clay - blueprint.obsidianRobotCost.second ), robots = it.robots.copy(obsidian = it.robots.obsidian + 1) ) } } fun buildGeodeRobot(state: State): State { val requiredOre = maxOf(blueprint.geodeRobotCost.first - state.materials.ore, 0).toFloat() val requiredObsidian = maxOf(blueprint.geodeRobotCost.second - state.materials.obsidian, 0).toFloat() return state.tick( if (requiredOre > 0 || requiredObsidian > 0) { maxOf( ceil(requiredOre / state.robots.ore), ceil(requiredObsidian / state.robots.obsidian) ).toInt() + 1 } else 1 ).let { it.copy( materials = it.materials.copy( ore = it.materials.ore - blueprint.geodeRobotCost.first, obsidian = it.materials.obsidian - blueprint.geodeRobotCost.second ), robots = it.robots.copy(geode = it.robots.geode + 1) ) } } } fun processInput(input: List<String>): List<Blueprint> { val blueprints = mutableListOf<Blueprint>() val regex = Regex("\\d+") for (line in input) { val num = regex.findAll(line).map { it.value.toInt() }.toList() blueprints.add(Blueprint(num[0], num[1], num[2], Pair(num[3], num[4]), Pair(num[5], num[6]))) } return blueprints } fun solve(blueprint: Blueprint, state: State): Int { return Simulator(blueprint).run(state) } fun part1(blueprints: List<Blueprint>): Int { return blueprints .map { Pair(it.id, solve(it, State(24))) } .sumOf { (it.first) * it.second } } fun part2(blueprints: List<Blueprint>): Int { return blueprints.take(3) .map { solve(it, State(32)) } .reduce(Int::times) } val testInput = processInput(readInput("Day19_test")) check(part1(testInput) == 33) check(part2(testInput) == 3472) val input = processInput(readInput("Day19")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
7,029
aoc-2022
Apache License 2.0
src/main/kotlin/year2023/day22/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2023.day22 import IProblem import kotlin.math.max class Problem : IProblem { private val blocks = mutableListOf<Pair<Triple<Int, Int, Int>, Triple<Int, Int, Int>>>() private val coords: Array<Array<IntArray>> private val support: Array<BooleanArray> private val depth: Int private val width: Int private val height: Int init { var d = 0 var w = 0 var h = 0 javaClass .getResourceAsStream("/2023/22.txt")!! .bufferedReader() .forEachLine { val split0 = it.split('~') val split1 = split0[0].split(',') val split2 = split0[1].split(',') val start = Triple(split1[0].toInt(), split1[1].toInt(), split1[2].toInt()) val end = Triple(split2[0].toInt(), split2[1].toInt(), split2[2].toInt()) if (end.first > d) { d = end.first } if (end.second > w) { w = end.second } if (end.third > h) { h = end.third } blocks.add(Pair(start, end)) } blocks.sortBy { it.first.third } depth = d + 1 width = w + 1 height = h + 1 coords = Array(depth) { Array(width) { IntArray(height) } } support = Array(blocks.size + 1) { BooleanArray(blocks.size + 1) } dropItLikeItsHot() mapSupport() } private fun dropItLikeItsHot() { val elevator = Array(depth) { IntArray(width) } var i = 1 for ((start, end) in blocks) { val (x0, y0, z0) = start val (x1, y1, z1) = end var h = 0 for (x in x0..x1) { h = max(elevator[x][y0], h) } for (y in y0 + 1..y1) { h = max(elevator[x0][y], h) } for (x in x0..x1) { coords[x][y0][h] = i elevator[x][y0] = h + 1 } for (y in y0 + 1..y1) { coords[x0][y][h] = i elevator[x0][y] = h + 1 } for (z in z0 + 1..z1) { coords[x0][y0][++h] = i } elevator[x0][y0] = h + 1 i++ } } private fun mapSupport() { for (z in 0 until height - 1) { for (x in 0 until depth) { for (y in 0 until width) { val i = coords[x][y][z] val j = coords[x][y][z + 1] if (i != 0 && j != 0 && i != j) { support[i][j] = true } } } } } private fun hasSupport(support: Array<BooleanArray>, i: Int, j: Int): Boolean { for (k in support.indices) { if (i != k && support[k][j]) { return true } } return false } private fun yeet(support: Array<BooleanArray>, i: Int): Boolean { for (j in support.indices) { if (support[i][j] && !hasSupport(support, i, j)) { return false } } return true } private fun hasSupport(support: Array<BooleanArray>, yeeted: BooleanArray, i: Int): Boolean { for (j in support.indices) { if (support[j][i] && !yeeted[j]) { return true } } return false } private fun dfs(coords: Array<Array<IntArray>>, support: Array<BooleanArray>, yeeted: BooleanArray, i: Int): Int { var n = 0 yeeted[i] = true for (j in support.indices) { if (support[i][j] && !hasSupport(support, yeeted, j)) { n += dfs(coords, support, yeeted, j) + 1 } } return n } override fun part1(): Int { var count = 0 for (i in 1..blocks.size) { if (yeet(support, i)) { count++ } } return count } override fun part2(): Int { var sum = 0 for (i in 1..blocks.size) { sum += dfs(coords, support, BooleanArray(blocks.size + 1), i) } return sum } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
4,317
advent-of-code
The Unlicense
Practice/Algorithms/Strings/WeightedUniformStrings.kts
kukaro
352,032,273
false
null
import kotlin.collections.* import kotlin.io.* import kotlin.ranges.* import kotlin.text.* /* * Complete the 'weightedUniformStrings' function below. * * The function is expected to return a STRING_ARRAY. * The function accepts following parameters: * 1. STRING s * 2. INTEGER_ARRAY queries */ fun weightedUniformStrings(s: String, queries: Array<Int>): ArrayList<String> { var mp = HashMap<Int, Boolean>() var cnt = 0 var pv = 'A' var ret = ArrayList<String>() for (ps in s) { if (pv == ps) { cnt += ps.toInt() - 'a'.toInt() + 1 mp[cnt] = true } else { mp[cnt] = true cnt = ps.toInt() - 'a'.toInt() + 1 mp[cnt] = true } pv = ps } for (query in queries) { if (mp[query] != null) { ret.add("Yes") } else { ret.add("No") } } return ret } fun main(args: Array<String>) { val s = readLine()!! val queriesCount = readLine()!!.trim().toInt() val queries = Array<Int>(queriesCount, { 0 }) for (i in 0 until queriesCount) { val queriesItem = readLine()!!.trim().toInt() queries[i] = queriesItem } val result = weightedUniformStrings(s, queries) println(result.joinToString("\n")) }
0
Kotlin
0
0
4f04ff7b605536398aecc696f644f25ee6d56637
1,310
hacker-rank-solved
MIT License
src/Day03.kt
skarlman
572,692,411
false
{"Kotlin": 4076}
import java.io.File // Problem: // https://adventofcode.com/2022/day/3 // More solutions: // https://www.competitivecoders.com/ProgrammingCompetitions/advent-of-code/advent-of-code/2022/day-3/ fun main() { fun part1(input: List<String>): Int { return input.map { row -> val parts = row.chunked(row.length / 2) for (c in parts[0]) { if (parts[1].contains(c)) { return@map if (c.code > 96) c.code - 96 else c.code - 64 + 26 } } return@map 0 }.sum() } fun part2(input: List<String>): Int { return input.chunked(3).map { for (c in it[0]) { if (it[1].contains(c) && it[2].contains(c)){ return@map if (c.code > 96) c.code - 96 else c.code - 64 + 26 } } return@map 0 }.sum() } val input = readInput("Day03") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
ef15752cfa6878ce2740a86c48b47597b8d5cabc
1,155
AdventOfCode2022_kotlin
Apache License 2.0
codeforces/globalround16/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.globalround16 private fun solve() { val n = readInt() val nei = List(n) { mutableListOf<Int>() } repeat(n - 1) { val (v, u) = readInts().map { it - 1 } nei[v].add(u) nei[u].add(v) } val kids = IntArray(n) val isLeaf = BooleanArray(n) val isBud = BooleanArray(n) var ans = 0 fun dfs(v: Int, p: Int = -1) { var nonLeaves = false for (u in nei[v]) { if (u == p) continue dfs(u, v) if (isBud[u]) continue kids[v]++ if (!isLeaf[u]) nonLeaves = true } isLeaf[v] = (p != -1 && kids[v] == 0) isBud[v] = (p != -1 && !nonLeaves && !isLeaf[v]) if (isBud[v]) ans-- if (isLeaf[v]) ans++ if (v == 0 && kids[v] == 0) ans++ } dfs(0) println(ans) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
929
competitions
The Unlicense
src/main/kotlin/problems/Koko.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
/** Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours. Input: piles = [3,6,7,11], h = 8 Output: 4 Input: piles = [30,11,23,4,20], h = 5 Output: 30 */ object Koko { fun minEatingSpeed(piles: IntArray, h: Int): Int { // Koko can eat max bananas -> max of piles val maxPile = maxPiles(piles) if (h == piles.size) { return maxPile } // so, koko can have minimum 1 banana and maximum maxPile banana // we can do binary search within a range 1..maxPile var i = 1 var j = maxPile var mid: Int = 0 while (i <= j) { mid = (i+j)/2 val hours = calculateMaxHoursTaken(piles, bananasPerHour = mid) when { hours > h -> i = mid + 1 // should increase speed hours < h -> j = mid - 1 // can decrease speed else -> return mid } } return mid } fun calculateMaxHoursTaken(piles: IntArray, bananasPerHour: Int): Int { var hours = 0 for (pile in piles) { hours += Math.ceil(pile.toDouble()/bananasPerHour).toInt() } return hours } fun maxPiles(piles: IntArray): Int { var m = Int.MIN_VALUE for (i in piles.indices) { m = maxOf(piles[i], m) } return m } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,891
data-structures
MIT License
src/main/day02/Part2.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day02 import readInput; import java.lang.IllegalArgumentException fun main() { val testinput = readInput("day02/testinput.txt") val input = readInput("day02/input.txt") val movesForResult = buildMap<Pair<Move, Result>, Move>() { put(Pair(Move.ROCK, Result.WIN), Move.PAPER) put(Pair(Move.ROCK, Result.LOSS), Move.SCISSORS) put(Pair(Move.ROCK, Result.DRAW), Move.ROCK) put(Pair(Move.PAPER, Result.WIN), Move.SCISSORS) put(Pair(Move.PAPER, Result.LOSS), Move.ROCK) put(Pair(Move.PAPER, Result.DRAW), Move.PAPER) put(Pair(Move.SCISSORS, Result.WIN), Move.ROCK) put(Pair(Move.SCISSORS, Result.LOSS), Move.PAPER) put(Pair(Move.SCISSORS, Result.DRAW), Move.SCISSORS) } val totalscore = input .map { it.split(" ") } .map { Pair(toMove(it.first()), toExpectedResult(it.last())) } .map { Round(it.first, movesForResult[it]!!) } .map { round -> round.score() } .map { it.second } .sum() println("Day 2 part 2. Total score $totalscore") } fun toMove(value: String): Move { return when(value) { "A" -> Move.ROCK "B" -> Move.PAPER "C" -> Move.SCISSORS else -> { throw IllegalArgumentException("Unknown move $value") } } } fun toExpectedResult(value: String): Result { return when(value) { "X" -> Result.LOSS "Y" -> Result.DRAW "Z" -> Result.WIN else-> { throw IllegalArgumentException("Unknown result $value") } } }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
1,558
aoc2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions68.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.BinaryTreeNode fun test68() { printlnResult('F', 'I') printlnResult('H', 'I') printlnResult('B', 'C') printlnResult('H', 'I') printlnResult('F', 'G') printlnResult('D', 'E') printlnResult('D', 'I') printlnResult('F', 'E') } /** * Questions 68: FInd the lowest public patent node of two nodes in a binary tree */ private fun <T> findLowestParent(root: BinaryTreeNode<T>, node1: T, node2: T): BinaryTreeNode<T>? = root.findLowestParent(node1, node2).second private fun <T> BinaryTreeNode<T>.findLowestParent(node1: T, node2: T): Pair<Boolean, BinaryTreeNode<T>?> { if (value == node1 || value == node2) return true to null val leftFound = left?.findLowestParent(node1, node2) val rightFound = right?.findLowestParent(node1, node2) return when { leftFound?.second != null -> true to leftFound.second rightFound?.second != null -> true to rightFound.second leftFound?.first == true && rightFound?.first == true -> true to this else -> (leftFound?.first == true || rightFound?.first == true) to null } } private fun buildBinaryTreeTest(): BinaryTreeNode<Char> = BinaryTreeNode( value = 'A', left = BinaryTreeNode( value = 'B', left = BinaryTreeNode( value = 'D', left = BinaryTreeNode(value = 'F'), right = BinaryTreeNode(value = 'G'), ), right = BinaryTreeNode( value = 'E', left = BinaryTreeNode('H'), right = BinaryTreeNode('I'), ), ), right = BinaryTreeNode(value ='C')) private fun printlnResult(c1: Char, c2: Char) = println("The lowest parent of node $c1 and $c2 is ${findLowestParent(buildBinaryTreeTest(), c1, c2)?.value}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,904
Algorithm
Apache License 2.0
src/main/kotlin/aoc2016/NoTimeForATaxicab.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2016 import komu.adventofcode.utils.Direction import komu.adventofcode.utils.Point import kotlin.math.absoluteValue fun taxicab(s: String): Int { val directions = s.trim().split(", ").map { TaxicabStep.parse(it) } var point = Point.ORIGIN var dir = Direction.UP for ((turn, steps) in directions) { dir = turn(dir, turn) point = point.towards(dir, steps) } return (point.x + point.y).absoluteValue } fun taxicab2(s: String): Int { val directions = s.trim().split(", ").map { TaxicabStep.parse(it) } var point = Point.ORIGIN var dir = Direction.UP val visited = mutableSetOf<Point>() for ((turn, steps) in directions) { dir = turn(dir, turn) repeat(steps) { point += dir if (!visited.add(point)) return (point.x + point.y).absoluteValue } } error("nothing visited twice") } private fun turn(dir: Direction, turn: String) = when (turn) { "L" -> dir.left "R" -> dir.right else -> error("invalid turn '$turn'") } private data class TaxicabStep(val turn: String, val steps: Int) { companion object { private val regex = Regex("""(.)(\d+)""") fun parse(s: String): TaxicabStep { val m = regex.matchEntire(s) ?: error("invalid input '$s'") return TaxicabStep(m.groupValues[1], m.groupValues[2].toInt()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,443
advent-of-code
MIT License
src/main/kotlin/Day01.kt
N-Silbernagel
573,145,327
false
{"Kotlin": 118156}
import java.util.* fun main () { val input = readFileAsList("Day01") println(Day01.part1(input)) println(Day01.part2(input)) } object Day01 { fun part1(input: List<String>): Int { var mostCalories = 0 var currentCalories = 0 for (line in input) { if (line.isBlank()) { if (currentCalories > mostCalories) { mostCalories = currentCalories } currentCalories = 0 continue } val lineCalories = line.toInt() currentCalories += lineCalories } return mostCalories } fun part2(input: List<String>): Int { val top3Calories = TreeSet<Int>() var currentCalories = 0 for (line in input) { if (line.isBlank()) { top3Calories.add(currentCalories) if (top3Calories.size > 3) { top3Calories.remove(top3Calories.first()) } currentCalories = 0 continue } val lineCalories = line.toInt() currentCalories += lineCalories } return top3Calories.sum() } }
0
Kotlin
0
0
b0d61ba950a4278a69ac1751d33bdc1263233d81
1,231
advent-of-code-2022
Apache License 2.0
app/src/main/java/online/vapcom/codewars/algorithms/PlantsAndZombies.kt
vapcomm
503,057,535
false
{"Kotlin": 142486}
package online.vapcom.codewars.algorithms /** * #28 Plants and Zombies - 3 kyu * * https://www.codewars.com/kata/5a5db0f580eba84589000979 * * @param zombies [i,row,hp] - where i is the move number (0-based) when it appears, * row is the row the zombie walks down, and hp is the initial health point value of the zombie. */ fun plantsAndZombies(lawn: Array<String>, zombies: Array<IntArray>): Int? { class BattleField(lawn: Array<String>) { private abstract inner class Creature private open inner class Shooter(val row: Int, val column: Int) : Creature() private inner class NumShooter(row: Int, column: Int, val power: Int) : Shooter(row, column) { override fun toString(): String = "N$power" } private inner class SuperShooter(row: Int, column: Int) : Shooter(row, column) { override fun toString(): String = "SS" } private inner class Zombie(var hp: Int) : Creature() { fun takeHit() { if (hp > 0) hp-- } fun isDead(): Boolean = hp <= 0 override fun toString(): String = "$hp".padStart(2, ' ') } private inner class Empty : Creature() { override fun toString(): String = " " } val field: Array<Array<Creature>> = Array(lawn.size) { Array(lawn[0].length) { Empty() } } val numShooters = mutableListOf<NumShooter>() val superShooters = mutableListOf<SuperShooter>() init { lawn.forEachIndexed { i, str -> str.forEachIndexed { j, c -> when (c) { 'S' -> { val ss = SuperShooter(i, j) field[i][j] = ss superShooters.add(ss) } in '0'..'9' -> { val ns = NumShooter(i, j, c.digitToInt()) field[i][j] = ns numShooters.add(ns) } } } } //DOC : S-shooters fire their shots in order from right to left, then top to bottom // so sort them out superShooters.sortWith { s1, s2 -> if (s1.column == s2.column) { s1.row.compareTo(s2.row) } else { -(s1.column.compareTo(s2.column)) } } } val maxColumn = field[0].lastIndex val maxRow = field.lastIndex override fun toString(): String { val sb = StringBuilder() sb.append(" ") repeat(field[0].size) { sb.append(" "); sb.append(it % 100) } sb.append("\n") field.forEachIndexed { index, creatures -> sb.append(index) sb.append(":'") sb.append(creatures.joinToString("") { it.toString() }) sb.append("'\n") } return sb.toString() } fun addZombies(newZombies: List<IntArray>) { println("add zombies: ${newZombies.size}") val zombieStart = field[0].lastIndex newZombies.forEach { zombie -> // [i, row, hp] field[zombie[1]][zombieStart] = Zombie(zombie[2]) } } fun moveZombies() { field.forEachIndexed { index, row -> for (i in 1..row.lastIndex) { if (row[i] is Zombie) { if (row[i - 1] is Shooter) { eliminateShooter(index, i - 1) } row[i - 1] = row[i] row[i] = Empty() } } } } private fun eliminateShooter(row: Int, column: Int) { println("shooter [$row,${column}] ELIMINATED") if (!numShooters.removeIf { it.row == row && it.column == column }) { superShooters.removeIf { it.row == row && it.column == column } } } fun shoot() { //DOC: The numbered shooters fire all their shots in a cluster // shoot straight (to the right) a given number of times per move. numShooters.forEach { shooter -> println("num shooter[${shooter.row},${shooter.column}] fire ${shooter.power} times from ${shooter.column + 1} to $maxColumn") repeat(shooter.power) { for (i in (shooter.column + 1)..maxColumn) { if(fireTo(shooter.row, i)) break } } } //DOC: S-shooters shoot straight, and diagonally upward and downward (ie. three directions simultaneously) once per move. superShooters.forEach { ss -> println("super shooter[${ss.row},${ss.column}]") fireLine(ss.row, ss.column, -1) // up diagonal fireLine(ss.row, ss.column, 0) // horizontal fireLine(ss.row, ss.column, 1) // down diagonal } } // shoot() private fun fireLine(shooterRow: Int, shooterColumn: Int, rowDelta: Int) { var row = shooterRow + rowDelta var column = shooterColumn + 1 while (row in 0..maxRow && column <= maxColumn) { if(fireTo(row, column)) break row += rowDelta column++ } } /** * Try to hit zombie, if hit something, return true */ private fun fireTo(row: Int, column: Int): Boolean { val creature = field[row][column] if (creature is Zombie) { creature.takeHit() println("zombie [$row,$column] hit, hp left: ${creature.hp}") if (creature.isDead()) { //DOC: once a zombie's health reaches 0 it drops immediately and does not absorb any additional shooter pellets. println("zombie [$row,$column] DEAD") field[row][column] = Empty() } return true } return false } fun zombiesWon(): Boolean = field.find { it[0] is Zombie } != null fun shootersWon(): Boolean = numberOfZombies() <= 0 fun numberOfZombies(): Int = field.sumOf { row -> row.sumOf { if (it is Zombie) 1.toInt() else 0 } } } println("lawn: '${lawn.joinToString { "\"$it\"" }}'") val zb = zombies.joinToString { "intArrayOf(${it[0]}, ${it[1]}, ${it[2]})" } println("zombies: '$zb'") printLawn(lawn) val bf = BattleField(lawn) println("Start field:") println(bf) val maxZombiesStep: Int = zombies.maxByOrNull { it[0] }?.get(0) ?: 0 var step = 0 do { println("--------- Step: $step ---------") bf.moveZombies() bf.addZombies(zombies.filter { it[0] == step }) println("----- Moved/Added zombies -----") print(bf) bf.shoot() step++ print(bf) println("num shooters: ${bf.numShooters}, super: ${bf.superShooters}") println("zombies won: ${bf.zombiesWon()}, shooters won: ${bf.shootersWon()}") } while (!bf.zombiesWon() && (step <= maxZombiesStep || !bf.shootersWon())) return if (bf.zombiesWon()) step else null } fun printLawn(lawn: Array<String>) { val width = lawn[0].length print(" ") repeat(width) { print(it % 10) } println() lawn.forEachIndexed { index, str -> println("$index:'$str'") } } // version for codewars without debug logs fun plantsAndZombiesNoLogs(lawn: Array<String>, zombies: Array<IntArray>): Int? { class BattleField(lawn: Array<String>) { private abstract inner class Creature private open inner class Shooter(val row: Int, val column: Int) : Creature() private inner class NumShooter(row: Int, column: Int, val power: Int) : Shooter(row, column) private inner class SuperShooter(row: Int, column: Int) : Shooter(row, column) private inner class Zombie(var hp: Int) : Creature() { fun takeHit() { if (hp > 0) hp-- } fun isDead(): Boolean = hp <= 0 } private inner class Empty : Creature() val field: Array<Array<Creature>> = Array(lawn.size) { Array(lawn[0].length) { Empty() } } val numShooters = mutableListOf<NumShooter>() val superShooters = mutableListOf<SuperShooter>() init { lawn.forEachIndexed { i, str -> str.forEachIndexed { j, c -> when (c) { 'S' -> { val ss = SuperShooter(i, j) field[i][j] = ss superShooters.add(ss) } in '0'..'9' -> { val ns = NumShooter(i, j, c.digitToInt()) field[i][j] = ns numShooters.add(ns) } } } } //DOC : S-shooters fire their shots in order from right to left, then top to bottom // so sort them out superShooters.sortWith { s1, s2 -> if (s1.column == s2.column) { s1.row.compareTo(s2.row) } else { -(s1.column.compareTo(s2.column)) } } } val maxColumn = field[0].lastIndex val maxRow = field.lastIndex fun addZombies(newZombies: List<IntArray>) { val zombieStart = field[0].lastIndex newZombies.forEach { zombie -> // [i, row, hp] field[zombie[1]][zombieStart] = Zombie(zombie[2]) } } fun moveZombies() { field.forEachIndexed { index, row -> for (i in 1..row.lastIndex) { if (row[i] is Zombie) { if (row[i - 1] is Shooter) { eliminateShooter(index, i - 1) } row[i - 1] = row[i] row[i] = Empty() } } } } private fun eliminateShooter(row: Int, column: Int) { if (!numShooters.removeIf { it.row == row && it.column == column }) { superShooters.removeIf { it.row == row && it.column == column } } } fun shoot() { //DOC: The numbered shooters fire all their shots in a cluster // shoot straight (to the right) a given number of times per move. numShooters.forEach { shooter -> repeat(shooter.power) { for (i in (shooter.column + 1)..maxColumn) { if(fireTo(shooter.row, i)) break } } } //DOC: S-shooters shoot straight, and diagonally upward and downward (ie. three directions simultaneously) once per move. superShooters.forEach { ss -> fireLine(ss.row, ss.column, -1) // up diagonal fireLine(ss.row, ss.column, 0) // horizontal fireLine(ss.row, ss.column, 1) // down diagonal } } // shoot() private fun fireLine(shooterRow: Int, shooterColumn: Int, rowDelta: Int) { var row = shooterRow + rowDelta var column = shooterColumn + 1 while (row in 0..maxRow && column <= maxColumn) { if(fireTo(row, column)) break row += rowDelta column++ } } /** * Try to hit zombie, if hit something, return true */ private fun fireTo(row: Int, column: Int): Boolean { val creature = field[row][column] if (creature is Zombie) { creature.takeHit() if (creature.isDead()) { //DOC: once a zombie's health reaches 0 it drops immediately and does not absorb any additional shooter pellets. field[row][column] = Empty() } return true } return false } fun zombiesWon(): Boolean = field.find { it[0] is Zombie } != null fun shootersWon(): Boolean = numberOfZombies() <= 0 fun numberOfZombies(): Int = field.sumOf { row -> row.sumOf { if (it is Zombie) 1.toInt() else 0 } } } val bf = BattleField(lawn) val maxZombiesStep: Int = zombies.maxByOrNull { it[0] }?.get(0) ?: 0 var step = 0 do { bf.moveZombies() bf.addZombies(zombies.filter { it[0] == step }) bf.shoot() step++ } while (!bf.zombiesWon() && (step <= maxZombiesStep || !bf.shootersWon())) return if (bf.zombiesWon()) step else null }
0
Kotlin
0
0
97b50e8e25211f43ccd49bcee2395c4bc942a37a
13,182
codewars
MIT License
src/Day17.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
fun main() { fun nonEmpty(line: CharArray): Boolean { for (i in 1..line.size - 2) { if (line[i] != '.') { return true } } return false } fun part1(input: String): Int { val shapes = arrayOf( arrayOf( "####" ), arrayOf( ".#.", "###", ".#." ), arrayOf( "..#", "..#", "###" ), arrayOf( "#", "#", "#", "#" ), arrayOf( "##", "##", ) ) val tunnel = mutableListOf( "+-------+".toCharArray() ) var nextShape = true var shape = shapes[0] var shapeColumn = 3 var shapeRow = 0 var jetCounter = 0 var shapeCounter = 0 fun blocked(row: Int, column: Int): Boolean { for (i in shape.indices) { for (j in shape[i].indices) { if (shape[i][j] != '.' && tunnel[row + i][column + j] != '.') { return true } } } return false } fun add(row: Int, column: Int): Boolean { for (i in shape.indices) { for (j in shape[i].indices) { tunnel[row + i][column + j] = shape[i][j] } } return false } while (shapeCounter < 2022) { if (nextShape) { nextShape = false shapeRow = 0 shapeColumn = 3 shape = shapes[shapeCounter % shapes.size] val toAdd = 3 + shape.size val emptiness = List(toAdd) { "|.......|".toCharArray() } tunnel.addAll(0, emptiness) } val jet = if (input[jetCounter] == '<') -1 else 1 if (!blocked(shapeRow, shapeColumn + jet)) { shapeColumn += jet } jetCounter = (jetCounter + 1) % input.length if (!blocked(shapeRow + 1, shapeColumn)) { shapeRow += 1 } else { add(shapeRow, shapeColumn) nextShape = true while (!nonEmpty(tunnel[0])) { tunnel.removeAt(0) } shapeCounter += 1 } } return tunnel.size - 1 } fun part2(input: String): Int { return 0 } // test if implementation meets criteria from the description, like: val testInputExample = readText("Day17_example") check(part1(testInputExample) == 3068) check(part2(testInputExample) == 0) val testInput = readText("Day17_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
3,012
aoc-2022-in-kotlin
Apache License 2.0
day06/src/Day06.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day06(path: String) { private val ages = mutableListOf<Int>() private val counts = LongArray(9) { 0L } init { val lines = File(path).readLines() val items = lines[0].split(',') items.forEach { ages.add(it.toInt()) counts[it.toInt()]++ } } private fun doTimer() { var newFish = 0 for (a in ages.indices) { ages[a]-- if (ages[a] == -1) { ages[a] = 6 newFish++ } } for (i in 0 until newFish) { ages.add(8) } } private fun printList(day: Int) { print("After $day day(s): ") ages.forEach { print("$it,") } println() } fun part1(): Int { for (day in 1..80) { doTimer() printList(day) } return ages.size } private fun doTimer2() { val newFish = counts[0] for (i in 0 until 8) { counts[i] = counts[i + 1] } counts[6] += newFish counts[8] = newFish } fun part2(): Long { for (day in 1..256) { doTimer2() } return counts.sum() } } fun main(args: Array<String>) { val aoc = Day06("day06/input.txt") //println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
1,379
aoc2021
Apache License 2.0
Day14/src/Stoichiometry.kt
gautemo
225,219,298
false
null
import java.io.File fun main(){ val input = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText().trim() val ore = oreForFuel(input) println(ore) val fuelForTrillion = fuelForOre(input, 1000000000000) println(fuelForTrillion) } fun fuelForOre(input: String, maxOre: Long): Int{ val reactions = input.lines().map { Reaction(it) } val fuel = reactions.first { it.output.name == "FUEL" }.output val ore = Material("0 ORE") val needs = mutableListOf(fuel, ore) var fuelUp = 0 while (ore.nr < maxOre){ fuelUp++ fuel.nr = 1 untilOnlyOreNeeded(reactions, needs) if(fuelUp % 1000000 == 0) println("Ore: ${ore.nr}, ${ore.nr * 100 / 1000000000000}%") } return fuelUp - 1 } fun oreForFuel(input: String): Long { val reactions = input.lines().map { Reaction(it) } val needs = mutableListOf(reactions.first { it.output.name == "FUEL" }.output.copy()) untilOnlyOreNeeded(reactions, needs) return needs.first { it.name == "ORE" }.nr } fun untilOnlyOreNeeded(reactions: List<Reaction>, needs: MutableList<Material>){ while(needs.any { it.name != "ORE" && it.nr > 0 }){ handleNextReaction(reactions, needs) } } fun handleNextReaction(reactions: List<Reaction>, needs: MutableList<Material>){ val next = needs.first { it.name != "ORE" && it.nr > 0 } val reactionToNext = reactions.first { it.output.name == next.name } next.nr -= reactionToNext.output.nr for(r in reactionToNext.inputs){ val alreadyNeeded = needs.firstOrNull { n -> n.name == r.name } if(alreadyNeeded != null){ alreadyNeeded.nr += r.nr }else{ needs.add(r.copy()) } } } class Reaction(input: String){ val output: Material val inputs: List<Material> init{ val s = input.trim().split("=>") output = Material(s[1]) val inputS = s[0].split(",") inputs = inputS.map { Material(it) } } } data class Material(val input: String){ var nr: Long val name: String init{ val s = input.trim().split(" ") nr = s[0].toLong() name = s[1] } }
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
2,208
AdventOfCode2019
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day16.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.e fun main() = Day16.run() object Day16 : Day(2016, 16) { override fun part1(): Any { val len = 272 val cs = checksum(dataOf(len)) return cs.joinToString("") } private fun dataOf(len: Int): MutableList<Int> { var data = input.e().map { it.toString().toInt() }.toMutableList() while (data.size < len) { val a: MutableList<Int> = data val b: MutableList<Int> = a.reversed().map { if (it == 1) 0 else 1 }.toMutableList() data = a + 0 + b } data = data.subList(0, len) return data } private fun checksum(inp: MutableList<Int>) : List<Int> { val cs = inp.windowed(2, 2).map { if (it[0] == it[1]) 1 else 0 }.toMutableList() return if (cs.size % 2 == 0) { checksum(cs) } else { cs } } override fun part2(): Any { val len = 35651584 val cs = checksum(dataOf(len)) return cs.joinToString("") } } private operator fun <E> MutableList<E>.plus(that: E): MutableList<E> { val newList = this.toMutableList() newList.add(that) return newList } private operator fun <E> MutableList<E>.plus(that: MutableList<E>): MutableList<E> { val newList = this.toMutableList() newList.addAll(that) return newList } private fun <E> MutableList<E>.inv(): MutableList<Int> { return this.map { if (it == 1) 0 else 1}.toMutableList() }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,568
adventofkotlin
MIT License
src/main/kotlin/com/colinodell/advent2016/Day21.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day21(private val operations: List<String>) { fun solvePart1(password: String) = operations.fold(password) { text, operation -> perform(operation, text) } fun solvePart2(password: String) = operations.reversed().fold(password) { text, operation -> perform(operation, text, reverse = true) } private fun perform(operation: String, text: String, reverse: Boolean = false): String { val match = Regex("""(.+?) (\w)\b(?: .+ (\w))?""").find(operation)!!.groupValues val op = match[1] val args = match.drop(2) return when (op) { "swap position" -> swapPosition(text, args[0].toInt(), args[1].toInt()) "swap letter" -> swapLetter(text, args[0][0], args[1][0]) "rotate left" -> if (!reverse) { rotateLeft(text, args[0].toInt()) } else { rotateRight(text, args[0].toInt()) } "rotate right" -> if (!reverse) { rotateRight(text, args[0].toInt()) } else { rotateLeft(text, args[0].toInt()) } "rotate based on position of letter" -> rotateBasedOnPositionOfLetter(text, args[0][0], reverse) "reverse positions" -> reversePositions(text, args[0].toInt(), args[1].toInt()) "move position" -> if (!reverse) { movePosition(text, args[0].toInt(), args[1].toInt()) } else { movePosition(text, args[1].toInt(), args[0].toInt()) } else -> throw IllegalArgumentException("Unknown operation: $op") } } private fun swapPosition(s: String, a: Int, b: Int): String { val chars = s.toCharArray() val tmp = chars[a] chars[a] = chars[b] chars[b] = tmp return chars.joinToString("") } private fun swapLetter(s: String, a: Char, b: Char): String { return s.map { if (it == a) b else if (it == b) a else it }.joinToString("") } private fun rotateLeft(s: String, n: Int): String { val tmp = ArrayDeque(s.toList()) repeat(n) { tmp.addLast(tmp.removeFirst()) } return tmp.joinToString("") } private fun rotateRight(s: String, n: Int): String { val tmp = ArrayDeque(s.toList()) repeat(n) { tmp.addFirst(tmp.removeLast()) } return tmp.joinToString("") } private fun rotateBasedOnPositionOfLetter(s: String, c: Char, reverse: Boolean): String { val index = s.indexOf(c) return if (!reverse) { rotateRight(s, if (index >= 4) 2 + index else 1 + index) } else { rotateLeft(s, index / 2 + (if (index % 2 == 1 || index == 0) 1 else 5)) } } private fun reversePositions(s: String, a: Int, b: Int): String { return s.substring(0, a) + s.substring(a, b + 1).reversed() + s.substring(b + 1) } private fun movePosition(s: String, a: Int, b: Int): String { val chars = ArrayDeque(s.toList()) chars.add(b, chars.removeAt(a)) return chars.joinToString("") } }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
3,119
advent-2016
Apache License 2.0
src/main/kotlin/Day20.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
object Day20 { enum class ModuleType { BROADCASTER, CONJUNCTION, FLIP_FLOP } enum class PulseType { HIGH, LOW } data class Pulse(val type: PulseType, val sender: String) data class Module( val id: String, val type: ModuleType, val destinations: List<String>, var on: Boolean, val inputs: MutableSet<String> = mutableSetOf(), val lastPulses: MutableMap<String, PulseType> = mutableMapOf() ) { fun process(pulse: Pulse): List<Pair<String, Pulse>> { lastPulses[pulse.sender] = pulse.type return when (type) { ModuleType.BROADCASTER -> destinations.map { it to pulse } ModuleType.CONJUNCTION -> { val typeToSend = if (inputs.map { lastPulses[it] ?: PulseType.LOW }.all { it == PulseType.HIGH }) { PulseType.LOW } else { PulseType.HIGH } destinations.map { it to Pulse(typeToSend, id) } } ModuleType.FLIP_FLOP -> { if (pulse.type == PulseType.HIGH) { emptyList() } else { val typeToSend = if (on) { PulseType.LOW } else { PulseType.HIGH } on = !on destinations.map { it to Pulse(typeToSend, id) } } } } } companion object { fun parse(input: String): Module { val (moduleIdAndType, destinations) = input.split(" -> ") if (moduleIdAndType == "broadcaster") { return Module( "broadcaster", ModuleType.BROADCASTER, destinations.split(", "), true ) } val type = moduleIdAndType.take(1) val id = moduleIdAndType.drop(1) return Module( id, when (type) { "%" -> ModuleType.FLIP_FLOP "&" -> ModuleType.CONJUNCTION else -> throw IllegalArgumentException("Unknown module type: $type") }, destinations.split(", "), type == "&" ) } } } fun part1(input: List<String>): String { val modules = input.map { Module.parse(it) }.associateBy { it.id } modules.forEach { key, value -> value.destinations.forEach { modules[it]?.inputs?.add(key) } } val presses = (1..1000).map { pushButton(modules) }.flatMap { it.values }.reduce { acc, map -> (acc.toList() + map.toList()) .groupBy { it.first } .mapValues { it.value.map { it.second }.sum() } } return presses.values.reduce(Long::times).toString() } private fun pushButton(modules: Map<String, Module>): Map<String, Map<PulseType, Long>> { val initialModule = modules["broadcaster"]!! val initialPulse = Pulse(PulseType.LOW, "broadcaster") val queue = ArrayDeque<Pair<Module?, Pulse>>(listOf(initialModule to initialPulse)) val pulseTypeMap = mutableMapOf<String, MutableMap<PulseType, Long>>() pulseTypeMap["broadcaster"] = mutableMapOf(PulseType.LOW to 1L) while (queue.isNotEmpty()) { val (module, pulse) = queue.removeFirst() val destinations = module?.process(pulse) ?: emptyList() destinations.forEach { (destination, pulse) -> val moduleMap = pulseTypeMap.getOrPut(destination) { mutableMapOf() } moduleMap[pulse.type] = moduleMap.getOrDefault(pulse.type, 0) + 1 } queue.addAll(destinations.map { (destination, pulse) -> modules[destination] to pulse }) } return pulseTypeMap } private fun numberOfButtonPushesUntilLowState(modules: Map<String, Module>, key: String): Long { val initialModule = modules["broadcaster"]!! val initialPulse = Pulse(PulseType.LOW, "broadcaster") val queue = ArrayDeque<Pair<Module?, Pulse>>(listOf(initialModule to initialPulse)) var count = 1L // We know the input to the target is a cond, so we can just find when the inputs to the cond are all high val targetInput = modules.values.find { it.destinations.contains(key) } ?: throw IllegalStateException("Invalid input: $key") val inputsOfTargetInput = targetInput.inputs.toSet() val countWhenHighPulse = mutableMapOf<String, Long>() while (true) { if (countWhenHighPulse.size == inputsOfTargetInput.size) { return countWhenHighPulse.values.reduce(Long::times) } val (module, pulse) = queue.removeFirst() val destinations = module?.process(pulse) ?: emptyList() val destinationsToPulses = destinations.map { (destination, pulse) -> modules[destination] to pulse } destinationsToPulses.forEach { (desination, pulse) -> if ((desination?.id ?: "") == targetInput.id) if (pulse.type == PulseType.HIGH && !countWhenHighPulse.containsKey(module?.id)) { countWhenHighPulse[module!!.id] = count } } queue.addAll(destinationsToPulses) if (queue.isEmpty()) { queue.add(initialModule to initialPulse) count++ } } } fun part2(input: List<String>): String { val modules = input.map { Module.parse(it) }.associateBy { it.id } return numberOfButtonPushesUntilLowState(modules, "rx").toString() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
6,052
kotlin-kringle
Apache License 2.0
src/Day06.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
fun main() { fun getIndexOfGroup(input: String, groupSize: Int): Int { val buffer = HashSet<Char>() var result = -1 run breaking@{ (groupSize-1 until input.length).forEach { index -> buffer.clear() (index - groupSize + 1..index).forEach { buffer.add(input[it]) } if (buffer.size == groupSize) { result = index + 1 return@breaking } } } return result } fun part1(input: List<String>): Int { return getIndexOfGroup(input[0], 4) } fun part2(input: List<String>): Int { return getIndexOfGroup(input[0], 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a638356cda864b9e1799d72fa07d3482a5f2128e
990
aoc-2022
Apache License 2.0
src/iii_conventions/MyDate.kt
robyp1
132,624,740
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int = when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth -other.dayOfMonth } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)/*todoTask27()*/ enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> { override fun contains(value: MyDate): Boolean = value >= start && value <= endInclusive override fun iterator(): Iterator<MyDate> = DateIterator(this) } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var current : MyDate = dateRange.start override fun hasNext(): Boolean = current <= dateRange.endInclusive override fun next(): MyDate { val result = current current = current.nextDay() return result } } class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int) //per la somma (+) tra Mydate e timeInterval operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval, 1) //per il prodotto (*) tra TimeIntervals e interi (costanti es: DAY * 2) operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number) //per la somma (+) tra MyDate e RepeatedTimeInterval (es : x + DAY * 2, dove x : Mytdate) operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) = addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
0
Kotlin
0
0
c792e7a4bca6fcb796332c69b68653fce0037a66
1,714
kotlin-koans-resolutions
MIT License
ParallelProgramming/possible-executions-analysis/src/PossibleExecutionsVerifier.kt
ShuffleZZZ
128,576,289
false
null
import java.io.* import java.util.* const val SOLUTION_FILE_NAME = "solution.txt" val STATE_REGEX = Regex("\\[P([1-4]),Q([1-4]),([01]),([01])]") fun main() { val transitions = mutableSetOf<Transition>() File(SOLUTION_FILE_NAME).readLines().forEachIndexed { index, line -> val trim = line.substringBefore('#').trim() try { if (trim.isNotEmpty()) { val t = parseTransition(trim) require(transitions.add(t)) { "Duplicate transition $t" } } } catch (e: IllegalArgumentException) { error("At $SOLUTION_FILE_NAME:${index + 1}: ${e.message}") } } val states = transitions .groupBy({ it.from }, { it.to }) .mapValues { it.value.toSet() } .toMutableMap() for (s in states.values.flatten()) { if (s !in states) states[s] = emptySet() } val initial = State(1, 1, 0, 0) // check initial state require(initial in states) { "Must contain transition from initial state $initial" } // check complete transitions out of each state for ((from, tos) in states) { val expected = mutableSetOf<State>() from.moveP().let { expected += it } from.moveQ()?.let { expected += it } require(expected.size == tos.size) { "Unexpected number of transitions (${tos.size}) from state $from" } for (e in expected) { require(e in tos) { "Missing transition from state $from" } } } // check reachability of all states val queue = ArrayDeque<State>() val reached = HashSet<State>() fun mark(state: State) { if (reached.add(state)) queue += state } mark(initial) while (!queue.isEmpty()) { val from = queue.removeFirst() for (to in states[from]!!) mark(to) } for (state in states.keys) { require(state in reached) { "State $state in never reached from the initial state" } } } data class State(val p: Int, val q: Int, val a: Int, val b: Int) { override fun toString(): String = "[P$p,Q$q,$a,$b]" fun moveP(): State = when(p) { // while true: 1 -> copy(p = 2, a = 1) // 1: a = 1 2 -> if (b != 0) this else copy(p = 3) // 2: while b != 0: pass // do nothing 3 -> copy(p = 4) // 3: pass // critical section, do nothing 4 -> copy(p = 1, a = 0) // 4: a = 0 else -> error("Invalid state $this") } fun moveQ(): State? = when(q) { // while true: 1 -> copy(q = 2, b = 1) // 1: b = 1 2 -> if (a == 0) copy(q = 4) else copy(q = 3) // 2: if a == 0: break // to line 4 3 -> copy(q = 1, b = 0) // 3: b = 0 4 -> null // 4: stop // outside of loop else -> error("Invalid state $this") } } data class Transition(val from: State, val to: State) { override fun toString(): String = "$from -> $to" } fun parseTransition(s: String): Transition { val i = s.indexOf("->") require(i > 0) { "Must contain transition with '->' separator" } return Transition(parseState(s.substring(0, i)), parseState(s.substring(i + 2))) } fun parseState(s: String): State { val match = STATE_REGEX.matchEntire(s.trim()) require(match != null) { "State does not match a specified format $STATE_REGEX" } val g = match.groupValues.drop(1).map { it.toInt() } return State(g[0], g[1], g[2], g[3]) }
103
Jupyter Notebook
2
10
29db54d96afef0558550471c58f695c962e1f747
3,569
ITMO
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/OpenLock.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 752. Open the Lock * @see <a href="https://leetcode.com/problems/open-the-lock/">Source</a> */ fun interface OpenLock { fun openLock(deadEnds: Array<String>, target: String): Int } class OpenLockBFS : OpenLock { private var begin: MutableSet<String> = HashSet<String>().apply { add(START_LOCK_POSITION) } private var end: MutableSet<String> = HashSet() override fun openLock(deadEnds: Array<String>, target: String): Int { val deads: MutableSet<String> = HashSet(deadEnds.toList()) end.add(target) var level = 0 var temp: MutableSet<String> while (begin.isNotEmpty() && end.isNotEmpty()) { if (begin.size > end.size) { temp = begin begin = end end = temp } temp = HashSet() for (s in begin) { if (end.contains(s)) { return level } if (deads.contains(s)) { continue } deads.add(s) val sb = StringBuilder(s) for (i in 0 until LOCK_SIZE) { val c = sb[i] val s1 = sb.substring(0, i) + (if (c == '9') 0 else c - '0' + 1) + sb.substring( i + 1, ) val s2 = sb.substring(0, i) + (if (c == '0') 9 else c - '0' - 1) + sb.substring( i + 1, ) if (!deads.contains(s1)) { temp.add(s1) } if (!deads.contains(s2)) { temp.add(s2) } } } level++ begin = temp } return DEFAULT_RESULT } companion object { private const val START_LOCK_POSITION = "0000" private const val LOCK_SIZE = 4 private const val DEFAULT_RESULT = -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,656
kotlab
Apache License 2.0
app/src/main/kotlin/com/github/ilikeyourhat/kudoku/solving/deduction/algorithm/RegionIntersectionAlgorithm.kt
ILikeYourHat
139,063,649
false
{"Kotlin": 166134}
package com.github.ilikeyourhat.kudoku.solving.deduction.algorithm import com.github.ilikeyourhat.kudoku.model.Region import com.github.ilikeyourhat.kudoku.model.hint.SudokuHintGrid import com.github.ilikeyourhat.kudoku.solving.deduction.combinations.CollectionCombinator class RegionIntersectionAlgorithm( regions: List<Region>, possibilities: SudokuHintGrid ) : DeductionAlgorithm(regions, possibilities) { class Factory : DeductionAlgorithm.Factory { override fun instance(regions: List<Region>, possibilities: SudokuHintGrid): RegionIntersectionAlgorithm { return RegionIntersectionAlgorithm(regions, possibilities) } } override fun solve(): Boolean { var changed = false val combinator = CollectionCombinator(2) combinator.iterate(regions) { values: List<Region> -> val first = values[0] val second = values[1] changed = changed or solve(first, second) } return changed } override fun solve(region: Region): Boolean { throw UnsupportedOperationException("This algorithm operates on two regions") } private fun solve(region1: Region, region2: Region): Boolean { var changed = false val intersection = region1.intersect(region2) if (!intersection.isEmpty()) { val regionSub1 = region1.subtract(intersection) val regionSub2 = region2.subtract(intersection) changed = changed or solve(regionSub1, regionSub2, intersection) } return changed } private fun solve(region1: Region, region2: Region, intersection: Region): Boolean { var changed = false val hintsFromIntersection = possibilities.forRegion(intersection) val hintsFromRegion1 = possibilities.forRegion(region1) val hintsFromRegion2 = possibilities.forRegion(region2) for (value in hintsFromIntersection) { if (hintsFromRegion1.contains(value) && !hintsFromRegion2.contains(value)) { if (possibilities.remove(region1, value)) { changed = true } } else if (!hintsFromRegion1.contains(value) && hintsFromRegion2.contains(value)) { if (possibilities.remove(region2, value)) { changed = true } } } return changed } }
1
Kotlin
0
0
b234b2de2edb753844c88ea3cd573444675fc1cf
2,410
Kudoku
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/NQueens.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 51. N 皇后 * * n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 * 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。 * * 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。 * * 示例: * * 输入:4 * 输出:[ * [".Q..", // 解法 1 * "...Q", * "Q...", * "..Q."], * * ["..Q.", // 解法 2 * "Q...", * "...Q", * ".Q.."] * ] * 解释: 4 皇后问题存在两个不同的解法。 * * 提示: * * 皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。 */ class NQueens { companion object { @JvmStatic fun main(args: Array<String>) { NQueens().solution(8).forEach { it.forEach { sub -> println("$sub,") } println() } } } fun solution(n: Int): List<List<String>> { val result = mutableListOf<List<String>>() val queens = IntArray(n) calQueens(0, n, queens, result) return result } /** * O(n!) */ private fun calQueens(row: Int, n: Int, queens: IntArray, result: MutableList<List<String>>) { if (row == n) { printlnQueens(n, queens, result) return } // 每一行都有n种放置方法 repeat(n) { if (isOk(row, it, n, queens)) { // 记入放置的位置 queens[row] = it // 下一行 calQueens(row + 1, n, queens, result) } } } /** * 判断是否符合放置规则 */ private fun isOk(row: Int, column: Int, n: Int, queens: IntArray): Boolean { var leftUp = column - 1 var rightUp = column + 1 var up = row - 1 // 与之前的行进行比较,判断是否符合规则 while (up >= 0) { // 之前的行在当前列上是否已经存在 if (queens[up] == column) return false // 左对角线是否存在 if (leftUp >= 0 && queens[up] == leftUp) return false // 右对角线是否存在 if (rightUp < n && queens[up] == rightUp) return false up-- leftUp-- rightUp++ } return true } private fun printlnQueens(n: Int, queens: IntArray, result: MutableList<List<String>>) { val subResult = mutableListOf<String>() var i = 0 while (i < n) { val sub = CharArray(n) { '.' } var j = 0 while (j < n) { if (queens[i] == j) { sub[j] = 'Q' } j++ } subResult.add(String(sub)) i++ } result.add(subResult) } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
3,046
daily_algorithm
Apache License 2.0
src/Day03.kt
Arclights
574,085,358
false
{"Kotlin": 11490}
fun main() { fun itemValue(item: Char): Int = when { item >= 'a' -> item.code - 96 else -> item.code - 38 } fun part1(input: List<String>) = input .map { line -> line.take(line.length / 2) to line.drop(line.length / 2) } .flatMap { (compartment1, compartment2) -> compartment1.toSet().intersect(compartment2.toSet()) } .map(::itemValue) .sum() fun part2(input: List<String>) = input .asSequence() .windowed(3, 3) .map { grouping -> grouping[0].toSet().intersect(grouping[1].toSet()).intersect(grouping[2].toSet()) } .map { it.first() } .map(::itemValue) .sum() val testInput = readInput("Day03_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
121a81ba82ba0d921bd1b689241ffa8727bc806e
871
advent_of_code_2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDiffInBST.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 783. Minimum Distance Between BST Nodes * @see <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/">Source</a> */ fun interface MinDiffInBST { fun minDiffInBST(root: TreeNode?): Int } class MinDiffInBSTInorder : MinDiffInBST { private var previous: TreeNode? = null private var min = Int.MAX_VALUE override fun minDiffInBST(root: TreeNode?): Int { inOrder(root) return min } private fun inOrder(root: TreeNode?) { if (root == null) return inOrder(root.left) previous?.let { prev -> min = min(min, root.value - prev.value) } previous = root inOrder(root.right) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,369
kotlab
Apache License 2.0
app/src/main/kotlin/kotlinadventofcode/2023/2023-04.kt
pragmaticpandy
356,481,847
false
{"Kotlin": 1003522, "Shell": 219}
// Originally generated by the template in CodeDAO package kotlinadventofcode.`2023` import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.grammar.* import com.github.h0tk3y.betterParse.lexer.* import kotlinadventofcode.Day import kotlin.math.pow class `2023-04` : Day { override fun runPartOneNoUI(input: String): String { return parseCards(input).sumOf { it.points }.toString() } override fun runPartTwoNoUI(input: String): String { val cards = parseCards(input) val cardsById = cards.associateBy { it.cardNum } val numCardsById = cards.associateTo(mutableMapOf()) { it.cardNum to 1 } for (cardId in 1..cards.maxOf { it.cardNum }) { repeat(numCardsById[cardId]!!) { for (i in 1..cardsById[cardId]!!.myWinningNums.size) { numCardsById[cardId + i]?.let { numCardsById[cardId + i] = it + 1 } } } } return numCardsById.values.sum().toString() } private data class Card(val cardNum: Int, val winningNums: List<Int>, val myNums: List<Int>) { val myWinningNums = winningNums.intersect(myNums.toSet()).toList() val points = if (myWinningNums.isEmpty()) 0 else 2.0.pow((myWinningNums.size - 1).toDouble()).toInt() } private fun parseCards(input: String): List<Card> { val grammar = object : Grammar<List<Card>>() { // tokens val newlineLit by literalToken("\n") val pipeLit by literalToken("|") val colonLit by literalToken(":") val cardLit by literalToken("Card") val spaceLit by literalToken(" ") val positiveIntRegex by regexToken("\\d+") // parsers val positiveInt by positiveIntRegex use { text.toInt() } val spaces = zeroOrMore(spaceLit) val nums by separatedTerms(positiveInt, spaces) val card by (skip(cardLit) and skip(spaces) and positiveInt and skip(colonLit) and skip(spaces) and nums and skip(spaces) and skip(pipeLit) and skip(spaces) and nums) map { Card(it.t1, it.t2, it.t3) }; override val rootParser by separatedTerms(card, newlineLit) } return grammar.parseToEnd(input) } override val defaultInput = """Card 1: 58 68 1 21 88 37 66 61 23 25 | 63 95 45 43 79 64 29 87 8 70 84 34 91 67 3 76 27 24 28 62 13 54 19 93 7 Card 2: 4 60 28 7 83 59 90 67 95 87 | 7 67 77 13 11 19 54 3 95 25 1 87 4 80 64 60 8 94 53 90 59 83 31 70 28 Card 3: 88 52 39 57 13 85 87 9 61 40 | 90 1 5 9 43 61 10 12 98 40 97 44 11 6 57 80 30 85 41 52 13 88 39 87 93 Card 4: 24 64 90 79 2 83 62 77 22 25 | 64 83 37 36 42 79 24 78 5 76 41 71 43 99 62 93 57 55 90 18 73 22 92 25 2 Card 5: 25 65 86 11 26 40 27 9 61 51 | 54 10 23 32 97 59 55 31 7 49 79 63 98 1 18 29 42 66 38 74 46 88 20 6 39 Card 6: 17 70 23 48 8 41 51 1 13 36 | 70 42 13 53 89 59 18 36 6 26 17 31 9 51 15 63 2 1 41 48 10 34 33 55 44 Card 7: 51 64 21 49 30 93 60 4 10 44 | 78 40 24 6 4 51 60 52 65 21 74 2 31 80 13 75 16 10 56 44 33 3 19 55 93 Card 8: 67 95 26 91 83 69 2 77 37 70 | 58 64 83 41 69 63 11 30 73 28 75 87 76 15 6 2 10 51 20 47 82 48 61 46 53 Card 9: 21 26 37 87 88 98 50 34 43 39 | 29 77 18 78 36 92 5 7 93 62 37 74 63 10 3 23 66 45 12 8 46 2 81 75 69 Card 10: 30 26 86 52 11 13 57 14 41 19 | 13 52 19 24 86 26 83 30 22 68 62 85 98 99 14 41 18 27 8 70 23 11 38 76 77 Card 11: 58 31 80 77 57 26 76 49 48 67 | 27 78 56 43 5 87 44 32 20 86 81 34 17 83 59 9 52 73 75 72 36 21 14 29 39 Card 12: 40 39 76 89 62 36 10 81 35 46 | 9 83 20 58 52 14 1 25 27 10 60 39 47 72 86 12 80 88 8 56 87 64 65 28 16 Card 13: 39 95 10 34 15 42 26 70 67 32 | 11 78 96 97 66 16 31 99 49 51 30 54 24 45 59 91 88 4 52 85 58 90 41 87 84 Card 14: 76 21 73 18 89 11 39 57 55 95 | 54 23 62 85 17 36 70 50 30 63 81 79 12 2 40 93 41 37 27 56 84 1 68 66 86 Card 15: 35 40 13 30 75 31 21 58 66 95 | 41 89 99 21 27 18 1 70 10 12 95 23 61 35 40 98 24 42 64 81 78 11 26 28 96 Card 16: 92 3 14 52 37 18 63 71 49 57 | 36 60 45 12 59 73 89 40 70 78 68 95 19 27 86 39 4 67 23 91 11 84 72 21 14 Card 17: 29 13 22 95 64 12 83 75 7 54 | 55 87 21 99 52 11 86 69 13 27 47 24 26 48 14 74 45 59 5 68 62 31 63 88 90 Card 18: 28 52 13 85 21 16 34 20 73 27 | 17 50 10 82 62 71 45 28 18 60 88 19 11 1 25 27 67 54 4 35 68 39 36 20 87 Card 19: 92 24 77 63 8 49 22 68 51 38 | 53 18 46 13 23 17 76 31 98 54 45 6 39 7 41 10 55 72 20 66 90 60 30 21 71 Card 20: 21 27 1 39 12 99 64 68 74 82 | 67 72 16 80 23 97 75 36 57 8 90 40 14 71 93 65 18 51 4 79 17 55 48 49 10 Card 21: 13 62 64 60 23 58 27 83 31 59 | 74 38 6 3 57 16 89 50 2 82 44 17 76 56 81 79 15 53 47 21 86 68 34 73 84 Card 22: 91 58 48 40 61 27 51 38 65 37 | 38 46 5 60 93 61 51 72 48 45 64 37 71 2 27 20 56 17 40 66 58 57 86 91 65 Card 23: 49 98 13 3 61 66 16 46 22 44 | 58 26 35 75 96 64 18 9 92 45 94 67 49 89 84 20 48 39 43 38 55 90 6 69 30 Card 24: 34 17 23 28 60 33 82 18 8 7 | 52 68 73 88 94 77 6 55 87 79 63 84 74 4 70 18 38 60 82 31 51 58 89 36 61 Card 25: 71 88 43 21 2 35 4 61 29 70 | 75 11 15 19 54 17 28 69 62 37 56 99 10 41 39 73 66 47 45 30 93 16 33 8 76 Card 26: 18 1 31 56 69 16 12 52 23 14 | 26 60 62 12 7 2 69 78 3 57 73 25 52 1 61 27 16 56 53 47 14 44 90 54 55 Card 27: 14 38 31 88 77 23 80 69 15 66 | 52 98 21 29 75 77 14 91 93 16 5 90 19 69 74 11 7 59 58 54 2 38 23 39 15 Card 28: 33 79 13 31 76 36 43 80 15 87 | 83 73 34 62 22 58 13 87 72 36 78 39 80 93 45 43 31 59 1 40 76 15 74 48 4 Card 29: 74 29 34 52 51 87 40 53 31 91 | 72 68 20 84 34 15 74 50 1 80 66 9 73 30 65 58 83 40 92 91 59 87 64 31 52 Card 30: 57 90 83 48 36 46 60 41 7 80 | 18 11 81 15 36 10 52 59 9 44 92 21 37 83 89 61 94 12 13 60 69 68 28 5 16 Card 31: 48 8 60 22 99 96 31 51 80 46 | 7 48 9 25 55 60 67 41 5 93 1 32 45 85 43 47 12 88 87 98 75 73 31 72 56 Card 32: 34 49 54 28 1 98 39 57 55 30 | 28 92 99 36 52 12 14 58 98 65 90 22 39 94 49 19 53 82 41 79 56 26 29 5 27 Card 33: 48 42 54 81 80 52 91 64 23 45 | 32 62 56 67 1 6 90 76 40 69 64 94 2 15 33 46 34 25 8 99 18 88 66 7 26 Card 34: 88 26 34 35 32 83 21 12 65 50 | 75 52 45 44 69 59 86 66 37 29 6 54 98 55 40 9 85 89 39 71 90 51 77 82 38 Card 35: 39 93 90 75 58 49 19 24 51 52 | 88 25 53 34 13 16 83 74 18 57 20 64 85 75 1 40 38 8 3 71 81 67 27 48 15 Card 36: 7 10 51 22 54 64 15 3 89 91 | 73 97 20 60 29 31 45 88 70 49 17 94 38 47 53 12 96 55 39 87 26 57 48 85 65 Card 37: 90 23 83 61 6 42 7 98 13 20 | 72 61 30 75 49 43 31 87 98 60 29 46 20 7 24 6 21 58 15 11 23 52 90 13 83 Card 38: 35 90 14 45 27 74 26 21 95 69 | 6 49 89 1 56 23 68 48 69 38 16 75 39 37 51 91 78 77 28 17 9 62 4 80 5 Card 39: 65 11 79 74 26 9 36 29 85 27 | 50 81 72 9 2 33 58 51 85 65 57 70 26 84 74 12 5 29 11 27 59 79 10 36 46 Card 40: 23 55 12 93 83 51 3 76 81 92 | 33 12 42 44 25 82 91 10 80 38 83 16 5 26 34 86 22 31 21 39 19 55 62 7 88 Card 41: 92 3 30 98 74 27 26 86 13 85 | 65 89 24 26 27 57 70 88 79 54 15 83 18 7 95 3 31 66 30 62 36 85 58 61 97 Card 42: 16 58 48 14 65 2 23 43 5 8 | 51 98 31 40 77 74 83 15 45 59 17 32 43 72 70 10 57 47 28 64 26 82 75 14 19 Card 43: 55 49 28 94 4 42 14 52 78 81 | 83 78 59 90 55 10 69 72 36 19 49 22 39 14 81 99 65 67 37 28 66 53 5 51 80 Card 44: 82 37 30 40 36 7 32 71 25 66 | 56 75 86 55 95 25 84 26 47 38 79 98 83 9 17 6 68 40 10 91 96 11 31 61 90 Card 45: 45 9 61 48 42 82 97 89 99 44 | 67 81 30 43 68 5 3 44 94 29 93 73 19 96 18 62 60 53 95 88 10 22 33 83 28 Card 46: 67 69 28 84 3 63 36 24 64 49 | 2 10 81 77 20 8 9 14 39 35 96 4 87 16 68 82 65 42 92 97 58 37 45 38 55 Card 47: 38 69 31 67 61 86 65 35 66 89 | 65 67 22 59 60 37 25 61 26 89 11 88 42 1 36 99 13 53 34 98 32 49 50 63 14 Card 48: 9 18 95 17 51 24 22 65 37 34 | 86 20 5 21 82 64 70 29 25 80 59 90 94 66 60 93 75 12 95 43 97 23 47 22 73 Card 49: 87 88 30 25 68 40 52 43 48 5 | 98 95 9 15 13 18 84 59 71 99 49 21 30 89 55 8 16 57 20 94 1 74 70 87 78 Card 50: 21 42 66 50 7 77 88 90 40 36 | 52 55 99 45 67 15 41 38 72 79 53 20 91 73 75 25 1 22 44 48 36 33 63 97 94 Card 51: 86 9 90 51 98 24 4 60 11 62 | 29 67 40 70 3 45 38 58 96 33 93 42 44 5 57 85 94 19 56 54 53 68 2 30 78 Card 52: 38 35 46 24 56 48 62 79 64 73 | 88 97 64 48 90 38 5 6 17 24 62 72 44 83 78 35 96 14 73 11 79 55 56 46 93 Card 53: 17 29 59 50 80 21 67 97 53 27 | 53 28 27 17 8 92 48 69 11 73 70 20 67 93 80 75 94 34 90 44 78 77 50 96 97 Card 54: 36 11 67 66 22 86 99 52 37 84 | 86 1 97 63 82 96 45 32 70 15 34 80 17 28 20 56 94 78 35 24 59 48 13 95 55 Card 55: 91 70 23 37 18 97 24 14 77 61 | 46 74 67 18 25 77 60 59 70 24 4 44 61 23 31 91 55 76 40 14 81 9 97 37 45 Card 56: 84 36 95 62 29 52 12 7 91 26 | 29 89 24 7 23 49 84 25 36 95 72 12 65 75 52 90 62 37 8 60 38 91 76 26 16 Card 57: 51 59 19 45 15 57 73 18 95 56 | 76 60 43 52 15 69 53 20 59 57 72 9 51 46 14 64 73 37 56 35 95 19 18 42 45 Card 58: 42 22 49 26 32 28 44 80 15 23 | 39 95 20 68 97 37 22 7 71 51 28 24 15 58 26 34 11 43 18 6 44 31 98 48 81 Card 59: 54 57 37 58 46 63 74 8 64 9 | 69 23 53 67 26 10 80 79 93 17 35 41 65 90 5 38 66 29 2 42 43 97 13 99 28 Card 60: 44 5 38 90 10 29 40 36 92 39 | 97 41 7 91 25 43 30 10 89 3 54 5 13 11 96 61 36 55 86 1 57 90 74 38 46 Card 61: 43 66 70 36 39 16 67 35 32 94 | 16 54 90 35 70 84 57 80 29 92 81 13 40 12 88 94 36 11 41 14 67 53 27 66 32 Card 62: 18 9 3 71 40 48 20 99 50 88 | 73 61 19 25 96 44 51 46 39 27 55 28 24 33 93 14 95 70 12 41 10 18 88 86 60 Card 63: 16 61 27 91 80 34 2 32 1 10 | 73 25 78 42 94 1 12 76 80 82 16 86 38 91 52 55 90 77 99 70 30 19 32 37 56 Card 64: 21 68 13 22 66 8 89 50 70 32 | 46 22 32 15 70 50 80 89 87 45 68 13 79 44 21 66 90 55 28 11 31 36 4 24 8 Card 65: 95 84 36 24 5 96 63 83 12 33 | 93 22 41 72 30 14 4 39 69 47 34 51 52 65 80 60 42 23 1 86 31 79 43 96 45 Card 66: 49 28 20 18 55 69 72 23 25 2 | 84 44 70 29 72 15 28 14 64 5 46 16 33 93 9 43 42 45 65 86 90 67 47 40 58 Card 67: 90 46 11 67 40 48 73 44 72 92 | 26 67 79 27 30 48 8 57 35 42 18 40 22 20 43 98 23 84 73 38 80 11 24 3 97 Card 68: 83 42 25 20 2 16 51 72 37 14 | 58 91 12 86 43 51 23 52 99 84 77 83 97 20 44 69 34 76 39 42 60 2 21 8 56 Card 69: 93 54 79 66 95 33 36 30 64 46 | 10 29 93 95 33 31 53 28 57 22 30 59 79 27 51 71 50 3 62 78 5 92 60 54 55 Card 70: 44 71 60 47 65 72 45 97 38 32 | 34 32 22 97 74 83 33 86 94 44 5 98 75 63 13 55 93 84 72 91 29 99 76 43 47 Card 71: 17 74 82 50 63 80 96 66 9 40 | 88 68 83 21 89 27 47 4 18 77 65 11 24 30 56 8 52 43 12 57 85 15 13 19 86 Card 72: 58 73 45 25 50 28 35 23 17 53 | 21 88 74 80 43 82 7 9 46 57 51 77 61 85 52 39 75 5 19 90 83 48 2 3 84 Card 73: 70 33 42 60 41 72 47 49 98 2 | 66 63 51 39 36 21 5 29 7 8 96 81 86 99 48 19 67 78 17 91 24 84 30 47 12 Card 74: 68 50 89 25 56 97 13 42 61 83 | 37 79 74 8 44 29 21 58 66 40 49 17 51 34 73 2 84 14 10 4 47 85 98 46 90 Card 75: 59 28 61 9 12 43 97 32 73 4 | 77 80 81 79 60 66 22 45 75 95 53 27 19 82 7 1 74 67 11 29 93 24 88 85 5 Card 76: 47 40 82 79 27 84 66 80 20 25 | 25 23 27 75 89 67 82 5 30 62 37 81 15 19 40 84 51 80 47 77 66 90 20 44 79 Card 77: 81 78 95 42 9 74 15 88 77 19 | 5 96 75 33 56 27 12 19 77 22 44 9 99 30 18 88 42 79 78 45 15 98 81 74 95 Card 78: 4 54 60 59 57 12 23 47 27 16 | 43 34 64 23 35 32 37 94 65 86 74 13 18 30 36 66 68 99 31 92 17 93 28 2 11 Card 79: 27 78 97 35 30 95 85 87 76 2 | 84 95 76 2 97 30 87 64 37 27 18 44 93 91 79 35 85 40 41 53 3 78 48 88 67 Card 80: 70 95 13 98 35 73 17 63 93 59 | 3 32 2 12 48 15 70 40 78 83 57 26 19 38 92 42 71 67 85 25 76 9 93 60 59 Card 81: 50 64 63 66 86 89 4 24 17 82 | 66 82 17 52 35 90 64 63 79 30 40 95 4 50 75 98 99 89 8 83 81 21 24 86 46 Card 82: 59 15 68 21 71 72 29 78 82 89 | 34 63 83 66 54 79 16 57 73 22 93 58 95 41 37 44 86 5 67 77 11 8 27 24 90 Card 83: 31 34 55 60 81 58 95 56 70 67 | 67 70 17 31 7 81 63 56 58 34 66 47 74 10 95 97 64 94 24 88 55 13 92 1 60 Card 84: 41 91 61 25 13 49 15 19 90 72 | 66 7 63 5 20 56 94 42 19 81 74 24 45 82 26 76 86 41 72 57 27 46 53 91 95 Card 85: 42 96 36 85 75 10 80 25 32 78 | 24 80 99 34 78 85 75 44 32 57 97 74 40 25 36 96 48 91 53 10 29 81 50 2 42 Card 86: 46 74 7 45 3 99 96 15 94 92 | 9 40 81 30 7 87 18 4 80 24 62 49 60 36 93 52 74 14 23 90 79 25 6 44 3 Card 87: 47 80 14 95 55 91 65 26 1 64 | 18 8 5 29 3 92 35 62 52 43 41 24 14 40 93 50 4 97 98 59 6 69 77 86 46 Card 88: 16 43 7 37 89 52 38 33 65 88 | 59 51 97 16 89 57 96 68 37 62 43 63 94 12 91 87 88 74 17 65 15 52 14 3 42 Card 89: 46 55 91 86 69 56 57 33 74 80 | 2 6 50 88 62 99 13 14 57 58 69 55 78 80 12 85 72 91 26 33 93 29 96 76 3 Card 90: 99 69 83 87 91 27 20 21 42 45 | 49 87 39 65 52 69 42 89 1 47 24 95 29 38 91 33 27 2 51 64 45 21 20 99 83 Card 91: 56 87 54 79 28 2 39 96 92 3 | 60 74 33 97 45 20 77 68 64 58 61 26 29 71 44 1 5 34 81 62 55 54 43 75 57 Card 92: 90 37 51 88 73 1 87 33 38 54 | 23 19 90 1 83 72 86 84 96 33 74 25 54 48 61 15 16 89 17 37 87 32 62 51 38 Card 93: 14 19 9 10 88 30 34 28 92 60 | 45 75 35 8 31 37 61 59 76 63 22 34 14 85 24 4 62 60 77 79 74 19 50 17 33 Card 94: 39 44 82 65 12 60 75 18 59 14 | 66 71 83 27 40 28 91 23 76 26 25 35 38 63 4 3 64 15 86 49 32 22 89 6 13 Card 95: 70 55 42 10 17 96 8 25 99 74 | 67 97 34 95 98 52 44 63 39 53 21 73 45 54 8 24 75 18 1 11 10 25 88 51 93 Card 96: 81 61 72 29 10 62 82 43 38 98 | 19 69 17 58 83 66 76 54 95 41 44 50 48 99 65 60 15 64 73 62 61 84 98 13 14 Card 97: 58 76 38 77 75 36 62 88 43 32 | 19 27 87 30 97 89 68 5 99 17 86 32 34 11 40 20 10 69 48 15 75 13 77 4 91 Card 98: 90 65 75 72 26 49 89 13 82 44 | 74 99 9 94 45 31 21 50 67 32 95 56 23 2 1 36 22 14 83 91 51 25 81 88 58 Card 99: 43 26 7 1 18 21 58 38 92 46 | 89 14 29 77 73 71 15 33 96 95 84 65 44 49 11 9 42 19 57 75 39 2 56 83 32 Card 100: 12 30 88 14 37 34 89 7 94 90 | 44 26 53 70 36 28 48 74 83 23 87 45 18 19 69 98 64 78 86 1 68 31 92 24 65 Card 101: 79 23 24 92 88 59 11 64 84 89 | 51 23 34 73 7 89 41 68 92 37 64 3 26 44 87 91 95 1 55 59 62 11 43 9 22 Card 102: 91 50 89 29 58 4 15 76 70 62 | 76 79 42 87 63 15 4 68 16 52 66 91 7 50 62 44 82 58 89 70 8 32 75 71 29 Card 103: 25 22 54 85 93 77 37 86 39 62 | 36 17 8 73 79 97 55 15 11 38 94 51 61 62 65 21 46 35 20 53 77 81 93 64 57 Card 104: 56 86 13 35 92 11 22 16 46 20 | 53 38 13 22 56 35 20 23 18 98 29 92 97 59 86 46 74 16 25 63 30 11 12 7 27 Card 105: 84 32 51 40 79 52 91 56 38 74 | 70 56 14 36 61 45 82 9 95 20 97 27 63 44 65 28 49 15 60 12 81 22 39 46 31 Card 106: 42 3 75 14 72 32 1 41 66 40 | 26 65 8 47 55 57 90 48 81 45 64 17 93 30 61 95 80 58 97 49 23 88 11 77 69 Card 107: 88 67 38 43 63 22 54 33 47 53 | 88 53 42 45 41 43 54 67 71 66 1 28 93 69 22 14 11 33 46 63 38 47 95 89 13 Card 108: 73 74 78 39 76 8 17 50 30 70 | 59 39 8 63 57 73 87 30 51 84 17 7 78 67 1 54 5 72 99 40 76 77 89 83 95 Card 109: 76 26 78 74 22 87 34 79 60 15 | 24 80 91 79 66 98 2 92 13 76 84 34 15 68 17 60 27 54 32 78 74 41 89 22 61 Card 110: 56 18 35 89 98 23 30 22 53 92 | 44 41 70 6 17 4 86 34 83 66 12 28 47 32 33 91 16 93 2 49 11 22 99 25 29 Card 111: 45 53 54 99 59 15 86 98 55 44 | 5 95 54 12 9 32 26 2 89 93 74 44 3 46 7 57 17 75 53 22 51 58 24 10 41 Card 112: 26 37 4 57 84 50 70 94 66 10 | 66 89 3 60 51 23 34 30 91 61 13 45 10 38 39 18 92 72 83 42 9 99 41 7 95 Card 113: 49 67 76 86 83 78 54 87 36 66 | 57 15 9 64 39 54 33 77 55 40 44 30 16 53 12 58 18 11 7 70 76 32 82 73 42 Card 114: 66 38 20 8 31 29 43 62 85 19 | 26 23 68 91 94 95 70 9 21 43 6 35 4 8 74 52 47 99 2 53 86 93 97 59 34 Card 115: 3 88 71 98 25 33 40 97 46 75 | 72 1 22 13 49 95 59 31 96 9 54 40 65 94 53 56 67 79 89 63 52 75 57 90 10 Card 116: 63 39 94 15 72 47 20 23 34 99 | 8 4 78 82 11 50 40 84 22 60 19 21 57 47 77 79 45 27 93 96 29 85 6 33 36 Card 117: 88 6 47 71 98 39 69 79 67 15 | 28 9 24 53 26 2 49 64 61 32 7 54 33 68 87 37 36 50 83 5 52 90 48 51 43 Card 118: 22 21 33 59 49 93 84 60 17 45 | 22 50 60 28 26 74 61 4 6 89 81 12 84 45 97 56 2 59 42 83 49 86 5 94 30 Card 119: 10 23 38 22 37 25 28 34 58 50 | 79 93 14 34 27 37 65 47 1 41 84 23 78 13 28 10 99 25 12 58 50 61 51 22 38 Card 120: 58 68 13 39 51 84 55 99 10 14 | 23 56 3 27 50 64 55 32 86 62 67 47 78 73 44 24 97 70 49 20 43 96 30 72 5 Card 121: 72 38 96 86 5 15 19 49 6 90 | 34 93 49 37 21 58 86 94 15 59 38 82 28 72 33 96 51 95 99 6 2 47 24 74 69 Card 122: 30 29 36 6 65 46 28 19 13 50 | 95 1 65 44 79 5 12 88 75 62 66 34 6 24 68 30 31 89 13 64 33 52 96 43 2 Card 123: 17 76 16 48 28 71 61 33 95 15 | 76 83 48 58 17 33 3 9 16 67 57 71 15 65 97 53 46 28 45 56 61 95 77 13 92 Card 124: 16 18 93 95 51 52 84 85 53 78 | 97 28 77 42 86 54 19 55 7 72 21 98 35 80 18 99 52 43 68 26 14 81 40 25 56 Card 125: 11 8 17 1 52 36 20 9 6 90 | 20 15 37 9 46 48 42 47 13 60 56 86 6 73 65 81 40 89 62 12 78 43 85 8 11 Card 126: 95 38 48 62 77 93 5 10 37 66 | 62 69 28 29 66 19 46 6 64 24 31 89 79 88 18 65 8 92 34 49 3 12 38 45 22 Card 127: 26 87 33 47 83 8 85 27 64 56 | 2 76 79 64 5 34 33 28 48 25 56 31 73 83 40 18 85 47 11 20 8 19 55 27 63 Card 128: 94 37 29 41 38 42 27 32 51 67 | 40 43 15 70 35 11 61 86 39 16 56 14 26 91 55 87 84 12 19 68 24 46 13 20 45 Card 129: 96 73 94 47 35 54 45 10 86 84 | 67 38 52 91 45 20 69 46 14 22 23 15 58 54 94 35 99 72 84 18 82 86 73 36 90 Card 130: 4 70 46 51 53 32 48 67 44 93 | 81 97 34 82 17 24 88 38 84 96 89 16 54 66 64 30 15 77 20 11 87 28 7 62 45 Card 131: 31 75 50 3 71 74 95 29 80 68 | 53 52 56 26 22 66 61 41 51 49 68 69 73 98 47 10 48 64 6 87 1 11 3 7 59 Card 132: 74 9 97 68 59 75 47 20 27 18 | 61 27 28 73 14 29 53 21 87 82 71 4 99 9 89 59 35 6 1 52 51 42 44 24 55 Card 133: 61 84 71 42 10 30 50 46 32 98 | 65 41 24 91 61 40 3 16 6 22 69 9 43 64 5 85 63 34 17 15 58 51 74 38 35 Card 134: 71 28 6 37 77 19 40 74 41 32 | 60 61 9 19 26 14 88 20 64 89 81 27 43 29 62 93 4 74 80 68 59 38 75 46 17 Card 135: 9 30 86 93 96 98 27 70 57 82 | 32 3 66 5 84 95 35 42 69 55 91 15 34 61 65 90 83 4 59 39 80 43 72 63 99 Card 136: 86 3 66 30 89 50 34 52 49 24 | 36 16 67 11 70 94 75 68 27 91 46 64 10 83 26 12 73 6 21 48 4 55 81 20 41 Card 137: 54 45 73 33 60 59 71 44 35 39 | 74 10 96 33 61 31 90 51 39 8 14 69 54 12 30 44 35 64 60 45 17 59 71 94 73 Card 138: 41 69 63 16 54 59 92 8 25 73 | 54 8 91 49 89 83 61 93 5 25 88 53 1 51 32 57 74 52 42 63 65 24 47 11 48 Card 139: 6 56 41 54 88 46 13 23 50 78 | 95 88 41 5 45 86 13 76 55 43 39 50 81 83 54 36 78 84 34 10 98 40 56 11 19 Card 140: 31 84 87 40 22 74 8 38 71 58 | 71 36 90 11 53 37 14 55 23 22 44 26 59 27 33 13 34 10 31 43 38 57 92 5 75 Card 141: 10 28 45 18 31 37 73 78 69 23 | 69 28 84 93 36 47 24 44 73 23 16 14 18 32 45 66 60 22 78 77 37 12 85 57 8 Card 142: 20 2 96 28 58 69 13 14 51 95 | 54 49 38 23 51 92 28 3 20 36 35 89 14 2 13 95 70 69 58 34 22 47 30 17 63 Card 143: 65 71 17 81 51 63 20 42 49 44 | 24 54 73 86 40 96 35 98 77 90 84 18 3 64 21 49 60 91 7 11 19 59 39 51 52 Card 144: 36 19 16 13 28 91 98 78 50 80 | 52 9 19 41 60 58 3 95 93 87 50 1 36 73 28 16 98 68 80 24 14 2 13 91 78 Card 145: 62 71 15 13 27 46 50 99 81 54 | 88 69 71 20 99 54 64 61 42 36 49 27 13 12 9 19 50 46 15 81 84 62 47 4 94 Card 146: 27 99 95 7 17 12 44 8 93 79 | 65 21 1 30 15 80 42 41 89 71 26 82 4 14 63 38 64 62 16 46 2 70 97 61 59 Card 147: 68 70 18 50 32 42 37 11 71 2 | 98 30 93 72 64 42 15 10 81 37 18 43 76 58 39 32 92 68 50 19 2 31 60 74 63 Card 148: 44 12 19 2 66 13 67 31 6 88 | 8 41 20 87 96 21 57 54 15 53 1 47 75 14 10 61 84 32 37 99 83 91 7 56 4 Card 149: 5 90 25 48 9 28 40 79 6 43 | 67 2 17 42 97 66 79 10 76 82 26 90 68 77 70 78 55 59 31 41 73 94 40 34 20 Card 150: 4 75 17 52 94 69 92 56 31 76 | 54 28 7 17 90 60 58 80 69 52 65 31 5 44 96 55 23 87 76 40 42 1 35 21 64 Card 151: 11 50 8 63 7 49 25 55 58 89 | 58 10 71 40 5 74 7 65 37 1 11 93 47 85 20 14 55 80 25 82 76 89 63 36 30 Card 152: 89 94 53 65 64 93 20 39 27 81 | 46 14 59 64 27 93 53 3 1 38 36 30 95 32 52 39 44 73 61 83 90 65 17 88 62 Card 153: 7 26 63 17 43 92 38 31 35 94 | 81 43 60 6 17 7 57 31 45 92 9 62 20 63 8 50 88 15 54 59 22 86 44 85 79 Card 154: 48 78 69 23 81 8 89 45 33 83 | 25 13 69 95 48 10 36 67 30 71 45 33 29 44 6 52 89 18 56 14 99 43 49 11 80 Card 155: 71 98 91 31 7 68 97 36 37 2 | 64 28 57 99 98 2 35 67 75 39 52 26 81 92 16 43 59 17 78 30 36 12 87 62 31 Card 156: 77 59 92 24 15 19 39 67 5 89 | 59 71 54 35 90 20 68 63 74 66 15 79 50 73 9 65 25 31 77 41 42 80 81 8 33 Card 157: 80 47 90 46 73 51 35 30 96 61 | 56 88 79 98 86 70 65 64 62 53 31 42 7 24 29 82 15 9 40 14 52 83 84 93 69 Card 158: 73 2 19 15 29 78 96 30 33 85 | 57 88 89 63 22 43 1 39 83 72 53 13 55 70 5 8 34 54 97 71 90 59 95 47 49 Card 159: 28 85 71 78 17 57 25 43 94 10 | 1 64 70 49 41 7 60 32 84 21 72 98 34 47 2 91 45 82 8 87 27 35 92 33 97 Card 160: 1 12 51 35 59 92 16 33 80 70 | 83 50 92 76 44 73 17 16 70 45 56 33 67 1 53 59 60 99 49 93 12 96 36 22 61 Card 161: 88 5 52 6 10 41 15 49 56 92 | 5 48 88 95 57 6 29 69 56 41 70 11 64 77 71 15 28 49 51 10 93 78 92 52 50 Card 162: 49 23 69 10 61 93 35 70 97 29 | 23 92 84 65 83 8 5 34 93 35 97 69 61 3 10 14 79 76 27 49 11 29 13 48 70 Card 163: 96 5 13 89 51 52 4 98 91 76 | 89 54 84 90 44 91 4 76 39 52 13 47 98 51 35 96 79 80 25 1 14 60 5 43 9 Card 164: 18 68 21 51 33 69 92 65 94 20 | 38 39 33 12 18 94 53 81 65 82 22 21 51 5 72 20 19 8 69 83 92 98 44 49 68 Card 165: 42 22 36 56 10 17 54 24 72 91 | 72 3 2 10 42 64 54 61 24 91 97 50 36 33 49 65 60 78 9 22 56 17 94 37 67 Card 166: 53 4 58 59 62 86 25 88 71 51 | 25 21 79 31 56 43 55 78 88 8 14 46 37 53 60 81 58 83 50 28 68 62 5 70 11 Card 167: 67 82 17 60 51 73 39 74 8 94 | 42 21 94 73 67 9 89 12 51 4 59 25 60 83 17 98 39 86 31 82 74 27 50 8 93 Card 168: 65 84 50 76 48 23 88 60 9 31 | 16 7 26 75 56 11 49 84 24 8 79 62 96 1 63 60 5 33 6 88 43 92 61 97 53 Card 169: 82 22 84 2 78 72 77 45 49 71 | 16 70 63 77 22 61 40 51 64 84 97 42 14 18 2 74 47 52 19 75 65 96 33 6 1 Card 170: 75 58 29 51 93 22 12 99 41 18 | 72 58 89 17 15 3 93 1 12 87 53 62 41 29 56 80 16 99 50 5 51 68 18 22 75 Card 171: 66 23 4 9 44 20 88 80 47 19 | 9 42 82 19 50 20 97 66 35 31 44 79 99 28 93 47 8 51 58 77 14 88 4 52 27 Card 172: 35 43 91 71 93 57 10 49 7 1 | 24 4 54 5 65 11 1 19 13 92 62 21 39 18 61 7 44 72 14 57 10 6 94 80 95 Card 173: 32 94 54 14 30 61 44 46 39 1 | 47 61 94 78 33 12 1 30 35 57 44 7 14 54 68 4 39 32 9 46 42 62 71 60 63 Card 174: 86 76 1 19 90 50 54 9 59 18 | 9 20 52 73 39 56 81 24 55 18 59 40 4 62 78 19 50 51 97 44 86 90 76 1 25 Card 175: 97 33 65 31 88 19 79 1 68 18 | 40 12 66 46 68 39 59 70 28 79 1 97 31 65 22 55 42 81 19 33 74 57 83 48 88 Card 176: 46 28 57 91 67 49 22 41 48 10 | 64 22 54 68 30 8 91 93 21 83 85 79 84 73 52 33 98 67 59 74 38 99 19 41 96 Card 177: 92 14 73 1 42 72 75 21 63 52 | 5 90 54 70 44 42 55 99 96 85 35 62 26 74 57 17 68 45 36 9 93 15 43 48 83 Card 178: 13 91 79 17 33 49 87 73 39 45 | 25 47 11 81 76 57 43 36 87 64 15 52 67 5 13 55 72 31 2 24 70 19 53 95 45 Card 179: 79 42 94 58 34 15 3 49 19 16 | 75 3 60 56 20 64 67 21 76 15 92 47 29 50 62 41 80 10 31 52 23 90 53 96 58 Card 180: 57 92 69 87 99 12 78 23 89 43 | 68 70 5 79 9 63 88 17 82 19 47 34 11 25 60 67 71 80 2 54 18 33 38 91 30 Card 181: 90 73 65 75 52 81 94 48 57 44 | 35 45 97 84 49 77 5 36 30 4 55 69 21 26 31 19 76 68 66 80 53 72 40 52 54 Card 182: 59 86 35 48 42 87 52 51 90 62 | 38 70 60 32 66 95 72 22 23 24 28 26 56 40 78 2 51 43 39 33 93 57 87 6 31 Card 183: 60 30 90 38 62 7 42 28 20 44 | 85 88 91 11 73 81 54 7 18 66 8 6 79 4 29 31 68 5 16 52 94 34 57 70 2 Card 184: 2 32 36 29 90 89 16 10 46 94 | 52 78 18 39 45 42 40 83 62 50 96 9 33 72 77 81 43 25 64 57 24 95 30 74 35 Card 185: 3 62 16 97 60 2 68 28 15 49 | 9 42 62 39 28 61 8 73 2 16 71 52 97 3 49 38 68 15 12 27 60 30 7 96 70 Card 186: 82 18 77 36 31 41 38 83 48 24 | 13 61 83 65 51 82 63 93 88 31 76 94 25 18 36 35 7 22 77 78 55 14 38 48 50 Card 187: 99 58 65 32 17 79 38 72 41 60 | 99 44 86 60 79 53 56 32 38 19 64 45 34 98 14 20 58 68 17 97 13 72 41 65 77 Card 188: 20 75 76 72 91 98 19 45 74 60 | 71 45 60 20 31 74 72 76 98 15 13 91 43 10 75 58 70 64 84 37 19 77 83 42 96 Card 189: 31 70 40 72 9 74 41 43 1 35 | 6 28 27 35 23 9 13 74 45 38 90 3 22 19 46 8 98 94 43 79 15 24 56 32 73 Card 190: 55 61 7 69 21 5 36 25 41 26 | 8 22 79 57 9 91 84 81 15 35 80 77 69 60 65 2 45 32 38 82 95 19 3 83 23 Card 191: 30 59 66 9 53 71 27 91 58 12 | 59 45 42 92 58 66 61 55 18 80 94 63 21 40 3 75 29 11 88 81 79 28 30 41 9 Card 192: 63 62 44 26 38 79 68 74 5 14 | 9 79 44 71 63 38 26 56 96 16 5 62 12 22 72 99 84 14 68 76 6 70 74 88 45 Card 193: 36 33 91 12 96 88 67 35 41 18 | 68 41 91 1 25 63 19 69 4 58 85 13 77 12 26 35 49 20 18 55 60 67 96 64 88 Card 194: 76 61 87 12 15 24 48 6 77 66 | 41 51 6 1 83 26 9 71 67 32 53 68 88 94 30 99 35 98 13 44 2 72 8 74 82 Card 195: 85 6 35 2 11 29 39 48 13 28 | 21 10 81 28 5 43 58 36 31 39 50 19 2 40 59 20 86 90 96 53 23 70 85 8 68 Card 196: 47 94 65 85 17 71 48 60 19 21 | 42 17 94 79 47 65 13 21 48 45 27 26 71 78 85 50 87 3 91 1 28 58 19 57 9 Card 197: 91 45 87 63 88 8 21 16 4 83 | 51 86 95 45 15 77 60 85 58 47 22 67 17 54 79 8 61 82 57 64 99 70 93 88 14 Card 198: 32 29 5 2 68 99 66 48 23 10 | 5 86 96 59 16 22 97 99 55 38 50 58 80 89 11 75 17 87 93 63 34 73 68 92 48 Card 199: 38 48 17 67 27 85 63 80 15 79 | 78 84 17 52 51 41 48 80 94 12 82 98 4 21 57 15 85 62 63 93 56 55 18 13 83 Card 200: 47 65 31 18 49 45 73 50 66 37 | 3 7 50 65 44 97 94 92 19 54 5 71 8 15 38 89 9 59 49 78 98 18 55 60 25 Card 201: 51 6 38 45 20 98 19 49 42 46 | 39 84 30 18 26 82 76 34 53 66 99 92 14 32 43 91 71 28 86 83 36 87 4 73 90 Card 202: 36 39 6 87 46 59 38 94 77 81 | 29 67 6 95 96 43 22 91 64 79 72 76 69 42 56 18 5 92 31 48 49 57 59 70 47 Card 203: 65 94 83 37 74 48 82 58 24 32 | 15 84 41 50 44 36 45 34 52 48 40 92 88 33 24 82 80 18 78 53 66 49 13 98 89 Card 204: 20 50 78 99 25 67 80 86 54 47 | 62 64 51 14 83 79 61 37 4 98 16 85 27 10 70 50 13 8 53 63 65 97 71 21 94 Card 205: 85 47 9 91 79 52 28 26 19 33 | 61 75 46 17 16 34 98 3 62 56 74 54 88 99 2 57 4 78 32 72 97 81 90 64 63 Card 206: 80 39 46 82 49 98 73 32 85 15 | 90 60 47 54 59 41 20 33 92 11 88 61 99 84 94 78 71 35 55 2 51 40 67 18 66""" }
0
Kotlin
0
3
26ef6b194f3e22783cbbaf1489fc125d9aff9566
26,446
kotlinadventofcode
MIT License
src/day10/MinimumTimeDiff.kt
minielectron
332,678,510
false
{"Java": 127791, "Kotlin": 48336}
package day10 import kotlin.math.abs /* Given an datastructure.array of time datastructure.strings times, return the smallest difference between any two times in minutes. Example: Input: ["00:03", "23:59", "12:03"] Output: 4 Input: The closest 2 times are "00:03" and "23:59" (by wrap-around), and they differ by 4 minutes. Constraints: All datastructure.strings will be non-empty and in the format HH:mm */ fun main(){ var min = Integer.MAX_VALUE val input = listOf("00:03", "23:59", "12:03") var pair : Pair<Int, Int> = Pair(-1,-1) for( i in input.indices){ for (j in i+1 until input.size){ val d = getDifference(input[i], input[j]) if (min > d){ min = d pair = Pair(i, j) } } } println("diff = <${pair.first}, ${pair.second}>") } fun getDifference(first: String, second: String ) : Int { return abs(getMinutes(first) - getMinutes(second)) } fun getMinutes(time: String): Int { val t = time.split(":") val h : Int h = if (t[0] == "00") { 24 }else{ t[0].toInt() } val m = t[1].toInt() return abs(h * 60 + m) }
0
Java
0
0
f2aaff0a995071d6e188ee19f72b78d07688a672
1,177
data-structure-and-coding-problems
Apache License 2.0
src/main/kotlin/at2020/day1/At2020Day1Part2.kt
JeanBarbosa27
575,328,729
false
{"Kotlin": 10872}
package at2020.day1 class At2020Day1Part2 : At2020Day1() { override var entriesToReachTargetSum = IntArray(3) { 0 } override val puzzleDescription: String = "Day1 part 2 description:\n" + "Find the three entries that sum to 2020; what do you get if you multiply them together?\n" private fun calculateProduct(): Int { return entriesToReachTargetSum[0] * entriesToReachTargetSum[1] * entriesToReachTargetSum[2] } private fun setEntriesToReachTargetSum(elementToSum: Int) { if ((currentIndex + 1) < expenseReport.lastIndex) { entriesToReachTargetSum[0] = expenseReport[currentIndex] entriesToReachTargetSum[1] = expenseReport[(currentIndex + 1)] } entriesToReachTargetSum[2] = elementToSum } override fun searchEntriesToGetProduct(list: List<Int>) { println("currentIndex: $currentIndex") println("list.size: ${list.size}") if (list.size < 10) { println("list is less than 10, here it is: $list") var elementToSumIndex = 0 println("list.lastIndex: ${list.lastIndex}") while (elementToSumIndex <= list.lastIndex) { println("elementToSumIndex: $elementToSumIndex") setEntriesToReachTargetSum(list[elementToSumIndex]) print("entries: [") for (entry in entriesToReachTargetSum) { print("$entry , " ) } println("]") println("entriesToReachTargetSum.sum(): ${entriesToReachTargetSum.sum()}") if (entriesToReachTargetSum.sum() == targetSum) { println("product is: ${calculateProduct()}") break } elementToSumIndex++ if (elementToSumIndex > list.lastIndex) { currentIndex++ searchEntriesToGetProduct(expenseReport) } } return } val listMiddleIndex = list.lastIndex / 2 println("listMiddleIndex: $listMiddleIndex") println("lastIndex: ${list.lastIndex}") if (listMiddleIndex > 0) { println("expenseReport[currentIndex]: ${expenseReport[currentIndex]}") println("list[listMiddleIndex]: ${list[listMiddleIndex]}") setEntriesToReachTargetSum(list[listMiddleIndex]) println("entriesToReachTargetSum: ${entriesToReachTargetSum[0]}, ${entriesToReachTargetSum[1]}, ${entriesToReachTargetSum[2]}") if (entriesToReachTargetSum.sum() == targetSum) { println("Target sum found!") println(calculateProduct()) return } val halfList = mutableListOf<Int>() if (entriesToReachTargetSum.sum() > targetSum) { println("Target sum is in first half, reiterating") println(entriesToReachTargetSum.sum()) list.forEachIndexed { index, number -> if (index <= listMiddleIndex) halfList.add(number) } println("halfList is: $halfList") searchEntriesToGetProduct(halfList) return } println("Target sum is in second half, reiterating") println(entriesToReachTargetSum.sum()) list.forEachIndexed { index, number -> if (index >= listMiddleIndex && index <= list.lastIndex ) halfList.add(number) } searchEntriesToGetProduct(halfList) } } }
0
Kotlin
0
0
62c4e514cd9a306e6a4b5dbd0c146213f08e05f3
3,561
advent-of-code-solving-kotlin
MIT License
src/main/kotlin/dp/MaxProd.kt
yx-z
106,589,674
false
null
package dp import util.* // similar to `MaxSum`, // given an array of numbers, // find the largest product in any contiguous subarray. // note that two negative numbers produce a positive result, ex. (-2) * (-4) = 8 fun main(args: Array<String>) { val arr = intArrayOf(-6, 12, -7, 0, 14, -7, 5) // println(arr.maxProdInt()) val fracArray = oneArrayOf(-2.0, 8.0, 0.25, -4.0, 0.5, -8.0) // println(fracArray.maxProd()) // println(fracArray.maxProdShort()) println(fracArray.maxProdKadane()) println(fracArray.maxProdRedo()) } // this solution assumes that input array are all integers // but cannot handle fractions that may decrease the product fun IntArray.maxProdInt(): Int { if (size == 0) { return 0 } if (size == 1) { return max(0, this[0]) } // 0 cancels all our current progress! yuck! // so we will recursively call ourself for (i in 0 until size) { if (this[i] == 0) { return max(this[0 until i].maxProdInt(), this[i + 1 until size].maxProdInt()) } } // since we are here, there is no 0 in the array // multiply all numbers up! val total = this.reduce { acc, it -> acc * it } // extra work to be done if the result is negative if (total < 0) { var leftMax = total var leftIdx = 0 while (leftIdx < size && this[leftIdx] > 0) { leftMax /= this[leftIdx] leftIdx++ } // first negative number from left to right leftMax /= this[leftIdx] var rightMax = total var rightIdx = size - 1 while (rightIdx >= 0 && this[rightIdx] > 0) { rightMax /= this[rightIdx] rightIdx-- } // first negative number from right to left rightMax /= this[rightIdx] return max(leftMax, rightMax) } return total // we can do this in O(n) } // given A[1..n] containing possibly negative, and possibly non-integer, numbers // find the largest prod fun OneArray<Double>.maxProd(): Double { val A = this val n = size // i like my idea from the above if (n == 0) { return 0.0 } if (n == 1) { return max(0.0, this[1]) } // 0 cancels all our current progress! yuck! // so we will recursively call itself before and after the 0 for (i in 1..n) { if (this[i] == 0.0) { return max(this[1 until i].maxProd(), this[i + 1..n].maxProd()) } } // still assumes no 0 in the input array // dp(i): (max product of A[1..i] that ends in A[i], min of such product) // memoization structure: 1d array dp[1..n] : dp[i] = dp(i) val dp = OneArray(n) { 0.0 tu 0.0 } // space complexity: O(n) // base case: // dp(i) = 0 if i !in 1..n dp.getterIndexOutOfBoundsHandler = { 0.0 tu 0.0 } // dp(1) = max(0, A[1]) dp[1] = max(0.0, A[1]) tu min(0.0, A[1]) // recursive case: // dp(i) = (max{ dp(k)_1 : k < i } * A[i], min{ dp(k)_2 : k < i } * A[i]) if A[i] > 0 // = (min{ dp(k)_2 : k < i } * A[i], max{ dp(k)_1 : k < i } * A[i]) o/w for (i in 2..n) { val maxPre = (1 until i).map { dp[it].first }.max() ?: 0.0 val minPre = (1 until i).map { dp[it].second }.min() ?: 0.0 dp[i] = if (A[i] > 0) { maxPre * A[i] tu minPre * A[i] } else { minPre * A[i] tu maxPre * A[i] } } // time complexity: O(n^2) dp.prettyPrintln() // we want max{ dp(i)_1 } return dp.asSequence().map { it.first }.max() ?: 0.0 } // while the following program is short, it is still slow O(n^2) fun OneArray<Double>.maxProdShort(): Double { val dp = OneArray(size) { OneArray(size) { 0.0 } } for (i in 1..size) dp[i, i] = this[i] for (i in 1..size) for (j in i + 1..size) dp[i, j] = dp[i, j - 1] * this[j] return dp.asSequence().map { it.max() ?: 0.0 }.max() ?: 0.0 } // O(n) time // assume input has no 0s, o/w we can wrap it as the methods above do fun OneArray<Double>.maxProdKadane(): Double { // similar to Kadane's algorithm described in MaxSum var maxEndingHere = 1.0 var minEndingHere = 1.0 var maxSoFar = 1.0 asSequence().forEach { if (it > 0) { maxEndingHere *= it minEndingHere = min(minEndingHere * it, 1.0) } else { val tmp = maxEndingHere maxEndingHere = max(minEndingHere * it, 1.0) minEndingHere = tmp * it } maxSoFar = max(maxSoFar, maxEndingHere) } return maxSoFar } fun OneArray<Double>.maxProdRedo(): Double { val A = this val n = size // max[i]: max prod subarray of A[i..n] that MUST include A[i] val max = OneArray(n) { A[it] } // min[i]: min prod subarray of A[i..n] that MUST include A[i] val min = OneArray(n) { A[it] } // space: O(n) for (i in n - 1 downTo 1) { when { // 0 is the easiest case since everything multiply with 0 is 0 A[i] == 0.0 -> { max[i] = 0.0 min[i] = 0.0 } // then we can do > 0 since it's not that tricky A[i] > 0 -> { // we can get bigger when the scaling factor > 1 if (max[i + 1] > 1.0) { max[i] *= max[i + 1] } // we will be smaller if we are multiplied with anything < 1 // ex. 0.7, 0.1, 0, and even better, negative numbers! if (min[i + 1] < 1.0) { min[i] *= min[i + 1] } } // we are now < 0 A[i] < 0 -> { // we can get bigger if we can either scaled to a smaller // magnitude (but still negative), or better, become positive! if (min[i + 1] < 1.0) { max[i] *= min[i + 1] } // we will get even smaller (more negative) when we are scaled up if (max[i + 1] > 1.0) { min[i] *= max[i + 1] } } } } // time: O(n) // max.prettyPrintln() return max.max()!! }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
5,326
AlgoKt
MIT License
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day09.kt
giacomozama
572,965,253
false
{"Kotlin": 75671}
package me.giacomozama.adventofcode2022.days import java.io.File import kotlin.math.abs import kotlin.math.sign class Day09 : Day() { private lateinit var input: List<IntArray> override fun parseInput(inputFile: File) { input = inputFile.useLines { lines -> lines.map { intArrayOf( when (it[0]) { 'U' -> U 'R' -> R 'D' -> D else -> L }, it.drop(2).toInt() ) }.toList() } } // time: O(n), space: O(n) override fun solveFirstPuzzle(): Int { val visited = hashSetOf<Int>() var headX = 0 var headY = 0 var tailX = 0 var tailY = 0 for ((dir, dist) in input) { repeat(dist) { when (dir) { U -> headY-- R -> headX++ D -> headY++ L -> headX-- } if (abs(headX - tailX) > 1 || abs(headY - tailY) > 1) { tailX += (headX - tailX).sign tailY += (headY - tailY).sign } visited += tailX * 10007 + tailY } } return visited.size } // time: O(n), space: O(n) override fun solveSecondPuzzle(): Int { val visited = hashSetOf<Int>() val state = Array(10) { IntArray(2) } for ((dir, dist) in input) { repeat(dist) { when (dir) { U -> state[0][1]-- R -> state[0][0]++ D -> state[0][1]++ L -> state[0][0]-- } for (i in 1..9) { if (abs(state[i - 1][0] - state[i][0]) > 1 || abs(state[i - 1][1] - state[i][1]) > 1) { state[i][0] += (state[i - 1][0] - state[i][0]).sign state[i][1] += (state[i - 1][1] - state[i][1]).sign } } visited += state[9][0] * 10007 + state[9][1] } } return visited.size } companion object { private const val U = 0 private const val R = 1 private const val D = 2 private const val L = 3 } }
0
Kotlin
0
0
c30f4a37dc9911f3e42bbf5088fe246aabbee239
2,400
aoc2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestSubarray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Deque import java.util.LinkedList fun shortestSubarray(a: IntArray, k: Int): Int { val n = a.size val p = LongArray(n + 1) for (i in 0 until n) p[i + 1] = p[i] + a[i].toLong() var ans = n + 1 val monoq: Deque<Int> = LinkedList() // opt(y) candidates, as indices of P for (y in p.indices) { // Want opt(y) = largest x with P[x] <= P[y] - K; while (monoq.isNotEmpty() && p[y] <= p[monoq.last]) { monoq.removeLast() } while (monoq.isNotEmpty() && p[y] >= p[monoq.first] + k) { ans = ans.coerceAtMost(y - monoq.removeFirst()) } monoq.addLast(y) } return if (ans < n + 1) ans else -1 }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,346
kotlab
Apache License 2.0
2020/day4/day4.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day4 import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input is whitespace-separated key:value pairs. Count number with required keys are present. */ object Part1 { private val required = setOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") // cid is optional private val whitespace = Regex("""\s+""") fun solve(input: Sequence<String>): String { return input .map { line -> whitespace.split(line).map { it.substringBefore(':') } } .filter { it.containsAll(required) } .count() .toString() } } /* Now validate value rules. */ object Part2 { enum class Field(val pattern: Regex) { BYR(Regex("""\d{4}""")) { override fun validate(value: String) = pattern.matches(value) && value.toInt() in 1920..2002 }, IYR(Regex("""\d{4}""")) { override fun validate(value: String) = pattern.matches(value) && value.toInt() in 2010..2020 }, EYR(Regex("""\d{4}""")) { override fun validate(value: String) = pattern.matches(value) && value.toInt() in 2020..2030 }, HGT(Regex("""(\d+)(cm|in)""")) { override fun validate(value: String) = pattern.matchEntire(value)?.let { val (_, height, units) = it.groupValues when (units) { "cm" -> height.toInt() in 150..193 "in" -> height.toInt() in 59..76 else -> throw IllegalArgumentException("$value has unknown units") } } ?: false }, HCL(Regex("""#[0-9a-f]{6}""")), ECL(Regex("""amb|blu|brn|gry|grn|hzl|oth""")), PID(Regex("""\d{9}""")); open fun validate(value: String) = pattern.matches(value) } private val whitespace = Regex("""\s+""") fun solve(input: Sequence<String>): String { return input .map { whitespace.split(it) } .filter { fields -> fields.map { it.split(':') } .filter { it[0] != "cid" } .filter { Field.valueOf(it[0].uppercase()).validate(it[1]) } .count() == Field.values().size } .count() .toString() } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toParagraphs().toList() // println("Lines has ${lines.size} paragraphs") print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } } fun Sequence<String>.toParagraphs(): Sequence<String> { var paragraph = mutableListOf<String>() return sequence { forEach { line -> if (line.isNotBlank()) { paragraph.add(line) } else { if (paragraph.isNotEmpty()) { yield(paragraph.joinToString("\n")) } paragraph = mutableListOf() } } if (paragraph.isNotEmpty()) { yield(paragraph.joinToString("\n")) } } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
3,272
adventofcode
MIT License
leetcode2/src/leetcode/move-zeroes.kt
hewking
68,515,222
false
null
package leetcode /** * 283. 移动零 * https://leetcode-cn.com/problems/move-zeroes/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-10-22 11:46 *给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次数。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/move-zeroes 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object MoveZeroes { class Solution { /** * 思路: * 参考冒泡排序,把0 冒到最后的位置 * 时间复杂度: O(n^2) */ fun moveZeroes(nums: IntArray): Unit { for (i in 0 until nums.size) { if (nums[i] == 0) { for (j in i + 1 until nums.size){ if (nums[j] != 0){ val tmp = nums[i] nums[i] = nums[j] nums[j] = tmp break } } } } } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,335
leetcode
MIT License
src/main/kotlin/day1/solver.kt
derekaspaulding
317,756,568
false
null
package day1 import java.io.File import java.lang.IllegalArgumentException fun solveForTwoNums(nums: List<Int>, target: Int = 2020): Pair<Int, Int> { for ((index, num1) in nums.withIndex()) { if (index != nums.lastIndex) { for (num2 in nums.subList(index + 1, nums.size)) { if (num1 + num2 == target) { return Pair(num1, num2) } } } } throw IllegalArgumentException("Given list does not contain a solution") } fun solveForThreeNums(nums: List<Int>): Triple<Int, Int, Int> { for ((index, num1) in nums.withIndex()) { if (index + 1 != nums.lastIndex) { try { val (num2, num3) = solveForTwoNums(nums.subList(index + 1, nums.size), 2020 - num1) return Triple(num1, num2, num3) } catch (e: IllegalArgumentException) { continue } } } throw IllegalArgumentException("Given list does not contain a solution") } fun main() { val nums = File("src/main/resources/day1/input.txt") .useLines { it.toList() } .map { it.toInt() } val (twoNum1, twoNum2) = solveForTwoNums(nums) val twoNumProduct = twoNum1 * twoNum2 println("$twoNum1 x $twoNum2 = $twoNumProduct") val (threeNum1, threeNum2, threeNum3) = solveForThreeNums(nums) val threeNumProduct = threeNum1 * threeNum2 * threeNum3 println("$threeNum1 x $threeNum2 x $threeNum3 = $threeNumProduct") }
0
Kotlin
0
0
0e26fdbb3415fac413ea833bc7579c09561b49e5
1,506
advent-of-code-2020
MIT License
src/main/kotlin/com/sk/topicWise/dp/53. Maximum Subarray.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.dp /** * At any index i there are 3 possibilities, * (1) Max sub-array is found before i.e. maxSoFar * (2) Max sub-array is running and also include this element i.e. maxEndingHere * (3) Max sub-array start here and may contain only this element */ // Top-down approach using memoization // StackOverflowError for big size array, but works for smaller array size private class Solution { fun maxSubArray(arr: IntArray): Int { return maxEndingAt(arr.lastIndex, arr).second } private fun maxEndingAt(n: Int, arr: IntArray): Pair<Int, Int> { if (n == 0) return Pair(arr[0], arr[0]) val mx = maxEndingAt(n - 1, arr) val maxHere = maxOf(mx.first + arr[n], arr[n]) val maxSoFar = maxOf(mx.second, maxHere) return Pair(maxHere, maxSoFar) } } // Bottom-up approach using tabulation private fun maxSubArray2(nums: IntArray): Int { var maxSoFar = nums[0] var maxEndingHere = nums[0] for (i in 1..nums.lastIndex) { maxEndingHere = maxOf(maxEndingHere + nums[i], nums[i]) maxSoFar = maxOf(maxSoFar, maxEndingHere) } return maxSoFar }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,157
leetcode-kotlin
Apache License 2.0
src/shreckye/coursera/algorithms/Course 1 Programming Assignment #3.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.io.File import kotlin.test.assertEquals val filename = args[0] val integers = File(filename).useLines { it.map(String::toInt).toIntArray(10_000) } fun quickSortAndCountNumComparisons( integers: IntArray, left: Int = 0, right: Int = integers.size, swapPivot: IntArray.(Int, Int) -> Unit ): Int { val size = right - left //println("$left $right $size") if (size == 0 || size == 1) return 0 integers.swapPivot(left, right) val pivot = integers[left] var i = 1 for (j in 1 until size) if (integers[left + j] < pivot) integers.swap(left + i++, left + j) integers.swap(left, left + i - 1) return size - 1 + quickSortAndCountNumComparisons(integers, left, left + i - 1, swapPivot) + quickSortAndCountNumComparisons(integers, left + i, right, swapPivot) } @Suppress("NOTHING_TO_INLINE") inline fun IntArray.swap(i: Int, j: Int) { this[i] = this[j].also { this[j] = this[i] } } inline fun quickSortAndCountNumComparisonsWithChoosePivot( integers: IntArray, crossinline choosePivot: IntArray.(Int, Int) -> Int ) = quickSortAndCountNumComparisons(integers) { left, right -> swap(left, choosePivot(left, right)) } fun quickSortAndCountNumComparisons(integers: IntArray) = quickSortAndCountNumComparisons(integers) { _, _ -> } fun quickSortAndCountNumComparisonsUsingFinalElementAsPivot(integers: IntArray) = quickSortAndCountNumComparisonsWithChoosePivot(integers) { _, right -> right - 1 } fun quickSortAndCountNumComparisonsUsingMedianOfThreeAsPivot(integers: IntArray) = quickSortAndCountNumComparisonsWithChoosePivot(integers) { left, right -> val first = left.let { it to this[it] } val middle = ((left + right - 1) / 2).let { it to this[it] } val final = (right - 1).let { it to this[it] } val three = arrayOf(first, middle, final) three.sortBy(IntPair::second) three[1].first } var integersToSort = integers.copyOf() println("1. ${quickSortAndCountNumComparisons(integersToSort)}") integersToSort = integers.copyOf() println("2. ${quickSortAndCountNumComparisonsUsingFinalElementAsPivot(integersToSort)}") integersToSort = integers.copyOf() println("3. ${quickSortAndCountNumComparisonsUsingMedianOfThreeAsPivot(integersToSort)}") // Test cases for (n in 0 until 1024) { val maxNumComparisons = n * (n - 1) / 2 assertEquals(maxNumComparisons, quickSortAndCountNumComparisons(IntArray(n) { it })) assertEquals(maxNumComparisons, quickSortAndCountNumComparisons(IntArray(n) { n - it })) assertEquals(maxNumComparisons, quickSortAndCountNumComparisonsUsingFinalElementAsPivot(IntArray(n) { it })) assertEquals(maxNumComparisons, quickSortAndCountNumComparisonsUsingFinalElementAsPivot(IntArray(n) { n - it })) } for (n in 0..10) { val size = (2 pow n + 1) - 1 val expectedNumOfComparisons = (n - 1) * (2 pow n + 1) + 2 assertEquals( expectedNumOfComparisons, quickSortAndCountNumComparisonsUsingMedianOfThreeAsPivot(IntArray(size) { it }), "size = $size" ) }
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
3,154
coursera-stanford-algorithms-solutions-kotlin
MIT License
multi-functions/src/main/kotlin/io/multifunctions/MultiMap.kt
stupacki
78,018,935
false
{"Kotlin": 108548}
package io.multifunctions import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad /** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. */ public inline fun <A, B, R> Iterable<Pair<A, B>>.map( transform: (A, B) -> R, ): List<R> = map { (first, second) -> transform(first, second) } /** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. */ public inline fun <A, B, C, R> Iterable<Triple<A, B, C>>.map( transform: (A, B, C) -> R, ): List<R> = map { (first, second, third) -> transform(first, second, third) } /** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. */ public inline fun <A, B, C, D, R> Iterable<Quad<A, B, C, D>>.map( transform: (A, B, C, D) -> R, ): List<R> = map { (first, second, third, fourth) -> transform(first, second, third, fourth) } /** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. */ public inline fun <A, B, C, D, E, R> Iterable<Penta<A, B, C, D, E>>.map( transform: (A, B, C, D, E) -> R, ): List<R> = map { (first, second, third, fourth, fifth) -> transform(first, second, third, fourth, fifth) } /** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. */ public inline fun <A, B, C, D, E, F, R> Iterable<Hexa<A, B, C, D, E, F>>.map( transform: (A, B, C, D, E, F) -> R, ): List<R> = map { (first, second, third, fourth, fifth, sixth) -> transform(first, second, third, fourth, fifth, sixth) } /** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. */ public inline fun <A, B, C, D, E, F, G, R> Iterable<Hepta<A, B, C, D, E, F, G>>.map( transform: (A, B, C, D, E, F, G) -> R, ): List<R> = map { (first, second, third, fourth, fifth, sixth, seventh) -> transform(first, second, third, fourth, fifth, sixth, seventh) }
0
Kotlin
3
25
5e82fd8e0dd745b379c7f4d8c475a66467b71ae9
2,356
MultiFunctions
Apache License 2.0
src/main/kotlin/aoc2021/day2.kt
sodaplayer
434,841,315
false
{"Kotlin": 31068}
package aoc2021 import aoc2021.utils.loadInput fun main() { val pattern = Regex("""(\w+) (\d+)""") val coms = loadInput("/2021/day2") .bufferedReader() .readLines() .map { val (dir, units) = pattern.find(it)!!.destructured Pair(dir, units.toInt()) } .fold(Pair(0, 0)) { (horz, vert), (dir, units) -> when(dir) { "forward" -> Pair(horz + units, vert) "up" -> Pair(horz, vert - units) "down" -> Pair(horz, vert + units) else -> Pair(horz, vert) } } val part1 = coms println(part1.first * part1.second) val coms2 = loadInput("/2021/day2") .bufferedReader() .readLines() .map { val (dir, units) = pattern.find(it)!!.destructured Pair(dir, units.toInt()) } .fold(Triple(0, 0, 0)) { (horz, vert, aim), (dir, units) -> when(dir) { "forward" -> Triple(horz + units, vert + units * aim, aim) "up" -> Triple(horz, vert, aim - units) "down" -> Triple(horz, vert, aim + units) else -> Triple(horz, vert, aim) } } val part2 = coms2 println(part2.first * part2.second) }
0
Kotlin
0
0
2d72897e1202ee816aa0e4834690a13f5ce19747
1,313
aoc-kotlin
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch4/Problem48.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch4 import java.math.BigInteger /** * Problem 48: Self Powers * * https://projecteuler.net/problem=48 * * Goal: Find the last 10 digits of the number generated by the series, * 1^1 + 2^2 + 3^3 + .. + N^N, without leading zeroes. * * Constraints: 1 <= N <= 2e6 * * e.g.: N = 10 * 1^1 + 2^2 + 3^3 + .. + 10^10 = 10_405_071_317 * last 10 digits = 405_071_317 (leading zero omitted) */ class SelfPowers { private val modulo: Long = 10_000_000_000 /** * Solution based on the modular arithmetic rule that: * * (x + y) % z == ((x % z) + (y % z)) % z * * This same rule applies to multiplication with modulo: * * (x * y) % z == ((x % z) * (y % z)) % z * * The carried over number for each new self-power is thereby significantly reduced by * performing modulo at every step, which avoids the need to use BigInteger. * * SPEED (Worse) 1.13s for N = 1e4 */ fun selfPowersSumModulo(n: Int): Long { var sum = 0L for (d in 1..n) { var power = d.toLong() repeat(d - 1) { power *= d power %= modulo } sum += power sum %= modulo } return sum } /** * Solution optimised by using BigInteger's built-in modPow(exp, mod). * * SPEED (BETTER) 337.51ms for N = 1e4 */ fun selfPowersSum(n: Int): Long { val bigMod = BigInteger.valueOf(modulo) var sum = BigInteger.ZERO for (d in 1L..n) { val power = BigInteger.valueOf(d) sum += power.modPow(power, bigMod) } return sum.mod(bigMod).longValueExact() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
1,744
project-euler-kotlin
MIT License
src/main/kotlin/g0601_0700/s0637_average_of_levels_in_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0637_average_of_levels_in_binary_tree // #Easy #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_02_10_Time_249_ms_(100.00%)_Space_39.5_MB_(72.73%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun averageOfLevels(root: TreeNode?): List<Double> { val map: MutableMap<Int, Array<Double>> = HashMap() helper(root, map, 0) val result: MutableList<Double> = ArrayList() for (pair in map.values) { val avg = pair[1] / pair[0] result.add(avg) } return result } private fun helper(root: TreeNode?, map: MutableMap<Int, Array<Double>>, level: Int) { if (root == null) { return } val pair = if (map.containsKey(level)) map[level]!! else arrayOf(0.0, 0.0) pair[0] += 1.0 pair[1] = pair[1] + root.`val` map[level] = pair helper(root.left, map, level + 1) helper(root.right, map, level + 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,209
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g2401_2500/s2477_minimum_fuel_cost_to_report_to_the_capital/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2477_minimum_fuel_cost_to_report_to_the_capital // #Medium #Depth_First_Search #Breadth_First_Search #Tree #Graph // #2023_07_05_Time_969_ms_(100.00%)_Space_106_MB_(100.00%) class Solution { private var ans = 0L fun minimumFuelCost(roads: Array<IntArray>, seats: Int): Long { val adj = ArrayList<ArrayList<Int>>() val n = roads.size + 1 ans = 0L for (i in 0 until n) { adj.add(ArrayList()) } for (a in roads) { adj[a[0]].add(a[1]) adj[a[1]].add(a[0]) } solve(adj, seats, 0, -1) return ans } private fun solve(adj: ArrayList<ArrayList<Int>>, seats: Int, src: Int, parent: Int): Long { var people = 1L for (i in adj[src]) { if (i != parent) { people += solve(adj, seats, i, src) } } if (src != 0) { ans += Math.ceil(people.toDouble() / seats).toLong() } return people } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,021
LeetCode-in-Kotlin
MIT License
src/main/java/challenges/educative_grokking_coding_interview/sliding_window/_7/CharacterReplacement.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.sliding_window._7 /** * Given a string with lowercase letters only, if you are allowed to replace no more than k letters with * any letter, find the length of the longest substring having the same letters after replacement. * * https://www.educative.io/courses/grokking-the-coding-interview/R8DVgjq78yR */ object CharacterReplacement { private fun findLength(str: String, k: Int): Int { var windowStart = 0 var maxLength = 0 var maxRepeatLetterCount = 0 val letterFrequencyMap: MutableMap<Char, Int> = HashMap() // try to extend the range [windowStart, windowEnd] for (windowEnd in str.indices) { val rightChar = str[windowEnd] letterFrequencyMap[rightChar] = letterFrequencyMap.getOrDefault(rightChar, 0) + 1 // we don't need to place the maxRepeatLetterCount under the below 'if', see the // explanation in the 'Solution' section above. maxRepeatLetterCount = Math.max(maxRepeatLetterCount, letterFrequencyMap[rightChar]!!) // current window size is from windowStart to windowEnd, overall we have a letter which is // repeating 'maxRepeatLetterCount' times, this means we can have a window which has one letter // repeating 'maxRepeatLetterCount' times and the remaining letters we should replace. // if the remaining letters are more than 'k', it is the time to shrink the window as we // are not allowed to replace more than 'k' letters val length = windowEnd - windowStart + 1 val remaining = length - maxRepeatLetterCount if (remaining > k) { val leftChar = str[windowStart] letterFrequencyMap[leftChar] = letterFrequencyMap[leftChar]!! - 1 windowStart++ } maxLength = Math.max(maxLength, windowEnd - windowStart + 1) } return maxLength } @JvmStatic fun main(args: Array<String>) { println(findLength("aabccbb", 2)) println(findLength("abbcb", 1)) println(findLength("abccde", 1)) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,190
CodingChallenges
Apache License 2.0
src/commonMain/kotlin/transform/Snub.kt
elizarov
337,522,862
false
null
package polyhedra.common.transform import polyhedra.common.poly.* import polyhedra.common.util.* import kotlin.math.* // a * x^2 + b * x + c = 0 private fun solve3(a: Double, b: Double, c: Double) = (-b + sqrt(sqr(b) - 4 * a * c)) / (2 * a) private fun snubComputeSA(ea: Double, da: Double, cr: Double): Double { val rf = 1 - cr val cm = (1 - cos(da)) / 2 val cp = (1 + cos(da)) / 2 val cosGA = solve3(cp * sqr(rf), 2 * cm * rf * cos(ea), -sqr(cos(ea)) * (cm + sqr(rf))) return ea - acos(cosGA) } private fun snubComputeA(ea: Double, da: Double, cr: Double, sa: Double): Double { val h = 1 / (2 * tan(ea)) val ga = ea - sa val rf = 1 - cr val t = rf / (2 * sin(ea)) return Vec3( 2 * t * sin(ga), (h - t * cos(ga)) * (cos(da) - 1), (h - t * cos(ga)) * sin(da) ).norm } private fun snubComputeB(ea: Double, da: Double, cr: Double, sa: Double): Double { val h = 1 / (2 * tan(ea)) val ga = ea - sa val ha = ea + sa val rf = 1 - cr val t = rf / (2 * sin(ea)) return Vec3( t * (sin(ga) - sin(ha)), (h - t * cos(ga)) * cos(da) - (h - t * cos(ha)), (h - t * cos(ga)) * sin(da) ).norm } private fun snubComputeCR(ea: Double, da: Double): Double { var crL = 0.0 var crR = 1.0 while (true) { val cr = (crL + crR) / 2 if (cr <= crL || cr >= crR) return cr // result precision is an ULP val sa = snubComputeSA(ea, da, cr) // error goes from positive to negative to NaN as cr goes from 0 to 1 val rf = 1 - cr val err = snubComputeB(ea, da, cr, sa) - rf if (err <= 0) crL = cr else crR = cr } } data class SnubbingRatio(val cr: Double, val sa: Double) { override fun toString(): String = "(cr=${cr.fmt}, sa=${sa.fmt})" } fun Polyhedron.regularSnubbingRatio(edgeKind: EdgeKind? = null): SnubbingRatio { val (ea, da) = regularFaceGeometry(edgeKind) val cr = snubComputeCR(ea, da) val sa = snubComputeSA(ea, da, cr) return SnubbingRatio(cr, sa) } fun Polyhedron.snub( sr: SnubbingRatio = regularSnubbingRatio(), scale: Scale? = null, forceFaceKinds: List<FaceKindSource>? = null ) = transformedPolyhedron(Transform.Snub, sr, scale, forceFaceKinds) { val (cr, sa) = sr val rr = dualReciprocationRadius // vertices from the face-vertices (directed edges) val fvv = fs.associateWith { f -> val c = f.dualPoint(rr) // for regular polygons -- face center val r = f.toRotationAroundQuat(-sa) f.directedEdges.associateBy({ it.a }, { e -> vertex(c + ((1 - cr) * (e.a - c)).rotated(r), VertexKind(directedEdgeKindsIndex[e.kind]!!)) }) } // faces from the original faces for (f in fs) { face(fvv[f]!!.values, f.kind) } // faces from the original vertices var kindOfs = faceKinds.size for (v in vs) { val fvs = v.directedEdges.map { fvv[it.r]!![v]!! } face(fvs, FaceKind(kindOfs + v.kind.id)) } for (vk in vertexKinds.keys) faceKindSource(FaceKind(kindOfs + vk.id), vk) // 3-faces from the directed edges kindOfs += vertexKinds.size for (e in directedEdges) { val fvs = listOf( fvv[e.l]!![e.a]!!, fvv[e.l]!![e.b]!!, fvv[e.r]!![e.a]!! ) face(fvs, FaceKind(kindOfs + directedEdgeKindsIndex[e.kind]!!)) } for ((ek, id) in directedEdgeKindsIndex) faceKindSource(FaceKind(kindOfs + id), ek) mergeIndistinguishableKinds() }
0
Kotlin
0
28
ac15c7fe326e472470562a42f9fd519b24dfb455
3,554
PolyhedraExplorer
Apache License 2.0
tree_data_structure/SymmetricBinaryTree/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
/** * Given a binary tree, check whether it is a mirror of itself * (ie, symmetric around its center). * <br/> * https://www.interviewbit.com/problems/symmetric-binary-tree/ */ fun isSymmetric(tree: TreeNode): Boolean = subSymmetry(tree.left, tree.right) fun subSymmetry(l: TreeNode?, r: TreeNode?): Boolean = (l == r) //this only catches null or same objects || (l?.v == r?.v && subSymmetry(l?.left, r?.right) && subSymmetry(l?.right, r?.left)) class TreeNode(val v: Int) { var left: TreeNode? = null var right: TreeNode? = null } //Test fun main() { var t = TreeNode(1) var success = true t.left = TreeNode(2) t.right = TreeNode(2) t.left!!.left = TreeNode(3) t.left!!.right = TreeNode(4) t.right!!.right = TreeNode(3) t.right!!.left = TreeNode(4) success = success && isSymmetric(t) t = TreeNode(1) t.left = TreeNode(2) t.right = TreeNode(2) t.left!!.left = TreeNode(3) t.right!!.right = TreeNode(3) t.right!!.left = TreeNode(4) success = success && isSymmetric(t) == false t = TreeNode(1) t.left = TreeNode(2) t.right = TreeNode(2) t.left!!.left = TreeNode(3) t.right!!.left = TreeNode(3) success = success && isSymmetric(t) == false println("Symmetric tree: ${if (success) "SUCCESS" else "FAIL"}") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,322
codility
MIT License
LeetCode/Medium/merge-intervals/Solution.kt
GregoryHo
254,657,102
false
null
class Solution { fun merge(intervals: Array<IntArray>): Array<IntArray> { intervals.sortWith(Comparator<IntArray> { o1, o2 -> when { o1[0] < o2[0] -> -1 o1[0] == o2[0] -> 0 else -> 1 } }) var index = 0 val merged = mutableListOf<IntArray>() intervals.forEach { if (merged.isEmpty() || merged[index - 1][1] < it[0]) { merged.add(it) index++ } else { merged[index - 1][1] = Math.max(merged[index - 1][1], it[1]) } } return merged.toTypedArray() } } fun main(args: Array<String>) { val solution = Solution() println(solution.merge(arrayOf(intArrayOf(1, 3), intArrayOf(2, 6), intArrayOf(8, 10), intArrayOf(15, 18))).map { it.contentToString() }) println(solution.merge(arrayOf(intArrayOf(1, 4), intArrayOf(4, 5))).map { it.contentToString() }) println(solution.merge(arrayOf(intArrayOf(1, 4), intArrayOf(0, 4))).map { it.contentToString() }) }
0
Kotlin
0
0
8f126ffdf75aa83a6d60689e0b6fcc966a173c70
962
coding-fun
MIT License
kotlin/app/bin/main/coverick/aoc/day12/hillClimbing.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day12 import java.util.PriorityQueue import readResourceFile val INPUT_FILE = "hillClimbing-input.txt" typealias Coordinate = Pair<Int,Int> data class Path(var current: Coordinate, val nodes:ArrayList<Coordinate>){} class Hill(val heightMap:List<CharArray>, val start: Char, val end:Char){ var startPos: Coordinate = Coordinate(0,0) var endPos: Coordinate = Coordinate(0,0) val unvisited = HashSet<Coordinate>() // determine start and end coordinates on grid init { for(i in 0..heightMap.size-1){ for(j in 0..heightMap.get(i).size - 1){ if(heightMap.get(i).get(j) == start){ startPos = Coordinate(i,j) } else if (heightMap.get(i).get(j) == end){ endPos = Coordinate(i,j) } unvisited.add(Coordinate(i,j)) } } println("Start height: ${getHeight(startPos)} endHeight: ${getHeight(endPos)}") } // replace heights of start and end with 'a' and 'z' respectively init { heightMap.get(startPos.first).set(startPos.second, 'a') heightMap.get(endPos.first).set(endPos.second, 'z') } fun getHeight(c:Coordinate) : Char { return heightMap.get(c.first).get(c.second) } fun isValidCoordinate(c:Coordinate): Boolean { return c.first >= 0 && c.first < heightMap.size && c.second >= 0 && c.second < heightMap.get(0).size } fun isValidMove(from:Coordinate, to:Coordinate): Boolean { val fromHeight = getHeight(from) val toHeight = getHeight(to) println("${from} ${fromHeight} , ${to} ${toHeight} (${toHeight - fromHeight})") return toHeight - fromHeight <= 1 && toHeight - fromHeight >= -1 } // return only unvisited adjacent nodes not including diagonals fun getNextMoves(c:Coordinate) : List<Coordinate>{ return hashSetOf( Coordinate(c.first + 1, c.second), Coordinate(c.first - 1, c.second), Coordinate(c.first, c.second - 1), Coordinate(c.first, c.second + 1) ).filter{ // unvisited.contains(it) && isValidCoordinate(it) && isValidMove(c,it)} } fun getShortestPathToEnd(): Int { val paths = PriorityQueue<Path>(compareBy({it.nodes.size})) paths.add(Path(startPos, arrayListOf(startPos))) val LIMITER = 10000000L // in case logic is screwed, avoids infinite while loop for(i in 0..LIMITER){ if(paths.size == 0){ println("Ran out of paths after ${i} iterations") break } val currentPath = paths.poll() println("Current path length: ${currentPath.nodes.size}") if(currentPath.current == endPos){ // don't count being on the end as a step, so -1 println("${currentPath}") return currentPath.nodes.size - 1 } val nextMoves = getNextMoves(currentPath.current).filter{!currentPath.nodes.contains(it)} if(nextMoves.size == 0){ println("Reached dead end at ${currentPath.current} for path ${currentPath.nodes}") } for(move in nextMoves){ val newPath = Path(move, ArrayList<Coordinate>()) newPath.nodes.addAll(currentPath.nodes) newPath.nodes.add(move) paths.add(newPath) unvisited.remove(move) // heightMap.get(currentPath.current.first).set(currentPath.current.second, '*') } } println("Hit rate limiter of ${LIMITER} without finding a valid path") for(r in heightMap){ println("${r.joinToString("")}") } return -1 } } fun part1():Int{ val heightMap = readResourceFile(INPUT_FILE).map{it.toCharArray()} val hill = Hill(heightMap, 'S', 'E') return hill.getShortestPathToEnd() } fun part2(): Int{ return 0 } fun solution(){ println("Hill Climbing Algorithm Part 1: ${part1()}") println("Hill Climbing Algorithm Part 2: ${part2()}") }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
4,196
adventofcode2022
Apache License 2.0
src/y2021/d02/Day02.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2021.d02 import println import readInput fun main() { val classPath = "y2021/d02" fun part1(input: List<String>): Int { var x = 0 var depth = 0 input. map { it.split(" ") }. forEach { val (action, value) = it when (action) { "forward" -> { x += value.toInt() } "down" -> { depth += value.toInt() } "up" -> { depth -= value.toInt() } } } return x * depth } fun part2(input: List<String>): Int { var x = 0 var depth = 0 var aim = 0 input. map { it.split(" ") }. forEach { val (action, value) = it when (action) { "forward" -> { x += value.toInt() depth += aim * value.toInt() } "down" -> { aim += value.toInt() } "up" -> { aim -= value.toInt() } } } return x * depth } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") part1(testInput).println() part2(testInput).println() // check(part1(testInput) == 1) println("Solutions:") val input = readInput("${classPath}/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
1,641
aoc
Apache License 2.0
src/plain/LogisticRegression.kt
philips-software
98,185,601
false
null
package plain class LogisticRegression { fun hessian(matrix: MatrixType): MatrixType { return -0.25 * (matrix.transpose() * matrix) } fun choleskyDecomposition(matrix: MatrixType): LowerTriangularMatrix { val d = matrix.numberOfRows val a = Array(d, { row -> Array(d, { column -> matrix[row, column] }) }) for (j in 0 until d) { for (k in 0 until j) { for (i in j until d) { a[i][j] -= a[i][k] * a[j][k] } } a[j][j] = Math.sqrt(a[j][j]) for (k in j + 1 until d) { a[k][j] /= a[j][j] } } return LowerTriangularMatrix(Matrix(*a)) } /** * Calculates the solution for the equation Lx=b, * using forward substitution. * * See also https://en.wikipedia.org/wiki/Triangular_matrix#Algorithm */ fun forwardSubstitution(L: LowerTriangularMatrix, b: Vector): Vector { val n = b.size val y = DoubleArray(n, { 0.0 }) for (i in 0 until n) { y[i] = b[i] for (j in 0 until i) { y[i] -= L[i, j] * y[j] } y[i] /= L[i, i] } return Vector(*y) } /** * Calculates the solution for the equation Ux=b, * using back substitution. * * See also https://en.wikipedia.org/wiki/Triangular_matrix#Algorithm */ fun backSubstitution(U: UpperTriangularMatrix, b: Vector): Vector { val n = b.size val x = DoubleArray(n, { 0.0 }) for (i in (0 until n).reversed()) { x[i] = b[i] for (j in i+1 until n) { x[i] -= U[i, j] * x[j] } x[i] /= U[i, i] } return Vector(*x) } fun likelihood(v1: Vector, v2: Vector): Double { val exponential = exp(-(v1 * v2)[0]) return 1.0 / (1.0 + exponential) } fun logLikelihoodPrime( x: MatrixType, y: Vector, beta: Vector): Vector { val result = DoubleArray(beta.size, { 0.0 }) for (k in 0 until beta.size) { for (i in 0 until x.numberOfRows) { result[k] += ( y[i] - likelihood(x.row(i), beta) ) * x[i,k] } } return Vector(*result) } fun updateLearnedModel(L: LowerTriangularMatrix, beta: Vector, l: Vector): Vector { val y = forwardSubstitution(L, l) val r = backSubstitution(L.transpose(), y) return beta + r } fun fitLogisticModel(Xs: Array<MatrixType>, Ys: Array<Vector>, lambda: Double = 0.0, numberOfIterations: Int = 10): Vector { var H: MatrixType? = null for (X in Xs) { val localH = hessian(X) if (H == null) { H = localH } else { H += localH } } if (H == null) { throw IllegalArgumentException("input must not be empty") } val I = IdentityMatrix(H.numberOfColumns) H -= lambda * I val L = choleskyDecomposition(-1.0 * H) var beta = Vector(*DoubleArray(H.numberOfColumns, { 0.0 })) for (i in 0 until numberOfIterations) { var lprime: Vector? = null for (party in 0 until Xs.size) { val X = Xs[party] val Y = Ys[party] val localLPrime = logLikelihoodPrime(X, Y, beta) if (lprime == null) { lprime = localLPrime } else { lprime += localLPrime } } if (lprime == null) { throw IllegalArgumentException("does not happen") } lprime -= (lambda * beta) beta = updateLearnedModel(L, beta, lprime) } return beta } }
0
Kotlin
2
0
3ae7aecd9383a9dd6a93666fb286b5480d5f6b67
4,031
Fresco-Logistic-Regression
MIT License
src/test/kotlin/org/jetbrains/research/ml/dataset/anonymizer/util/FileTestUtil.kt
JetBrains-Research
313,572,156
false
{"Kotlin": 49946, "Java": 6844}
package org.jetbrains.research.ml.dataset.anonymizer.util import java.io.File enum class Type { Input, Output } class TestFileFormat(private val prefix: String, private val extension: Extension, val type: Type) { data class TestFile(val file: File, val type: Type, val number: Number) fun check(file: File): TestFile? { val number = "(?<=${prefix}_)\\d+(?=(_.*)?${extension.value})".toRegex().find(file.name)?.value?.toInt() return number?.let { TestFile(file, type, number) } } fun match(testFile: TestFile): Boolean { return testFile.type == type } } object FileTestUtil { val File.content: String get() = this.readText().removeSuffix("\n") /** * We assume the format of the test files will be: * * inPrefix_i_anySuffix.inExtension * outPrefix_i_anySuffix.outExtension, * * where: * inPrefix and outPrefix are set in [inFormat] and [outFormat] together with extensions, * i is a number; two corresponding input and output files should have the same number, * suffixes can by any symbols not necessary the same for the corresponding files. */ fun getInAndOutFilesMap( folder: String, inFormat: TestFileFormat = TestFileFormat("in", Extension.CSV, Type.Input), outFormat: TestFileFormat = TestFileFormat("out", Extension.CSV, Type.Output) ): Map<File, File> { val (files, folders) = File(folder).listFiles().orEmpty().partition { it.isFile } // Process files in the given folder val inAndOutFilesGrouped = files.mapNotNull { inFormat.check(it) ?: outFormat.check(it) }.groupBy { it.number } val inAndOutFilesMap = inAndOutFilesGrouped.map { (number, fileInfoList) -> require(fileInfoList.size == 2) { "There are less or more than 2 test files with number $number" } val (f1, f2) = fileInfoList.sortedBy { it.type }.zipWithNext().first() require(inFormat.match(f1) && outFormat.match(f2)) { "Test files aren't paired with each other" } f1.file to f2.file }.sortedBy { it.first.name }.toMap() // Process all other nested files return folders.sortedBy { it.name }.map { getInAndOutFilesMap(it.absolutePath, inFormat, outFormat) } .fold(inAndOutFilesMap, { a, e -> a.plus(e) }) } }
3
Kotlin
0
0
d738818867038cea70db998c138091fbaa14e875
2,346
dataset-anonymizer
Apache License 2.0
kotlin/2021/qualification-round/cheating-detection/src/main/kotlin/MaximumLikelyhoodEstimationSolution.kts
ShreckYe
345,946,821
false
null
import kotlin.math.exp import kotlin.math.ln fun main() { val t = readLine()!!.toInt() val p = readLine()!!.toInt() repeat(t, ::testCase) } val maxAlpha = 1 val minAlpha = 1e-2 fun testCase(ti: Int) { val results = List(100) { readLine()!!.map { when (it) { '1' -> true '0' -> false else -> throw IllegalArgumentException() } } } // gradient ascend fun mleLnP(ss: DoubleArray, qs: DoubleArray, cheatingPlayerIndex: Int): Double = ss.flatMapIndexed { i, s -> qs.mapIndexed { j, q -> val isNotCheating = i != cheatingPlayerIndex val sigmoidSMinusQ = sigmoid(s - q) ln( if (results[i][j]) if (isNotCheating) sigmoidSMinusQ else (1 + sigmoidSMinusQ) / 2 else if (isNotCheating) 1 - sigmoidSMinusQ else (1 - sigmoidSMinusQ) / 2 ) } }.sum() fun mleLnPPartialDerivatives( ss: DoubleArray, qs: DoubleArray, cheatingPlayerIndex: Int ): Pair<List<Double>, List<Double>> { fun ijDerative(s: Double, q: Double, result: Boolean, isNotCheating: Boolean): Double { val sigmoidSMinusQ = sigmoid(s - q) return if (isNotCheating) if (result) 1 - sigmoidSMinusQ else -sigmoidSMinusQ else if (result) 1 - sigmoidSMinusQ.squared() / (1 + sigmoidSMinusQ) else 1 + sigmoidSMinusQ.squared() / (1 - sigmoidSMinusQ) } val cachedIjDeravative = ss.mapIndexed { i, s -> val isNotCheating = i != cheatingPlayerIndex qs.mapIndexed { j, q -> ijDerative(s, q, results[i][j], isNotCheating) }.toDoubleArray() }.toTypedArray() val pdss = ss.indices.map { i -> cachedIjDeravative[i].sum() } val pdqs = qs.indices.map { j -> -ss.indices.map { i -> cachedIjDeravative[i][j] }.sum() } return pdss to pdqs } val likelyhoods = (0 until 100).asSequence().map { cheatingPlayerIndex -> var ss = DoubleArray(100) { 0.0 } var qs = DoubleArray(10000) { 0.0 } var lnP = mleLnP(ss, qs, cheatingPlayerIndex) var alpha = maxAlpha while (true) { val (dss, dqs) = mleLnPPartialDerivatives(ss, qs, cheatingPlayerIndex) fun Double.coerceInRange() = coerceIn(-3.0, 3.0) val newSs = DoubleArray(100) { i -> (ss[i] + alpha * dss[i]).coerceInRange() } val newQs = DoubleArray(10000) { j -> (qs[j] + alpha * dqs[j]).coerceInRange() } val newLnP = mleLnP(ss, qs, cheatingPlayerIndex) /*println(cheatingPlayerIndex) println(lnP) println(alpha) println(ss.take(10)) println(dss.take(10)) println(qs.take(10)) println(dqs.take(10)) println(lnP) println()*/ if (newLnP > lnP) { ss = newSs qs = newQs lnP = newLnP } else { alpha /= 2 if (alpha < minAlpha) break } } lnP } val y = likelyhoods.withIndex().maxByOrNull { it.value }!!.index println("Case #${ti + 1}: ${y + 1}") } fun sigmoid(x: Double) = 1 / (1 + exp(-x)) fun Double.squared() = this * this /* \paragraph{If no player is cheating} $$ P_{ij} = P (X_{ij} = a_{ij}) = \begin{cases} f(S_i - Q_j), & a_{ij} = 1 \\ 1 - f(S_i - Q_j), & a_{ij} = 0 \end{cases}, \\ P = \prod_{i = 0, 1, ..., 99, j = 0, 1, ..., 9999} P_{ij}, \\ \max_{S_i (i = 0, 1, ..., 99), Q_j (j = 0, 1, ..., 9999)} P, \\ \ln P = \sum_{i = 0, 1, ..., 99, j = 0, 1, ..., 9999} \ln P_{ij}, $$ Let $$ g(x) = 1 - f(x), \\ h(x) = \ln f(x), \\ i(x) = \ln g(x), \\ h'(x) = 1 - f(x), \\ i'(x) = - f(x) $$ $$ \forall i: \frac{\partial{P}}{\partial{S_i}} = \sum_{A_{ij} = 1} h'(S_i - Q_j) + \sum_{A_{ij} = 0} i'(S_i - Q_j), \\ \forall j: \frac{\partial{P}}{\partial{Q_j}} = - (\sum_{A_{ij} = 1} h'(S_i - Q_j) + \sum_{A_{ij} = 0} i'(S_i - Q_j)) $$ \paragraph{If the $k$-th player is cheating} $$ P_{kj} = \begin{cases} \frac{1}{2} + \frac{1}{2} f(S_k - Q_j), & a_{kj} = 1 \\ \frac{1}{2} - \frac{1}{2} f(S_k - Q_j), & a_{kj} = 0 \end{cases} $$ $$ f_c(x) = \frac{1}{2} + \frac{1}{2} f(x) = \frac{1 + f(x)}{2}, \\ g_c(x) = \frac{1}{2} - \frac{1}{2} f(x) = \frac{1 - f(x)}{2}, \\ h_c(x) = \ln f_c(x) = \ln (1 + f(x)) - \ln 2, \\ i_c(x) = \ln g_c(x) = \ln (1 - f(x)) - \ln 2, \\ h_c'(x) = \frac{1 + f(x) (1 - f(x)}{1 + f(x)} = 1 - \frac{f(x)^2}{1 + f(x)}, \\ i_c'(x) = \frac{1 - f(x)(1 - f(x)}{1 - f(x)} = 1 + \frac{f(x)^2}{1 - f(x)} $$ */ main()
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
4,890
google-code-jam
MIT License
src/Day11.kt
zuevmaxim
572,255,617
false
{"Kotlin": 17901}
import java.util.* private class Monkey( val operation: (Long) -> Long, val divisor: Long, val trueMonkey: Int, val falseMonkey: Int, vararg elements: Int ) { private val items = LinkedList(elements.map { it.toLong() }.toList()) var inspections = 0L fun test(x: Long) = x.mod(divisor) == 0L fun hasItems() = items.isNotEmpty() fun process(monkeys: List<Monkey>, divide: Boolean, globalDivisor: Long) { inspections++ var e = items.removeFirst() % globalDivisor e = operation(e) if (divide) { e /= 3 } monkeys[if (test(e)) trueMonkey else falseMonkey].items.add(e) } } private fun List<Monkey>.round(divide: Boolean) { val globalDivisor = map { it.divisor }.fold(1L) { x, y -> x * y } for (m in this) { while (m.hasItems()) { m.process(this, divide, globalDivisor) } } } private fun part1(monkeys: List<Monkey>): Long { repeat(20) { monkeys.round(true) } val (t1, t2) = monkeys.map { it.inspections }.sortedDescending().take(2) return t1 * t2 } private fun part2(monkeys: List<Monkey>): Long { repeat(10000) { monkeys.round(false) } val (t1, t2) = monkeys.map { it.inspections }.sortedDescending().take(2) return t1 * t2 } fun main() { check( part1( listOf( Monkey({ it * 19 }, 23, 2, 3, 79, 98), Monkey({ it + 6 }, 19, 2, 0, 54, 65, 75, 74), Monkey({ it * it }, 13, 1, 3, 79, 60, 97), Monkey({ it + 3 }, 17, 0, 1, 74), ) ) == 10605L ) println( part1( listOf( Monkey({ it * 13 }, 19, 6, 2, 91, 66), Monkey({ it + 7 }, 5, 0, 3, 78, 97, 59), Monkey({ it + 6 }, 11, 5, 7, 57, 59, 97, 84, 72, 83, 56, 76), Monkey({ it + 5 }, 17, 6, 0, 81, 78, 70, 58, 84), Monkey({ it + 8 }, 7, 1, 3, 60), Monkey({ it * 5 }, 13, 7, 4, 57, 69, 63, 75, 62, 77, 72), Monkey({ it * it }, 3, 5, 2, 73, 66, 86, 79, 98, 87), Monkey({ it + 2 }, 2, 1, 4, 95, 89, 63, 67), ) ) ) check( part2( listOf( Monkey({ it * 19 }, 23, 2, 3, 79, 98), Monkey({ it + 6 }, 19, 2, 0, 54, 65, 75, 74), Monkey({ it * it }, 13, 1, 3, 79, 60, 97), Monkey({ it + 3 }, 17, 0, 1, 74), ) ) == 2713310158L ) println( part2( listOf( Monkey({ it * 13 }, 19, 6, 2, 91, 66), Monkey({ it + 7 }, 5, 0, 3, 78, 97, 59), Monkey({ it + 6 }, 11, 5, 7, 57, 59, 97, 84, 72, 83, 56, 76), Monkey({ it + 5 }, 17, 6, 0, 81, 78, 70, 58, 84), Monkey({ it + 8 }, 7, 1, 3, 60), Monkey({ it * 5 }, 13, 7, 4, 57, 69, 63, 75, 62, 77, 72), Monkey({ it * it }, 3, 5, 2, 73, 66, 86, 79, 98, 87), Monkey({ it + 2 }, 2, 1, 4, 95, 89, 63, 67), ) ) ) }
0
Kotlin
0
0
34356dd1f6e27cc45c8b4f0d9849f89604af0dfd
3,142
AOC2022
Apache License 2.0
src/Day01.kt
ig13
575,430,058
false
{"Kotlin": 1858}
import java.util.* /** * Day1 */ fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 val iter = input.iterator() while (iter.hasNext()) { val str = iter.next() if (str.isBlank()) { if (current > max) { max = current } current = 0 } else { val calories = str.toInt(10) current += calories } } if (current > max) { max = current } return max } fun part2(input: List<String>): Int { val set = TreeSet<Int> { a, b -> b - a } var current = 0 val iter = input.iterator() while (iter.hasNext()) { val str = iter.next() if (str.isBlank()) { set.add(current) current = 0 } else { val calories = str.toInt(10) current += calories } } return set.take(3).sumOf { it } } val input = readInput("Day01") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
cbf618a43737228189629d2f00d67972393125fc
1,210
Advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2020/Day17.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2020 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Point3D import com.chriswk.aoc.util.Point4D import com.chriswk.aoc.util.report class Day17: AdventDay(2020, 17) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day17() report { day.part1() } report { day.part2() } } } fun evaluatePoint(world: World, point: Point3D, currentState: Boolean): Cube { val activeNeighbourCount = point.neighbours.count { world.getOrDefault(it, false) } val newState = activeNeighbourCount == 3 || currentState && activeNeighbourCount == 2 return point to newState } fun evaluateHyperPoint(world: HyperWorld, point: Point4D, currentState: Boolean): HyperCube { val activeNeighbourCount = point.neighbours.count { world.getOrDefault(it, false) } val newState = when(currentState) { true -> activeNeighbourCount in 2..3 false -> activeNeighbourCount == 3 } return point to newState } fun gatherPointsToCheck(world: World): List<Point3D> { return world.entries.filter { it.value }.flatMap { it.key.neighbours }.distinct().toList() } fun gatherHyperPointsToCheck(world: HyperWorld): List<Point4D> { return world.entries.filter { it.value }.flatMap { it.key.neighbours }.distinct() } fun step(world: World): World { val allPoints = gatherPointsToCheck(world) return allPoints.map { point -> evaluatePoint(world, point, world.getOrDefault(point, false)) }.filter { it.second }.toMap() } fun hyperStep(world: HyperWorld): HyperWorld { val allPoints = gatherHyperPointsToCheck(world) return allPoints.map { p -> evaluateHyperPoint(world, p, world.getOrDefault(p, false)) }.filter { it.second }.toMap() } fun simulate(world: World, steps: Int): World { return generateSequence(world) { step(it) }.drop(steps).first() } fun simulateHyper(world: HyperWorld, steps: Int): HyperWorld { return generateSequence(world) { hyperStep(it) }.drop(steps).first() } fun cubes(input: List<String>): World { return input.flatMapIndexed { x, row -> row.mapIndexed { y, column -> Pair(Point3D(x, y, 0), column == '#') } }.toMap() } fun hyperCubes(input: List<String>): HyperWorld { return input.flatMapIndexed { x, row -> row.mapIndexed { y, column -> Pair(Point4D(x, y, 0, 0), column == '#') } }.toMap() } fun part1(): Int { return simulate(cubes(inputAsLines), 6).size } fun part2(): Int { return simulateHyper(hyperCubes(inputAsLines), 6).size } } typealias World = Map<Point3D, Boolean> typealias HyperWorld = Map<Point4D, Boolean> typealias HyperCube = Pair<Point4D, Boolean> typealias Cube = Pair<Point3D, Boolean>
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,128
adventofcode
MIT License
src/ch6Arrays/6.2IncrementArbitraryPrecisionNumber.kt
codingstoic
138,465,452
false
{"Kotlin": 17019}
package ch6Arrays fun main(args: Array<String>) { println(addOne(mutableListOf(1, 2, 9))) // 111 // 11 //1010 println(variantSumTwoBinary("111", "11", ::sumTwoBinaryStringsBitwise)) } fun addOne(list: MutableList<Int>): MutableList<Int> { for (i in (list.size - 1).downTo(0)) { if ((list[i] + 1) == 10) { list[i] = 0 } else { list[i] += 1 break } } if (list[0] == 10) { list[0] = 0 list.add(0, list[0] + 1) } return list } fun variantSumTwoBinary(b1: String, b2: String, calc: (a: String, b: String) -> String): String { return when { b1.length > b2.length -> { var b2Copy = b2 for (i in 0.until(b1.length - b2.length)) { b2Copy = "0$b2Copy" } calc(b1, b2Copy) } b2.length > b1.length -> { var b1Copy = b1 for (i in 0.until(b2.length - b1.length)) { b1Copy = "0$b1Copy" } calc(b2, b1Copy) } else -> calc(b2, b1) } } // hard coded version fun sumTwoBinaryStrings(b1: String, b2: String): String { var result = "" var carryOver = 0 for (i in (b1.length - 1).downTo(0)) { if (b1[i] == '1' && b2[i] == '1' && carryOver == 1) { result = '1' + result carryOver = 1 } else if (b1[i] == '1' && b2[i] == '1' && carryOver == 0) { result = '0' + result carryOver = 1 } else if (((b1[i] == '1' && b2[i] == '0') || (b1[i] == '0' && b2[i] == '1')) && carryOver == 1) { result = '0' + result carryOver = 1 } else if (((b1[i] == '1' && b2[i] == '0') || (b1[i] == '0' && b2[i] == '1')) && carryOver == 0) { result = '1' + result } else { result = '0' + result } } if (carryOver == 1) { result = '1' + result } return result } // simpler version fun sumTwoBinaryStringsBitwise(b1: String, b2: String): String { var result = "" var carryIn = 0 var carryOut: Int for (i in (b1.length - 1).downTo(0)) { val b1Int: Int = b1[i].toInt() - 48 val b2Int: Int = b2[i].toInt() - 48 carryOut = b1Int.and(b2Int).or(carryIn.and(b1Int)).or(carryIn.and(b2Int)) result = b1Int.xor(b2Int).xor(carryIn).toString() + result carryIn = carryOut } if (carryIn == 1) { result = "1$result" } return result } /* carry out current Bit a b cI R a b c r 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 1 0 1 1 0 1 0 1 0 1 1 1 0 0 1 1 0 1 0 0 */
0
Kotlin
0
2
fdec1aba315405e140f605aa00a9409746cb518a
2,689
elements-of-programming-interviews-solutions
MIT License
src/test/kotlin/dev/shtanko/algorithms/leetcode/NAryTreePreorderTraversalTest.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test abstract class NAryTreePreorderTraversalTest<out T : NAryTreePreorderTraversalStrategy>( private val strategy: T, ) { @Test fun `NAry tree preorder traversal test`() { val root = NAryNode(1) val third = NAryNode(3) third.children = listOf(NAryNode(5), NAryNode(6)) root.children = listOf(third, NAryNode(2), NAryNode(4)) val actual = strategy.preorder(root) assertEquals(listOf(1, 3, 5, 6, 2, 4), actual) } @Test fun `NAry tree preorder traversal 2 test`() { val root = NAryNode(1) val third = NAryNode(3) val seventh = NAryNode(7) val eleventh = NAryNode(11) seventh.children = listOf(eleventh) eleventh.children = listOf(NAryNode(14)) third.children = listOf(NAryNode(6), seventh) val fourth = NAryNode(4) val eight = NAryNode(8) fourth.children = listOf(eight) eight.children = listOf(NAryNode(12)) val fifth = NAryNode(5) val ninth = NAryNode(9) ninth.children = listOf(NAryNode(13)) fifth.children = listOf(ninth, NAryNode(10)) root.children = listOf(NAryNode(2), third, fourth, fifth) val actual = strategy.preorder(root) assertEquals(listOf(1, 2, 3, 6, 7, 11, 14, 4, 8, 12, 5, 9, 13, 10), actual) } } class NAryTreePreorderTraversalIterativeTest : NAryTreePreorderTraversalTest<NAryTreePreorderTraversalIterative>(NAryTreePreorderTraversalIterative()) class NAryTreePreorderTraversalRecursiveTest : NAryTreePreorderTraversalTest<NAryTreePreorderTraversalRecursive>(NAryTreePreorderTraversalRecursive())
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,375
kotlab
Apache License 2.0
src/commonMain/kotlin/org/mifek/wfc/utils/Formatters.kt
JakubMifek
326,496,922
false
null
package org.mifek.wfc.utils /** * Format waves * * @param waves * @return */ fun formatWaves(waves: Array<BooleanArray>): String { return " " + waves.indices.joinToString(" ") { idx -> val s = waves[idx].sumBy { when (it) { true -> 1 else -> 0 } } val r = when (s) { 0 -> "[XX]" 1 -> "[" + (if (waves[idx].withIndex().find { it.value }!!.index < 10) "0" + waves[idx].withIndex() .find { it.value }!!.index.toString() else waves[idx].withIndex() .find { it.value }!!.index.toString()) + "]" else -> " " + (if (s < 10) " $s" else s.toString()) + " " } if ((idx + 1) % 10 == 0) (r + "\n") else r } } /** * Format patterns * * @param patterns * @return */ fun formatPatterns(patterns: Array<IntArray>): String { return patterns.mapIndexed { index, it -> "$index:\n${it.joinToString(" ")}" }.joinToString("\n\n") } /** * Format propagator * * @param propagator * @return */ fun formatPropagator(propagator: Array<Array<IntArray>>): String { val x = " " var result = propagator[0].indices.joinToString(" ") { x.subSequence(0, x.length - it.toString().length).toString() + it.toString() } + "\n" val template = "00" for (dir in propagator.indices) { result += propagator[dir].joinToString(" ") { when { it.isEmpty() -> "[X]" it.size > 1 -> "[?]" else -> template.slice( 0 until (3 - it[0].toString().length) ) + it[0].toString() } } + "\n" } return result } /** * Format neighbours * * @param propagator * @return */ fun formatNeighbours(propagator: Array<Array<IntArray>>): String { var ret = "" for (patternIndex in propagator[0].indices) { ret += "Pattern $patternIndex:\n" for (dir in propagator.indices) { ret += "\t${propagator[dir][patternIndex].joinToString(", ")}\n" } ret += "\n" } return ret }
0
Kotlin
1
2
2e86233098bcf93ba506526e5ec8386da75eb2e5
2,212
WFC-Kotlin
MIT License
solutions/src/solutions/y21/day 3.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch", "UnusedImport") package solutions.y21.d3 import grid.Clock import helpers.Lines import helpers.e import helpers.getLines import helpers.transpose val xxxxx = Clock(6, 3); /* */ private fun part1(data: Data) { var transpose = data.e().transpose().map { it.map { i -> i - '0' } } val gamma = transpose.map { if (it.sum() * 2 > data.size) 1 else 0 }.reversed() var epsilon = gamma.map { 1 - it } // bin to value var g = gamma.mapIndexed { i, v -> if (v == 1) (1 shl i) else 0 }.sum() var e = epsilon.mapIndexed { i, v -> if (v == 1) (1 shl i) else 0 }.sum() println(g * e) } private fun part2(data: Data) { var oxygen = 0 var co2 = 0 var do2 = data var dco2 = data var x = 0 while (x <= data[0].length) { var transpose_o2 = do2.e().transpose().map { it.map { i -> i - '0' } } var transpose_co2 = dco2.e().transpose().map { it.map { i -> i - '0' } } val gamma = transpose_o2.map { if (it.sum() * 2 >= do2.size) 1 else 0 } var epsilon = transpose_co2.map { if (it.sum() * 2 < dco2.size) 1 else 0 } if(x < data[0].length){ do2 = do2.filter { (it[x] - '0') == gamma[x] } if (dco2.size > 1) dco2 = dco2.filter { (it[x] - '0') == epsilon[x] } } // bin to value oxygen = gamma.reversed().mapIndexed { i, v -> if (v == 1) (1 shl i) else 0 }.sum() co2 = epsilon.reversed().mapIndexed { i, v -> if (v == 0) (1 shl i) else 0 }.sum() x++ } println(oxygen * co2) } private typealias Data = Lines fun main() { val data: Data = getLines(2021_03) part1(data) part2(data) } fun <T> T.log(): T = also { println(this) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
1,737
AdventOfCodeSolutions
MIT License
2020/Day13/src/main/kotlin/main.kt
airstandley
225,475,112
false
{"Python": 104962, "Kotlin": 59337}
import java.io.File fun getInput(filename: String): List<String> { return File(filename).readLines() } fun parseInput(input: List<String>): Pair<Int, List<Int?>> { assert(input.size == 2) val timestamp: Int = input[0].toInt() val busIds = mutableListOf<Int?>() val ids: List<String> = input[1].split(',') for (id in ids) { if(id == "x") { busIds.add(null) } else { busIds.add(id.toInt()) } } return Pair(timestamp, busIds) } fun getNextBus(initialTimestamp: Int, ids: List<Int>): Pair<Int, Int> { // Return the Bus and Timestamp for the next available bus. var timestamp = initialTimestamp // If a bus doesn't depart by twice the initial then it probably never will. while (timestamp < initialTimestamp * 2) { val departingBuses = ids.filter { id -> (timestamp.rem(id) == 0) } if (!departingBuses.isEmpty()) { // Return the first match since the problem is set up in such // a wat that it's assume no id is a multiple of another id. return Pair(timestamp, departingBuses.first()) } timestamp++ } throw Exception("No departing bus found!") } const val ZERO: Long = 0 fun getSequentialTimestampBRUTE(ids: List<Int?>): Long { // Brute Force!!! var initialTimestamp: Long = 0 while (true) { var timestamp = initialTimestamp var match = true for (id in ids) { if (id != null) { if (timestamp.rem(id) != ZERO) { // Bus does not depart match = false break } } timestamp++ } if (match) { return initialTimestamp } initialTimestamp++ } } fun getSequentialTimestampBRUTE2(ids: List<Int?>): Long { val idGaps = mutableListOf<Pair<Int,Int>>() var gap = 1 for (id in ids) { if(id == null) { gap++ } else { idGaps.add(Pair(id, gap)) gap = 1 } } val multiples = mutableListOf<Int>() idGaps.forEach { id -> multiples.add(1) } var i = 1 while (i < idGaps.size) { if (i == 0){ i++ continue } val gap = idGaps[i].second val a = idGaps[i-1].first val b = idGaps[i].first if(a*multiples[i-1]+gap == b*multiples[i]) { //matched i++ } else if (a*multiples[i-1]+gap < b * multiples[i]) { // Check next departure of A multiples[i-1]++ i-- } else { // Check next departure of B multiples[i]++ } } return idGaps[0].first.toLong()*multiples[0].toLong() } const val ONE: Long = 1 fun modInverse(number:Long, mod: Long): Long { // xi[1] => 35xi ≡ 1 (mod 2) => xi ≡ 1 (mod 2) -> 1 (1%2=1) // xi[2] => 14xi ≡ 1 (mod 5) => 4xi ≡ 1 (mod 5) -> not 1, not 2, not 3, 4 (16%5=1) // xi[3] => 10xi ≡ 1 (mod 7) => 3xi ≡ 1 (mod 7) -> not 1, not 2, not 3, not 4, 5 (15%7=1) val target = number.rem(mod) for (i in 1..mod) { if ((target*i).rem(mod) == ONE) { return i } } throw Exception("No Inverse. Number: $number Mod: $mod") } fun chineseRemainder(congruences: List<Pair<Int, Int>>): Long { // Simultaneous congruences // t ≡ 0 (mod 2) // t ≡ 4 (mod 5) // t ≡ 5 (mod 7) // CRT (N=70) var bigN:Long = 1 congruences.forEach { congruence -> bigN *= congruence.second } // bi Ni xi bNx // 0 35 1 0 // 4 14 4 224 // 5 10 5 250 var sum: Long = 0 for (congruence in congruences) { val bi = congruence.first val bigNi = bigN/congruence.second val xi = modInverse(bigNi, congruence.second.toLong()) sum += (bi*bigNi*xi) } // 474 // t = 474 (mod 70) => t = 54 (55,56) return sum.rem(bigN) } fun getSequentialTimestamp(ids: List<Int?>): Long { // Cheat and check reddit to find out about a random theorem that I've never heard of that is apparently really // well know in modulo mathematics. (Because apparently that was supposed to be obvious). // Chinese Remainder Theorem time. // 2, 5 , 7 // Answer to 2, 5 is 2*t modulo 5 = -1 (2*3 = 9 mod 5 = -1) => (t ≡ -1 (mod 5) ) => (t ≡ 4 (mod 5) ) // Answer to 5, 7 is 5*t modulo 7 = -1 (5*4 = 20 mod 7 = -1) => (t+1 ≡ -1 (mod 7)) -> (t ≡ -2 (mod 7)) => (t ≡ 5 mod(7)) // 7,13,x,x,59,x,31,19 // t ≡ 0 (mod 7) // t+1 ≡ 0 (mod 13) => t ≡ -1 (mod 13) => t ≡ 12 (mod 13) // t+4 ≡ 0 (mod 59) => t ≡ -4 (mod 59) => t ≡ 55 (mod 59) val congruences = mutableListOf<Pair<Int, Int>>() for (i in ids.indices) { if (ids[i] != null) { val mod = ids[i] as Int var rem = 0 - i if (rem < 0) { rem += mod } congruences.add(Pair(rem, mod)) } } return chineseRemainder(congruences) } fun main(args: Array<String>) { val input = parseInput(getInput("Input")) val timestamp = input.first val ids = input.second val output = getNextBus(timestamp, ids.filter { id -> id != null } as List<Int>) val departing = output.first val bus = output.second val solutionOne = (departing - timestamp) * bus println("First Solution: $solutionOne") val solutionTwo = getSequentialTimestamp(ids) println("Second Solution: $solutionTwo") }
0
Python
0
0
86b7e289d67ba3ea31a78f4a4005253098f47254
5,577
AdventofCode
MIT License
modules/domain/src/main/kotlin/ru/astrainteractive/astrashop/domain/usecase/PriceCalculator.kt
Astra-Interactive
562,599,158
false
{"Kotlin": 93228}
package ru.astrainteractive.astrashop.domain.usecase import ru.astrainteractive.astrashop.api.model.ShopConfig import kotlin.math.sqrt object PriceCalculator { private fun sch(x: Double): Double { return 1 / kotlin.math.cosh(x) } /** * Calculated a median - threshold for item dynamic price */ private fun fMedian(x: Double): Double { return when { x <= 1 -> 50.0 x <= 10 -> x * sqrt(x) x <= 100 -> (x / (1.0 + x)) * sqrt(x) + x / 2 x <= 1000 -> (x / (1.0 + x)) * sqrt(x) else -> 2.0 } } /** * Calculate price depending on it's * [stock] - amount in shop * [price] - static price value */ private fun f(stock: Int, price: Double): Double { if (stock == -1) return price if (price <= 0) return 0.0 if (stock == 0) return 0.0 val median = fMedian(price) return sch(stock.toDouble() / median) * price } private fun getMinPrice(price: Double, amount: Int): Double { val powerOfTwo = kotlin.math.log2(amount.toDouble()).coerceAtLeast(2.0) val amountPowerOfE = kotlin.math.log10(amount.toDouble()).coerceAtLeast(2.0) return price / powerOfTwo / amountPowerOfE } private val ShopConfig.ShopItem.buyFromShopPrice: Double get() = price private val ShopConfig.ShopItem.playerSellPrice: Double get() = price * 0.95 /** * Calculate sell price from shop * * aka player buy from shop for this price */ fun calculateBuyPrice(item: ShopConfig.ShopItem, amount: Int): Double { if (!item.isForPurchase) return 0.0 if (item.stock == 0 && !item.isPurchaseInfinite) return 0.0 if (item.stock == -1) return item.buyFromShopPrice * amount val maxAmount = if (item.isPurchaseInfinite) amount else item.stock val coercedAmount = amount.coerceIn(0, maxAmount) return ((maxAmount - coercedAmount + 1)..maxAmount) .sumOf { stock -> f(stock, item.buyFromShopPrice).coerceAtLeast(getMinPrice(item.buyFromShopPrice, stock)) } } /** * Calculate sell price by player to shop * * aka player sell to shop for this price */ fun calculateSellPrice(item: ShopConfig.ShopItem, amount: Int): Double { if (!item.isForSell) return 0.0 if (item.stock == -1) return item.playerSellPrice * amount return ((item.stock + 1)..(item.stock + amount)) .sumOf { stock -> f(stock, item.playerSellPrice).coerceAtLeast(getMinPrice(item.playerSellPrice, stock)) } } }
0
Kotlin
1
0
b73cddc06d6f1d6ca4eff26cd99ead1921b3ab08
2,623
AstraShop
MIT License
scripts/Day22.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File val raw = File("../inputs/22.txt").readLines() val blankLineIndex = raw.indexOf("") sealed class Inst { object Left: Inst() object Right: Inst() data class Move(val n: Int): Inst() } val instructions = raw[blankLineIndex+1].replace("L", " L ").replace("R", " R ").split(" ").map { when (it) { "L" -> Inst.Left "R" -> Inst.Right else -> Inst.Move(it.toInt()) } } data class Pos(val x: Int, val y: Int) { operator fun plus(a: Pos) = Pos(x + a.x, y + a.y) } val map: MutableMap<Pos,Boolean> = mutableMapOf() for (y in 0 until blankLineIndex) { for (x in 0 until raw[y].length) { if (raw[y][x] == '#') map[Pos(x,y)] = true else if (raw[y][x] == '.') map[Pos(x,y)] = false } } val width = map.keys.maxOf { it.x } + 1 val height = map.keys.maxOf { it.y } + 1 // Index using a y value to get the minimum/maximum x value in that row val xMins = (0 until height).map { y -> (0 until width).first { x -> Pos(x,y) in map } } val xMaxes = (0 until height).map { y -> (0 until width).last { x -> Pos(x,y) in map } } // Index using an x value to get the minimum/maximum y value in that row val yMins = (0 until width).map { x -> (0 until height).first { y -> Pos(x,y) in map } } val yMaxes = (0 until width).map { x -> (0 until height).last { y -> Pos(x,y) in map } } val RIGHT = Pos(1,0) val LEFT = Pos(-1,0) val DOWN = Pos(0,1) val UP = Pos(0,-1) val start = Pos(xMins[0],0) val startingDir = RIGHT fun rotateRight(p: Pos) = when(p) { RIGHT -> DOWN DOWN -> LEFT LEFT -> UP UP -> RIGHT else -> Pos(0,0) } fun rotateLeft(p: Pos) = when(p) { RIGHT -> UP DOWN -> RIGHT LEFT -> DOWN UP -> LEFT else -> Pos(0,0) } fun canonicalDir(p: Pos) = when(p) { RIGHT -> 0 DOWN -> 1 LEFT -> 2 UP -> 3 else -> 0 } run { var pos = start var dir = startingDir for (i in instructions) { when (i) { is Inst.Left -> dir = rotateLeft(dir) is Inst.Right -> dir = rotateRight(dir) is Inst.Move -> { for (counter in 0 until i.n) { var nextPos = pos + dir if (dir.x != 0) { if (nextPos.x < xMins[pos.y]) nextPos = Pos(xMaxes[nextPos.y], nextPos.y) else if (nextPos.x > xMaxes[pos.y]) nextPos = Pos(xMins[nextPos.y], nextPos.y) } if (dir.y != 0) { if (nextPos.y < yMins[pos.x]) nextPos = Pos(nextPos.x, yMaxes[nextPos.x]) else if (nextPos.y > yMaxes[pos.x]) nextPos = Pos(nextPos.x, yMins[nextPos.x]) } assert (nextPos in map.keys) if (map[nextPos]!!) break pos = nextPos } } } } val endingColumn = pos.x + 1 val endingRow = pos.y + 1 val endingDir = canonicalDir(dir) val result = endingRow * 1000 + endingColumn * 4 + endingDir println("Final column: $endingColumn, Final row: $endingRow, Final dir: $endingDir, Password: <PASSWORD>") } run { var pos = start var dir = startingDir for (i in instructions) { when (i) { is Inst.Left -> dir = rotateLeft(dir) is Inst.Right -> dir = rotateRight(dir) is Inst.Move -> { for (counter in 0 until i.n) { var nextPos = pos + dir var nextDir = dir // we do a little bit of hardcoding // my cube looks like this (1 through E are edge labels, # are faces, | and - are connected edges): // 6 7 // 5#-#8 // | 9 // 4#A // 3 | // 2#-#B // | C // 1#D // E if (nextPos !in map) { if (nextPos.x == -1 && nextPos.y in 150..199 && dir == LEFT) {nextPos = Pos(nextPos.y-100,0); nextDir = DOWN} else if (nextPos.x == -1 && nextPos.y in 100..149 && dir == LEFT) {nextPos = Pos(50,149-nextPos.y); nextDir = RIGHT} else if (nextPos.y == 99 && nextPos.x in 0..49 && dir == UP) {nextPos = Pos(50,50+nextPos.x); nextDir = RIGHT} else if (nextPos.x == 49 && nextPos.y in 50..99 && dir == LEFT) {nextPos = Pos(nextPos.y-50,100); nextDir = DOWN} else if (nextPos.x == 49 && nextPos.y in 0..49 && dir == LEFT) {nextPos = Pos(0,149-nextPos.y); nextDir = RIGHT} else if (nextPos.y == -1 && nextPos.x in 50..99 && dir == UP) {nextPos = Pos(0,nextPos.x+100); nextDir = RIGHT} else if (nextPos.y == -1 && nextPos.x in 100..149 && dir == UP) {nextPos = Pos(nextPos.x-100,199); nextDir = UP} else if (nextPos.x == 150 && nextPos.y in 0..49 && dir == RIGHT) {nextPos = Pos(99,149-nextPos.y); nextDir = LEFT} else if (nextPos.y == 50 && nextPos.x in 100..149 && dir == DOWN) {nextPos = Pos(99,nextPos.x-50); nextDir = LEFT} else if (nextPos.x == 100 && nextPos.y in 50..99 && dir == RIGHT) {nextPos = Pos(nextPos.y+50,49); nextDir = UP} else if (nextPos.x == 100 && nextPos.y in 100..149 && dir == RIGHT) {nextPos = Pos(149,149-nextPos.y); nextDir = LEFT} else if (nextPos.y == 150 && nextPos.x in 50..99 && dir == DOWN) {nextPos = Pos(49,nextPos.x+100); nextDir = LEFT} else if (nextPos.x == 50 && nextPos.y in 150..199 && dir == RIGHT) {nextPos = Pos(nextPos.y-100,149); nextDir = UP} else if (nextPos.y == 200 && nextPos.x in 0..49 && dir == DOWN) {nextPos = Pos(nextPos.x+100,0); nextDir = DOWN} else throw Exception("Unhandled movement out of bounds: $nextPos, $dir") } if (map[nextPos]!!) break pos = nextPos dir = nextDir } } } } val endingColumn = pos.x + 1 val endingRow = pos.y + 1 val endingDir = canonicalDir(dir) val result = endingRow * 1000 + endingColumn * 4 + endingDir println("Final column: $endingColumn, Final row: $endingRow, Final dir: $endingDir, Password: $<PASSWORD>") }
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
6,634
adventofcode2022
MIT License
y2021/src/main/kotlin/adventofcode/y2021/Day06.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day06 : AdventSolution(2021, 6, "Lanternfish") { override fun solvePartOne(input: String) = solve(input, 80) override fun solvePartTwo(input: String) = solve(input, 256) private fun solve(input: String, days: Int): Long { val parsed: Map<Int, Int> = parseInput(input) val fish = List(9) { parsed[it]?.toLong() ?: 0L } return generateSequence(fish, ::next).elementAt(days).sum() } private fun next(fish: List<Long>) = List(9) { when (it) { 8 -> fish[0] 6 -> fish[0] + fish[it + 1] else -> fish[it + 1] } } private fun parseInput(input: String) = input.split(',') .map { it.toInt() } .groupingBy { it } .eachCount() }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
841
advent-of-code
MIT License
src/com/crossbowffs/ccikotlin/chapter2/5-SumLists.kt
apsun
63,534,825
false
null
package com.crossbowffs.ccikotlin.chapter2 import com.crossbowffs.ccikotlin.utils.doAssert /** * Calculates the sum of a linked list of decimal digits. * The least significant digit comes first, i.e. 1->2->3 * is equal to 321. The result is returned in a new linked * list with the same format. If the result equals zero, * null is returned. */ fun sumListsReverse(a: LinkedNode<Int>?, b: LinkedNode<Int>?): LinkedNode<Int>? { // This version uses a recursive full-adder algorithm to // add each digit together. We can begin "merging" the nodes // immediately since the least significant digit is at the // beginning. This version is not limited by the size of the // integer, since the digits are added together directly. fun helper(a: LinkedNode<Int>?, b: LinkedNode<Int>?, carry: Int): LinkedNode<Int>? { if (a == null && b == null && carry == 0) return null var sum = carry if (a != null) sum += a.data if (b != null) sum += b.data val next = helper(a?.next, b?.next, sum / 10) if (next == null && sum == 0) { return null } val node = LinkedNode(sum % 10) node.next = next return node } return helper(a, b, 0) } /** * Calculates the sum of a linked list of decimal digits. * The most significant digit comes first, i.e. 1->2->3 * is equal to 123. The result is returned in a new linked * list with the same format. If the result equals zero, * null is returned. */ fun sumListsForward(a: LinkedNode<Int>?, b: LinkedNode<Int>?): LinkedNode<Int>? { // This version converts each list to an integer, adds the // results, then converts the sum into a new list. This is // necessary since we don't know the length of each list // in advance, so we cannot know whether the digits of the // two lists are aligned or not without first iterating the // entire list. This version is limited by the size of // an integer (so arbitrary-precision addition is not possible). fun listToInt(node: LinkedNode<Int>?): Pair<Int, Int> { if (node == null) return 0 to 1 val (digit, base) = listToInt(node.next) return (node.data * base + digit) to (base * 10) } var sum = listToInt(a).first + listToInt(b).first var prev: LinkedNode<Int>? = null while (sum != 0) { val curr = LinkedNode(sum % 10) sum /= 10 curr.next = prev prev = curr } return prev } fun main(args: Array<String>) { sumListsReverse(linkedListOf(), linkedListOf()).apply { doAssert(linkedListEquals()) } sumListsReverse(linkedListOf(), linkedListOf(0)).apply { doAssert(linkedListEquals()) } sumListsReverse(linkedListOf(1, 2, 3), linkedListOf(9, 9, 9)).apply { doAssert(linkedListEquals(0, 2, 3, 1)) } sumListsReverse(linkedListOf(1, 2), linkedListOf(9, 9, 0, 0)).apply { doAssert(linkedListEquals(0, 2, 1)) } sumListsForward(linkedListOf(), linkedListOf()).apply { doAssert(linkedListEquals()) } sumListsForward(linkedListOf(), linkedListOf(0)).apply { doAssert(linkedListEquals()) } sumListsForward(linkedListOf(1, 2, 3), linkedListOf(9, 9, 9)).apply { doAssert(linkedListEquals(1, 1, 2, 2)) } sumListsForward(linkedListOf(0, 0, 0, 1, 2), linkedListOf(9, 9, 0, 0)).apply { doAssert(linkedListEquals(9, 9, 1, 2)) } }
0
Kotlin
0
3
b72075c54277e8cefef4b491cee6383413cb28e0
3,450
CCIKotlin
MIT License
yandex/y2022/qual/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2022.qual import kotlin.random.Random fun main() { val (n, q) = readInts() val dsu = DisjointSetUnionRPS(n) val three = IntArray(n + 1) three[0] = 1 for (i in 1 until three.size) three[i] = (3 * three[i - 1].toModular()).x repeat(q) { val (uIn, vIn, resultIn) = readStrings() val u = uIn.toInt() - 1 val v = vIn.toInt() - 1 val result = "LDW".indexOf(resultIn) - 1 dsu.unite(u, v, result) println(if (dsu.broken) 0 else three[dsu.degrees]) } } private class DisjointSetUnionRPS(n: Int) { val p: IntArray val diffP: IntArray val r: Random = Random(566) var broken: Boolean var degrees: Int init { p = IntArray(n) for (i in p.indices) { p[i] = i } diffP = IntArray(n) broken = false degrees = n } operator fun get(v: Int): Pair<Int, Int> { if (p[v] == v) return v to 0 val (r, diffR) = get(p[v]) p[v] = r diffP[v] += diffR return p[v] to diffP[v] } fun unite(u: Int, v: Int, d: Int) { val (uu, diffU) = get(u) val (vv, diffV) = get(v) if (vv == uu) { if ((diffU - diffV - d) % 3 != 0) broken = true return } degrees-- if (r.nextBoolean()) { p[vv] = uu diffP[vv] = diffU - diffV - d } else { p[uu] = vv diffP[uu] = diffV - diffU + d } } } private fun Int.toModular() = Modular(this)//toDouble() private class Modular { companion object { const val M = 1_000_000_007 } val x: Int @Suppress("ConvertSecondaryConstructorToPrimary") constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } } operator fun plus(that: Modular) = Modular((x + that.x) % M) operator fun minus(that: Modular) = Modular((x + M - that.x) % M) operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular() private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt()) operator fun div(that: Modular) = times(that.modInverse()) override fun toString() = x.toString() } private operator fun Int.plus(that: Modular) = Modular(this) + that private operator fun Int.minus(that: Modular) = Modular(this) - that private operator fun Int.times(that: Modular) = Modular(this) * that private operator fun Int.div(that: Modular) = Modular(this) / that private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,345
competitions
The Unlicense
src/main/aoc2023/Day11.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 import AMap import Pos class Day11(input: List<String>) { private val universe = AMap.parse(input, listOf('.')) private fun expand(expansionFactor: Int): AMap { val expandedUniverse = AMap() var expandedX = 0 var expandedY = 0 val columnIsEmpty = universe.xRange().associateWith { x -> universe.keys.none { it.x == x } } for (y in universe.yRange()) { val rowIsEmpty = universe.keys.none { it.y == y } // when row is empty expand instead of processing row if (rowIsEmpty) { expandedY += expansionFactor continue } for (x in universe.xRange()) { val curr = universe[Pos(x, y)] if (curr != null) { expandedUniverse[Pos(expandedX, expandedY)] = curr } expandedX += if (columnIsEmpty[x]!!) expansionFactor else 1 } expandedX = 0 expandedY++ } return expandedUniverse } private fun pairs(keys: Set<Pos>) = buildSet { keys.forEach { a -> keys.forEach { b -> if (a != b) { add(setOf(a, b)) } } } } private fun calculateSum(universe: AMap) = pairs(universe.keys).sumOf { it.first().distanceTo(it.last()).toLong() } fun solvePart1(): Long { return calculateSum(expand(2)) } fun solvePart2(expansionFactor: Int = 1_000_000): Long { return calculateSum(expand(expansionFactor)) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,609
aoc
MIT License
src/main/kotlin/day3/Day3.kt
Mee42
433,459,856
false
{"Kotlin": 42703, "Java": 824}
package dev.mee42.day3 import dev.mee42.*; fun main() { val input = inputLines(day = 3, year = 2021,) fun findLevel(inverse: Boolean) = (0 until input[0].length).toList().foldr(input) { validNumbers, index -> val selection = (validNumbers.map { it[index] }.count { it == '1' } > (validNumbers.size - 1) / 2) .xor(inverse) validNumbers .apIf(validNumbers.size > 1) { validNumbers.filter { it[index] == '1' == selection } } }[0].toInt(radix = 2) val o2 = findLevel(false) val co2 = findLevel(true) println(o2 * co2) } fun main1() { val input = inputLines(day = 3, year = 2021) val eps = input.transpose().map { list -> if(list.count { it == '1' } > input.size / 2) '1' else '0' } val gam = eps.map { if(it == '1') '0' else '1' }.charListToString() println(eps.charListToString().toInt(2) * gam.toInt(2)) }
0
Kotlin
0
0
db64748abc7ae6a92b4efa8ef864e9bb55a3b741
919
aoc-2021
MIT License
test/highlight/kotlin/Test.kt
HiPhish
661,447,423
false
{"Lua": 125127, "Scheme": 53074, "Janet": 5133, "SystemVerilog": 3912, "C#": 3595, "Rust": 3478, "Jsonnet": 2953, "TypeScript": 2768, "Shell": 2350, "Kotlin": 2276, "Vim Script": 2156, "Makefile": 2017, "Zig": 2017, "Go": 2012, "Fennel": 1912, "HCL": 1688, "JavaScript": 1650, "Java": 1576, "Elm": 1532, "Dart": 1437, "Vue": 1392, "C": 1367, "Cuda": 1310, "Nix": 1173, "C++": 1129, "Haskell": 1099, "TeX": 1008, "Verilog": 960, "Perl": 958, "Elixir": 820, "Astro": 812, "Python": 807, "Starlark": 788, "Racket": 782, "HTML": 674, "Nim": 673, "PHP": 626, "Ruby": 468, "SCSS": 351, "CUE": 349, "CSS": 290, "R": 271, "Common Lisp": 227, "Clojure": 189, "Julia": 101}
// Define a simple class with a primary constructor class Person<T>(private val name: String, private val age: Int, private val t: T) { // Secondary constructor constructor(name: String) : this(name, 0) class Hello { class Goodbye { } } init { println("New person created with name $name") } // Member function fun greet() { println("Hello, my name is $name and I am $age years old.") } } // Extension function fun String.exclaim() = "$this!" // Top-level function fun calculateFactorial(n: Int): Int { return if (n == 1) n else n * calculateFactorial(n - 1) } // Main function - entry point of the program fun main() { val person = Person<Map<String, String>>("Alice", 30, emptyMap()) person.greet() // Using the extension function println("Wow".exclaim()) // Conditional val number = 5 if (number % 2 == 0) { println("$number is even") } else { println("$number is odd") } // Loop for (i in 1..5) { println("Factorial of $i is: ${calculateFactorial(i)}") } // Using a map val map = mapOf("a" to 1, "b" to 2, "c" to 3) for ((key, value) in map) { println("Key: $key, Value: $value") } // Lambda expression val numbers = listOf(1, 2, 3, 4, 5) val doubled = numbers.map { it * 2 } println("Doubled numbers: $doubled") } val list = listOf(1, 2, 3) list.forEach { item -> println(item) } fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int { return operation(a, b) } val sum = operateOnNumbers(2, 3) { x, y -> x + y } println("Sum: $sum") val multiply = fun(x: Int, y: Int): Int { return x * y } println("Product: ${multiply(2, 3)}") val x = 2 when (x) { 1 -> println("x == 1") 2 -> println("x == 2") else -> println("x is neither 1 nor 2") } when { 1 == 1 -> print("1") else -> print("not") } val rows = 2 val cols = 3 val matrix = Array(rows) { IntArray(cols) } // Fill the array for (i in matrix.indices) { for (j in matrix[i].indices) { matrix[i][j] = i + j } matrix[matrix[i][i]] } // Print the 2D array for (row in matrix) { for (col in row) { print("$col ") } println() }
9
Lua
24
328
ca8d5ee2b4ee1eec491040a7601d366ddc8a2e02
2,276
rainbow-delimiters.nvim
Apache License 2.0
src/main/kotlin/aoc2019/day04_secure_container/SecureContainer.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2019.day04_secure_container fun main() { util.solve(1716, ::partOne) util.solve(1163, ::partTwo) } internal fun Int.isValidPassword(): Boolean { if (this < 100_000 || this > 999_999) return false var next = mod(10) var n = div(10) var hasDouble = false for (i in 4 downTo 0) { val curr = n % 10 if (curr > next) { return false } if (curr == next) { hasDouble = true } next = curr n /= 10 } return hasDouble } private fun String.toRange(): IntRange { val (start, end) = lines() .first() .split("-") .map { it.toInt() } return start..end } fun partOne(input: String) = input.toRange().count(Int::isValidPassword) internal fun Int.isMoreValidPassword(): Boolean { if (this < 100_000 || this > 999_999) return false var next = mod(10) var n = div(10) var hasDouble = false var runLen = 1 for (i in 4 downTo 0) { val curr = n % 10 if (curr > next) { return false } if (curr == next) { ++runLen } else { if (runLen == 2) { hasDouble = true } runLen = 1 } next = curr n /= 10 } if (runLen == 2) { hasDouble = true } return hasDouble } fun partTwo(input: String) = input.toRange().count(Int::isMoreValidPassword)
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
1,466
aoc-2021
MIT License
src/main/kotlin/info/benjaminhill/fm/chopper/TimedEvent.kt
salamanders
469,162,795
false
{"Kotlin": 52730, "Shell": 1382}
package info.benjaminhill.fm.chopper import java.time.Duration import java.time.Instant /** * A timed event is a pair of "stuff (state) that happened at time (ts)" * The idea is to keep a collection (ArrayDeque?) of these to record when things first happened. */ data class InstantState<T>( val ts: Instant, val state: T, ) data class DurationState<T>( val duration: Duration, val state: T, ) fun <T> List<InstantState<T>>.toDurations( contiguous: Boolean = false, maxTtl: Duration ) = if (contiguous) { maxContiguousDurations(maxTtl) } else { sumDurations(maxTtl) } private fun <T> List<InstantState<T>>.sumDurations( maxTtl: Duration, ): List<DurationState<T>> = this.asSequence().zipWithNext().map { (is0, is1) -> DurationState( state = is0.state, duration = Duration.between(is0.ts, is1.ts).coerceAtMost(maxTtl), ) }.groupingBy { it.state } .fold(Duration.ZERO) { acc, elt -> acc + elt.duration }.map { DurationState( duration = it.value, state = it.key ) }.toList() /** * Longest contiguous duration */ private fun <T> List<InstantState<T>>.maxContiguousDurations( maxTtl: Duration, ): List<DurationState<T>> { val maxContiguous = mutableMapOf<T, Duration>() this.distinctBy { it.state }.forEach { maxContiguous[it.state] = Duration.ZERO } var currentState: T? = null var currentDuration: Duration = Duration.ZERO this.zipWithNext().forEach { (event0, event1): Pair<InstantState<T>, InstantState<T>> -> val (ts0, state0) = event0 val (ts1, _) = event1 if (currentState != state0) { currentState = state0 currentDuration = Duration.ZERO } currentDuration += Duration.between(ts0, ts1).coerceAtMost(maxTtl) if (currentDuration > maxContiguous[currentState]) { maxContiguous[currentState!!] = currentDuration } } return maxContiguous.map { DurationState( duration = it.value, state = it.key ) } }
0
Kotlin
1
0
c19094a521cb7afb608e67d11657897dc74b79c4
2,170
nrsc5-chopper
MIT License
src/Day03.kt
timlam9
573,013,707
false
{"Kotlin": 9410}
fun main() { fun part1(input: List<String>): Int = input.fold(0) { sum: Int, rucksack: String -> sum + rucksack.getCommonItemPriority() } fun part2(input: List<String>): Int = input.chunked(3).fold(0) {sum: Int, group: List<String> -> sum + group.getGroupItemPriority() } val input = readInput("Day03") println(part1(input)) println(part2(input)) } private val Char.toPriority: Int get() = Priority.valueOf(this.toString()).value private fun String.getCommonItemPriority() = chunked(length / 2).run { val firstCompartment = first().toSet() val secondCompartment = last().toSet() val commonItem = firstCompartment.intersect(secondCompartment).first() commonItem.toPriority } private fun List<String>.getGroupItemPriority(): Int { val firstRucksack = this[0].toSet() val secondRucksack = this[1].toSet() val thirdRucksack = this[2].toSet() return firstRucksack.intersect(secondRucksack).intersect(thirdRucksack).first().toPriority } enum class Priority(val value: Int) { a(1), b(2), c(3), d(4), e(5), f(6), g(7), h(8), i(9), j(10), k(11), l(12), m(13), n(14), o(15), p(16), q(17), r(18), s(19), t(20), u(21), v(22), w(23), x(24), y(25), z(26), A(27), B(28), C(29), D(30), E(31), F(32), G(33), H(34), I(35), J(36), K(37), L(38), M(39), N(40), O(41), P(42), Q(43), R(44), S(45), T(46), U(47), V(48), W(49), X(50), Y(51), Z(52), }
0
Kotlin
0
0
1df3465966915590022981546659ee4f1cdeb33b
1,622
AdventOfCodeKotlin2022
Apache License 2.0
grind-75-kotlin/src/main/kotlin/ValidAnagram.kt
Codextor
484,602,390
false
{"Kotlin": 27206}
/** * Given two strings s and t, return true if t is an anagram of s, and false otherwise. * * An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, * typically using all the original letters exactly once. * * * * Example 1: * * Input: s = "anagram", t = "nagaram" * Output: true * Example 2: * * Input: s = "rat", t = "car" * Output: false * * * Constraints: * * 1 <= s.length, t.length <= 5 * 10^4 * s and t consist of lowercase English letters. * * * Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case? * @see <a href="https://leetcode.com/problems/valid-anagram/">LeetCode</a> */ fun isAnagram(s: String, t: String): Boolean { if (s.length != t.length) { return false } val map = HashMap<Char, Int>() for (character in s) { map.put(character, map.getOrDefault(character, 0) + 1) } for (character in t) { if (!map.contains(character) || map.get(character) == 0) { return false } else { map.put(character, map.getOrDefault(character, 1) - 1) } } return true }
0
Kotlin
0
0
87aa60c2bf5f6a672de5a9e6800452321172b289
1,184
grind-75
Apache License 2.0
src/Day01.kt
psy667
571,468,780
false
{"Kotlin": 23245}
fun main() { val id = "01" fun getElvesWeights(input: List<String>): List<Int> { return input .joinToString("\n") .split("\n\n") .map { it .split("\n") .map(String::toInt) .sum() } } fun part1(input: List<String>): Int { return getElvesWeights(input).max() } fun part2(input: List<String>): Int { return getElvesWeights(input) .sortedDescending() .take(3) .sum() } val testInput = readInput("Day${id}_test") check(part1(testInput) == 24000) val input = readInput("Day${id}") println("==== DAY ${id} ====") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
73a795ed5e25bf99593c577cb77f3fcc31883d71
791
advent-of-code-2022
Apache License 2.0
leetcode2/src/leetcode/sum-of-two-integers.kt
hewking
68,515,222
false
null
package leetcode /** * 371. 两整数之和 * https://leetcode-cn.com/problems/sum-of-two-integers/ * Created by test * Date 2019/7/19 0:59 * Description * 不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。 示例 1: 输入: a = 1, b = 2 输出: 3 示例 2: 输入: a = -2, b = 3 输出: 1 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-of-two-integers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object SumOfTwoIntegers { class Solution { /** * 思路: * 1. 异或^是不进位加法 * 2. & 是进位 */ fun getSum(a: Int, b: Int): Int { if (a == 0) { return b } if ( b == 0) { return a } var nb = b var na = a while (nb != 0) { var tmp = na.xor(nb) nb = na.and(nb).shl(1) na = tmp } return na } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,146
leetcode
MIT License
src/main/kotlin/space/d_lowl/kglsm/iterativeimprovement/strategy/IterativeImprovementStrategy.kt
d-lowl
300,622,439
false
null
package space.d_lowl.kglsm.iterativeimprovement.strategy import space.d_lowl.kglsm.general.memory.BasicSolution import space.d_lowl.kglsm.general.memory.Memory import space.d_lowl.kglsm.problem.CostFunction import space.d_lowl.kglsm.general.space.SearchSpace import space.d_lowl.kglsm.general.strategy.Strategy /** * Enum representing mode of Iterative Improvement algorithm */ enum class IIMode { BEST, FIRST } /** * Iterative Improvement strategy * * @param[T] Solution entity type * @param[mode] Iterative Improvement strategy mode * @param[updateBest] flag, set true to update best solution after the step */ class IterativeImprovementStrategy<T>(private val mode: IIMode, private val updateBest: Boolean = true) : Strategy<T, BasicSolution<T>>() { /** * If there's a neighbouring solution that improves the current cost, select the next solution according to the [mode]: * - [IIMode.BEST] -- the best improvement * - [IIMode.FIRST] -- the first improvement * * @param[memory] memory * @param[searchSpace] search space for a problem instance * @param[costFunction] cost function of a problem instance */ override fun step(memory: Memory<T, BasicSolution<T>>, searchSpace: SearchSpace<T>, costFunction: CostFunction<T>) { val neighbourhood = searchSpace.getNeighbourhood(memory.currentSolution.solution) val bestCost = memory.currentSolution.cost var newSolution = memory.currentSolution when (mode) { IIMode.FIRST -> { for (neighbour in neighbourhood) { val cost = costFunction(neighbour) if (cost < bestCost) { newSolution = BasicSolution(neighbour, cost) break } } } IIMode.BEST -> { val neighbourhoodSolutions = neighbourhood .map { costFunction(it) } .zip(neighbourhood) .map { BasicSolution(it.second, it.first) } val improvement = neighbourhoodSolutions.filter { it.cost < bestCost }.toList() newSolution = if (improvement.isEmpty()) { memory.currentSolution } else { improvement.minBy { it.cost }!! } } } memory.update(newSolution) if (updateBest) memory.updateBest() } override fun toString(): String { val subtype = when (mode) { IIMode.BEST -> "Best" IIMode.FIRST -> "First" } return "$subtype Iterative Improvement${if (updateBest) " [updating best]" else ""}" } }
17
Kotlin
0
1
0886e814be75a77fa8f33faa867329aef19085a5
2,745
kGLSM
MIT License
backtracking/sudoku/kotlin/Sudoku.kt
ZoranPandovski
93,438,176
false
{"Jupyter Notebook": 21909905, "C++": 1692994, "Python": 1158220, "Java": 806066, "C": 560110, "JavaScript": 305918, "Go": 145277, "C#": 117882, "PHP": 85458, "Kotlin": 72238, "Rust": 53852, "Ruby": 43243, "MATLAB": 34672, "Swift": 31023, "Processing": 22089, "HTML": 18961, "Haskell": 14298, "Dart": 11842, "CSS": 10509, "Scala": 10277, "Haxe": 9750, "PureScript": 9122, "M": 9006, "Perl": 8685, "Prolog": 8165, "Shell": 7901, "Erlang": 7483, "Assembly": 7284, "R": 6832, "Lua": 6392, "LOLCODE": 6379, "VBScript": 6283, "Clojure": 5598, "Elixir": 5495, "OCaml": 3989, "Crystal": 3902, "Common Lisp": 3839, "Julia": 3567, "F#": 3376, "TypeScript": 3268, "Nim": 3201, "Brainfuck": 2466, "Visual Basic .NET": 2033, "ABAP": 1735, "Pascal": 1554, "Groovy": 976, "COBOL": 887, "Mathematica": 799, "Racket": 755, "PowerShell": 708, "Ada": 490, "CMake": 393, "Classic ASP": 339, "QMake": 199, "Makefile": 111}
/** * @author https://github.com/jeffament/ */ private const val EMPTY_CELL = 0 fun main(args: Array<String>) { val board = arrayOf( intArrayOf(8, 0, 0, 0, 0, 0, 0, 0, 0), intArrayOf(0, 0, 3, 6, 0, 0, 0, 0, 0), intArrayOf(0, 7, 0, 0, 9, 0, 2, 0, 0), intArrayOf(0, 5, 0, 0, 0, 7, 0, 0, 0), intArrayOf(0, 0, 0, 0, 4, 5, 7, 0, 0), intArrayOf(0, 0, 0, 1, 0, 0, 0, 3, 0), intArrayOf(0, 0, 1, 0, 0, 0, 0, 6, 8), intArrayOf(0, 0, 8, 5, 0, 0, 0, 1, 0), intArrayOf(0, 9, 0, 0, 0, 0, 4, 0, 0) ) if (solvePuzzle(board)) { println("Puzzle solved successfully!\n") printPuzzle(board) } else print("No solution is available for this puzzle!") } // solves the puzzle by recursively backtracking until a solution is found or all possibilities have been exhausted private fun solvePuzzle(array: Array<IntArray>): Boolean { val locationOfEmptyCell = arrayOf(0, 0) if (!findNextEmptyCell(array, locationOfEmptyCell)) return true val row = locationOfEmptyCell[0] val column = locationOfEmptyCell[1] for (numChoice in 1..9) { if (isValidMove(array, row, column, numChoice)) { array[row][column] = numChoice if (solvePuzzle(array)) return true array[row][column] = EMPTY_CELL } } return false } // returns true if there are still empty cells and updates the locationOfEmptyCell array, returns false when puzzle // is solved private fun findNextEmptyCell(sudokuArray: Array<IntArray>, locationOfEmptyCell: Array<Int>): Boolean { for (row in 0..8) { for (column in 0..8) { if (sudokuArray[row][column] == EMPTY_CELL) { locationOfEmptyCell[0] = row locationOfEmptyCell[1] = column return true } } } return false } // returns true if the chosen number does not occur in the row, column and quadrant, false otherwise private fun isValidMove(array: Array<IntArray>, row: Int, column: Int, numChoice: Int): Boolean { return checkRow(array, row, numChoice) && checkColumn(array, column, numChoice) && checkBox(array, row, column, numChoice) } // returns false if the chosen number is already in the box, true otherwise private fun checkBox(array: Array<IntArray>, row: Int, column: Int, numChoice: Int): Boolean { val startingRowIndex = (row / 3) * 3 val startingColumnIndex = (column / 3) * 3 for (row in startingRowIndex..startingRowIndex + 2) { for (column in startingColumnIndex..startingColumnIndex + 2) { if (array[row][column] == numChoice) return false } } return true } // returns false if the chosen number is already in the row, true otherwise private fun checkRow(array: Array<IntArray>, row: Int, numChoice: Int): Boolean { for (column in 0..8) { if (array[row][column] == numChoice) return false } return true } // returns false if the chosen number is already in the column, true otherwise private fun checkColumn(array: Array<IntArray>, column: Int, numChoice: Int): Boolean { for (row in 0..8) { if (array[row][column] == numChoice) return false } return true } // prints the 9x9 grid with sudoku formatting private fun printPuzzle(array: Array<IntArray>) { for (i in 0..8) { for (j in 0..8) { print("${array[i][j]} ") } println() } }
62
Jupyter Notebook
1,994
1,298
62a1a543b8f3e2ca1280bf50fc8a95896ef69d63
3,582
al-go-rithms
Creative Commons Zero v1.0 Universal
src/Day01.kt
dlfelps
576,047,868
false
{"Kotlin": 2821}
import java.io.File fun main() { fun parseInput(input: String) : List<Int> { fun getNext(rest: List<Int?>): Pair<Int,List<Int?>> { val next = rest.takeWhile {it != null} as List<Int> val temp = rest.dropWhile {it != null} val rest = if (temp.isEmpty()) { temp } else { temp.drop(1) //drop null } return Pair(next.sum(), rest) } var rest = input.lines().map {it.toIntOrNull()} val sums = mutableListOf<Int>() while (rest.isNotEmpty()) { val (sum, temp) = getNext(rest) rest = temp sums.add(sum) } return sums } fun part1(input: String): Int { val data = parseInput(input) return data.max() } fun part2(input:String): Int { val data = parseInput(input) return data .sortedDescending() .take(3) .sum() } val input = File("src/Day01.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3ebcc492735bf6b6e8b0ea085d071cf019001d79
1,102
aoc-2022
Apache License 2.0
src/pl/shockah/aoc/y2017/Day7.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2017 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import java.util.* import java.util.regex.Pattern class Day7: AdventTask<List<Day7.Program>, String, Int>(2017, 7) { private val inputPattern: Pattern = Pattern.compile("(\\w+) \\((\\d+)\\)(?: -> ([\\w, ]+))?") private data class InputEntry( val name: String, val weight: Int, val childrenNames: List<String> ) data class Program( val name: String, val weight: Int ) { var parent: Program? = null val children: MutableList<Program> = mutableListOf() val totalWeight: Int by lazy { weight + children.sumOf { it.totalWeight } } } override fun parseInput(rawInput: String): List<Program> { val entries = LinkedList(rawInput.lines().map { val matcher = inputPattern.matcher(it) require(matcher.find()) val name = matcher.group(1) val weight = matcher.group(2).toInt() val rawChildren = matcher.group(3) val children = rawChildren?.split(",")?.map { it.trim() } ?: listOf() return@map InputEntry(name, weight, children) }) val programs = mutableMapOf<String, Program>() while (!entries.isEmpty()) { val oldCount = entries.size val iterator = entries.iterator() outer@ while (iterator.hasNext()) { val entry = iterator.next() val children = mutableListOf<Program>() for (childName in entry.childrenNames) { children += programs[childName] ?: continue@outer } val program = Program(entry.name, entry.weight) program.children += children programs[program.name] = program iterator.remove() for (child in children) { child.parent = program } } require(oldCount != entries.size) { "Cycle between programs." } } return programs.values.toList() } private fun getRoot(input: List<Program>): Program { var current: Program = input[0] while (true) { current = current.parent ?: return current } } override fun part1(input: List<Program>): String { return getRoot(input).name } private val Program.unbalancedProgram: Program? get() { for (child in children) { child.unbalancedProgram?.let { return it } } if (children.isEmpty()) return null val groups = children.groupBy { it.totalWeight }.values.sortedBy { it.size } return if (groups.size == 1) null else groups[0][0] } override fun part2(input: List<Program>): Int { val unbalanced = getRoot(input).unbalancedProgram ?: throw IllegalStateException("No unbalanced program.") val siblingWeight = unbalanced.parent?.children?.first { it != unbalanced }?.totalWeight ?: throw IllegalArgumentException() return unbalanced.weight + (siblingWeight - unbalanced.totalWeight) } class Tests { private val task = Day7() private val rawInput = """ pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57) """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals("tknk", task.part1(input)) } @Test fun part2() { val input = task.parseInput(rawInput) Assertions.assertEquals(60, task.part2(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
3,338
Advent-of-Code
Apache License 2.0
app/src/main/kotlin/day06/Day06.kt
meli-w
433,710,859
false
{"Kotlin": 52501}
package day06 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 6 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay06Part1, ::solveDay06Part2) } fun solveDay06Part1(input: List<String>): Int = input .first() .split(",") .map { it.toInt() } .timeFliesBy() .toInt() fun solveDay06Part2(input: List<String>): Int { val solution = input .first() .split(",") .map { it.toInt() } .timeFliesBy(256) println("The Solution of Part 2 is $solution") return 0 } fun List<Int>.timeFliesBy(days: Int = 80): Long { var map: Map<Int, Long> = this .groupBy { it } .mapValues { (_, value) -> value.size.toLong() } repeat(days) { val newMap = mutableMapOf<Int, Long>() map .forEach { (age, count) -> if (age == 0) { newMap.putNewFish(8, count) newMap.putNewFish(6, count) } else { val newAge = age - 1 newMap.putNewFish(newAge, count) } } map = newMap } var size: Long = 0 map.forEach { (_, count) -> size += count } return size } private fun MutableMap<Int, Long>.putNewFish(key: Int, value: Long): MutableMap<Int, Long> { val newAgeCount = this[key] if (newAgeCount == null) { this[key] = value } else { this[key] = newAgeCount + value } return this }
0
Kotlin
0
1
f3b96c831d6c8e21de1ac866cf9c64aaae2e5ea1
1,604
AoC-2021
Apache License 2.0
src/test/kotlin/com/igorwojda/integer/fibonacci/basic/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.integer.fibonacci.basic // iterative solution private object Solution1 { private fun fibonacci(n: Int): Int { if (n < 2) { return n } var first = 0 var second = 1 var current = 0 (2..n).forEach { current = first + second first = second second = current } return current } } // iterative solution with temporary list (not efficient) private object Solution2 { private fun fibonacci(n: Int): Int { val list = mutableListOf(0, 1) for (it in list.size..n) { list.add(list.takeLast(2).sum()) } return list[n] } } // recursive solution private object Solution3 { private fun fibonacci(n: Int): Int { return when (n) { 0 -> 0 1 -> 1 else -> fibonacci(n - 1) + fibonacci(n - 2) } } } // recursive solution private object Solution4 { private fun fibonacci(n: Int): Int { if (n < 2) { return n } return fibonacci(n - 1) + fibonacci(n - 2) } }
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
1,141
kotlin-coding-challenges
MIT License
src/Day10.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
fun main() { fun part1(ops: List<String>): Int { var value = 1 var res = 0 var cycle = 0 for (s in ops) { ++cycle if (s.startsWith("noop")) { if ((cycle - 20) % 40 == 0) res += cycle * value } else { if ((cycle - 20) % 40 == 0) res += cycle * value ++cycle if ((cycle - 20) % 40 == 0) res += cycle * value value += s.split(" ")[1].toInt() } } return res } fun pp(value: Int, position: Int): Char = if (kotlin.math.abs((position % 40) - value) <= 1) '#' else '.' fun part2(ops: List<String>) { var value = 1 var cycle = 0 for (s in ops) { if (cycle % 40 == 0) println() ++cycle if (s.startsWith("noop")) { print(pp(value, cycle - 1)) } else { print(pp(value, cycle - 1)) if (cycle % 40 == 0) println() ++cycle print(pp(value, cycle - 1)) value += s.split(" ")[1].toInt() } } } val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
1,312
AOC-2022
Apache License 2.0