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
kotlin/Rational.kt
indy256
1,493,359
false
{"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571}
import java.math.BigInteger class Rational(n: BigInteger, d: BigInteger = BigInteger.ONE) : Comparable<Rational> { val num: BigInteger val den: BigInteger init { val gcd = n.gcd(d) val g = if (d.signum() > 0) gcd else if (d.signum() < 0) gcd.negate() else BigInteger.ONE num = n.divide(g) den = d.divide(g) } constructor(num: Long, den: Long = 1) : this(BigInteger.valueOf(num), BigInteger.valueOf(den)) operator fun plus(r: Rational): Rational = Rational(num.multiply(r.den).add(r.num.multiply(den)), den.multiply(r.den)) operator fun minus(r: Rational): Rational = Rational(num.multiply(r.den).subtract(r.num.multiply(den)), den.multiply(r.den)) operator fun times(r: Rational): Rational = Rational(num.multiply(r.num), den.multiply(r.den)) operator fun div(r: Rational): Rational = Rational(num.multiply(r.den), den.multiply(r.num)) operator fun unaryMinus(): Rational = Rational(num.negate(), den) fun inverse(): Rational = Rational(den, num) fun abs(): Rational = Rational(num.abs(), den) fun signum(): Int = num.signum() fun doubleValue(): Double = num.toDouble() / den.toDouble() fun longValue(): Long = num.toLong() / den.toLong() override fun compareTo(other: Rational): Int = num.multiply(other.den).compareTo(other.num.multiply(den)) override fun equals(other: Any?): Boolean = num == (other as Rational).num && den == other.den override fun hashCode(): Int = num.hashCode() * 31 + den.hashCode() override fun toString(): String = "$num/$den" companion object { val ZERO = Rational(0) val ONE = Rational(1) val POSITIVE_INFINITY = Rational(1, 0) val NEGATIVE_INFINITY = Rational(-1, 0) } } // Usage example fun main() { val a = Rational(1, 3) val b = Rational(1, 6) val s1 = Rational(1, 2) val s2 = a + b println(true == (s1 == s2)) println(a * b / b - a) println(a * Rational.ZERO) }
97
Java
561
1,806
405552617ba1cd4a74010da38470d44f1c2e4ae3
1,991
codelibrary
The Unlicense
src/main/kotlin/net/voldrich/aoc2021/Day2.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay // https://adventofcode.com/2021/day/2 fun main() { Day2().run() } class Day2 : BaseDay() { override fun task1() : Int { var depth = 0 var forward = 0 parseInstructions().forEach { when (it.instruction) { "forward" -> forward += it.value "up" -> depth -= it.value "down" -> depth += it.value } } println("forward ${forward}, depth $depth, multiplied ${forward * depth}") return forward * depth } override fun task2() : Int { var aim = 0 var depth = 0 var forward = 0 parseInstructions().forEach { when (it.instruction) { "forward" -> { forward += it.value depth += aim * it.value } "up" -> aim -= it.value "down" -> aim += it.value } } println("forward ${forward}, depth $depth, multiplied ${forward * depth}") return forward * depth } data class Instruction (val instruction: String, val value: Int) private fun parseInstructions(): List<Instruction> { val regex = Regex("([a-z]+) ([0-9]+)") return input.lines() .map { it.lowercase() } .map { parseInstruction(it, regex) } .toList() } private fun parseInstruction(str: String, regex: Regex): Instruction { val matches = regex.find(str) ?: throw Exception("No match for $str") val instruction = matches.groups.get(1)?.value val num = matches.groups.get(2)?.value?.toInt() if (instruction == null || num == null) { throw Exception("No match for $str") } return Instruction(instruction, num) } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
1,872
advent-of-code
Apache License 2.0
rtron-std/src/main/kotlin/io/rtron/std/Collections.kt
tum-gis
258,142,903
false
{"Kotlin": 1425220, "C": 12590, "Dockerfile": 511, "CMake": 399, "Shell": 99}
/* * Copyright 2019-2023 Chair of Geoinformatics, Technical University of Munich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rtron.std /** * Returns a list without consecutive elements which have the same return by the given [selector] function. * * @receiver the base list for which the consecutive duplicates according to the [selector] are being removed * @param selector if the resulting elements of the selector is equal, the duplicates are being removed * @return list without consecutive duplicates */ inline fun <T, K> Iterable<T>.distinctConsecutiveBy(crossinline selector: (T) -> K): List<T> { if (this is Collection && isEmpty()) return emptyList() if (this.count() == 1) return this.toList() return this.toList().filterWindowed(listOf(true, false)) { selector(it[0]) == selector(it[1]) } + this.last() } /** * Returns a list without consecutive elements which have the same return by the given [selector] function. * The operation is performed enclosing around the list, meaning that the selector(lastElement) == * selector(firstElement) is also evaluated. * * @receiver the base list for which the consecutive duplicates according to the [selector] are being removed * @param selector if the resulting elements of the selector is equal, the duplicates are being removed * @return list without consecutive duplicates (also potentially enclosing duplicates) */ inline fun <T, K> Iterable<T>.distinctConsecutiveEnclosingBy(crossinline selector: (T) -> K): List<T> { if (this is Collection && isEmpty()) return emptyList() if (this.count() == 1) return this.toList() return this.toList().filterWindowedEnclosing(listOf(true, false)) { selector(it[0]) == selector(it[1]) } } /** * Returns a list sorted according to natural sort order of the value returned by specified [selector] function by * filtering all unsorted elements. */ inline fun <T, K : Comparable<K>> Iterable<T>.filterToSortingBy(crossinline selector: (T) -> K): List<T> = this.filterToSorting { first, second -> selector(first) <= selector(second) } /** * Returns a list strictly sorted according to natural sort order of the value returned by specified [selector] function by * filtering all unsorted elements. */ inline fun <T, K : Comparable<K>> Iterable<T>.filterToStrictSortingBy(crossinline selector: (T) -> K): List<T> = this.filterToSorting { first, second -> selector(first) < selector(second) } /** * Returns a list sorted descending according to natural sort order of the value returned by specified [selector] * function by filtering all unsorted elements. */ inline fun <T, K : Comparable<K>> Iterable<T>.filterToStrictSortingByDescending(crossinline selector: (T) -> K): List<T> = this.filterToSorting { first, second -> selector(first) > selector(second) } /** * Returns a sorted list according to the [predicate] by filtering all unsorted elements. * * Example: Strict ordering * Given a list: 1, 3, 2, 4 * Predicate: first < second * Returning list: 1, 3, 4 (2 was dropped, since 3 < 2 is false) * * @receiver iterable to be filtered * @param predicate comparison function * @return filtered list without the unsorted elements */ inline fun <T> Iterable<T>.filterToSorting(predicate: (first: T, second: T) -> Boolean): List<T> { if (this is Collection && isEmpty()) return emptyList() var threshold = this.first() val list = arrayListOf(this.first()) for (element in this) { if (predicate(threshold, element)) { list.add(element) threshold = element } } return list } /** * Creates a sequence of lists with [size], iterating through the (receiver) sequence. * * @receiver the base sequence used to generate the sublists of [size] * @param size the size of the sublists to be returned * @param step the number of elements to move on * @return the sequence of sublists */ fun <T> Sequence<T>.windowedEnclosing(size: Int, step: Int = 1): Sequence<List<T>> = (this + this.take(size - 1)).windowed(size, step) /** * Returns true, if all lists have the same number of elements. * * @receiver first list used for comparing the sizes of the lists * @param others other lists used for the size comparison * @return true, if all lists have the same size */ fun <T, K> Collection<T>.hasSameSizeAs(vararg others: Collection<K>) = others.all { it.size == this.size } /** * Returns a list containing only elements where the pair of it and its successor matches the given [predicate]. * The last element is always included. */ inline fun <T> Iterable<T>.filterWithNext(crossinline predicate: (a: T, b: T) -> Boolean): List<T> { if (this is Collection && isEmpty()) return emptyList() if (this.count() == 1) return this.toList() return this.zipWithNext().filter { predicate(it.first, it.second) }.map { it.first } + this.last() } /** * Returns a list containing only elements where the pair of it and its successor (including the enclosing pair) matches the given [predicate]. */ inline fun <T> Iterable<T>.filterWithNextEnclosing(crossinline predicate: (a: T, b: T) -> Boolean): List<T> { if (this is Collection && isEmpty()) return emptyList() if (this.count() == 1) return this.toList() return this.zipWithNextEnclosing().filter { predicate(it.first, it.second) }.map { it.first } } /** * Returns true, if at least one consecutively following pair matches the [predicate]. */ inline fun <T> Iterable<T>.anyWithNext(crossinline predicate: (a: T, b: T) -> Boolean): Boolean = this.zipWithNext().any { predicate(it.first, it.second) } /** * Returns true, if at least one consecutively following pair (including the enclosing pair) matches the [predicate]. */ inline fun <T> Iterable<T>.anyWithNextEnclosing(crossinline predicate: (a: T, b: T) -> Boolean): Boolean = this.zipWithNextEnclosing().any { predicate(it.first, it.second) } /** * Returns true, if no consecutively following pair matches the [predicate]. */ inline fun <T> Iterable<T>.noneWithNext(crossinline predicate: (a: T, b: T) -> Boolean): Boolean = this.zipWithNext().none { predicate(it.first, it.second) } /** * Returns true, if no consecutively following pair (including the enclosing pair) matches the [predicate]. */ inline fun <T> Iterable<T>.noneWithNextEnclosing(crossinline predicate: (a: T, b: T) -> Boolean): Boolean = this.zipWithNextEnclosing().none { predicate(it.first, it.second) }
4
Kotlin
12
38
27969aee5a0c8115cb5eaf085ca7d4c964e1f033
6,995
rtron
Apache License 2.0
app/src/main/kotlin/kotlinadventofcode/2015/2015-13.kt
pragmaticpandy
356,481,847
false
{"Kotlin": 1003522, "Shell": 219}
// Originally generated by the template in CodeDAO package kotlinadventofcode.`2015` import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.grammar.* import com.github.h0tk3y.betterParse.lexer.* import com.github.h0tk3y.betterParse.parser.Parser import kotlinadventofcode.Day class `2015-13` : Day { data class PersonId(private val id: String) data class Effect(val target: PersonId, val change: Int, val source: PersonId) /** * Alice would gain 54 happiness units by sitting next to Bob. */ fun parse(input: String): List<Effect> { val grammar = object: Grammar<List<Effect>>() { val would by literalToken(" would ") val gain by literalToken("gain") val lose by literalToken("lose") val personIdText by regexToken("""[a-zA-Z]+""") val happinessText by regexToken("\\d+") val finalFiller by literalToken(" happiness units by sitting next to ") val space by literalToken(" ") val period by literalToken(".") val newline by literalToken("\n") val personId by personIdText use { PersonId(text) } val happinessSign by (gain map { 1 }) or (lose map { -1 }) val unsignedHappiness by happinessText use { text.toInt() } val happiness by happinessSign and skip(space) and unsignedHappiness map { it.t1 * it.t2 } val line by personId and skip(would) and happiness and skip(finalFiller) and personId and skip(period) map { Effect(it.t1, it.t2, it.t3) } override val rootParser: Parser<List<Effect>> by separatedTerms(line, newline) } return grammar.parseToEnd(input) } private fun Iterable<Effect>.people(): Set<PersonId> { return this.flatMap { listOf(it.source, it.target) }.toSet() } private fun Iterable<Effect>.toMap(): Map<Pair<PersonId, PersonId>, Int> { val result: MutableMap<Pair<PersonId, PersonId>, Int> = mutableMapOf() this.forEach { result += (it.target to it.source) to it.change } return result } private fun List<PersonId>.grade(effectByPeople: Map<Pair<PersonId, PersonId>, Int>): Int { var result = 0 for (i in this.indices) { val otherI = (i + 1) % this.size result += effectByPeople.getValue(this[i] to this[otherI]) result += effectByPeople.getValue(this[otherI] to this[i]) } return result } private fun createPermutations(people: Set<PersonId>): Set<List<PersonId>> { if (people.size == 1) return setOf(people.toList()) val person = people.first() val permutations = createPermutations(people - person) return permutations .flatMap { val result: MutableList<List<PersonId>> = mutableListOf() for (i in it.indices) { val permutation = it.toMutableList() permutation.add(i, person) result += permutation } result } .toSet() } /** * After verifying your solution on the AoC site, run `./ka continue` to add a test for it. */ override fun runPartOneNoUI(input: String): String { val effects = parse(input) // There are only 8 folks so we can just have all the permutations in memory. val permutations: Set<List<PersonId>> = createPermutations(effects.people()) val effectMap = effects.toMap() return permutations.maxOf { it.grade(effectMap) }.toString() } /** * After verifying your solution on the AoC site, run `./ka continue` to add a test for it. */ override fun runPartTwoNoUI(input: String): String { val effects = parse(input).toMutableList() val me = PersonId("💩") effects.people().forEach { effects += Effect(me, 0, it) effects += Effect(it, 0, me) } val permutations = createPermutations(effects.people() + me) val effectMap = effects.toMap() return permutations.maxOf { it.grade(effectMap) }.toString() } override val defaultInput = """Alice would gain 54 happiness units by sitting next to Bob. Alice would lose 81 happiness units by sitting next to Carol. Alice would lose 42 happiness units by sitting next to David. Alice would gain 89 happiness units by sitting next to Eric. Alice would lose 89 happiness units by sitting next to Frank. Alice would gain 97 happiness units by sitting next to George. Alice would lose 94 happiness units by sitting next to Mallory. Bob would gain 3 happiness units by sitting next to Alice. Bob would lose 70 happiness units by sitting next to Carol. Bob would lose 31 happiness units by sitting next to David. Bob would gain 72 happiness units by sitting next to Eric. Bob would lose 25 happiness units by sitting next to Frank. Bob would lose 95 happiness units by sitting next to George. Bob would gain 11 happiness units by sitting next to Mallory. Carol would lose 83 happiness units by sitting next to Alice. Carol would gain 8 happiness units by sitting next to Bob. Carol would gain 35 happiness units by sitting next to David. Carol would gain 10 happiness units by sitting next to Eric. Carol would gain 61 happiness units by sitting next to Frank. Carol would gain 10 happiness units by sitting next to George. Carol would gain 29 happiness units by sitting next to Mallory. David would gain 67 happiness units by sitting next to Alice. David would gain 25 happiness units by sitting next to Bob. David would gain 48 happiness units by sitting next to Carol. David would lose 65 happiness units by sitting next to Eric. David would gain 8 happiness units by sitting next to Frank. David would gain 84 happiness units by sitting next to George. David would gain 9 happiness units by sitting next to Mallory. Eric would lose 51 happiness units by sitting next to Alice. Eric would lose 39 happiness units by sitting next to Bob. Eric would gain 84 happiness units by sitting next to Carol. Eric would lose 98 happiness units by sitting next to David. Eric would lose 20 happiness units by sitting next to Frank. Eric would lose 6 happiness units by sitting next to George. Eric would gain 60 happiness units by sitting next to Mallory. Frank would gain 51 happiness units by sitting next to Alice. Frank would gain 79 happiness units by sitting next to Bob. Frank would gain 88 happiness units by sitting next to Carol. Frank would gain 33 happiness units by sitting next to David. Frank would gain 43 happiness units by sitting next to Eric. Frank would gain 77 happiness units by sitting next to George. Frank would lose 3 happiness units by sitting next to Mallory. George would lose 14 happiness units by sitting next to Alice. George would lose 12 happiness units by sitting next to Bob. George would lose 52 happiness units by sitting next to Carol. George would gain 14 happiness units by sitting next to David. George would lose 62 happiness units by sitting next to Eric. George would lose 18 happiness units by sitting next to Frank. George would lose 17 happiness units by sitting next to Mallory. Mallory would lose 36 happiness units by sitting next to Alice. Mallory would gain 76 happiness units by sitting next to Bob. Mallory would lose 34 happiness units by sitting next to Carol. Mallory would gain 37 happiness units by sitting next to David. Mallory would gain 40 happiness units by sitting next to Eric. Mallory would gain 18 happiness units by sitting next to Frank. Mallory would gain 7 happiness units by sitting next to George.""" }
0
Kotlin
0
3
26ef6b194f3e22783cbbaf1489fc125d9aff9566
7,709
kotlinadventofcode
MIT License
src/Day10.kt
fonglh
573,269,990
false
{"Kotlin": 48950, "Ruby": 1701}
fun main() { fun signalStrength(cycle: Int, X: Int): Int { if (cycle == 20 || cycle == 60 || cycle == 100 || cycle == 140 || cycle == 180 || cycle == 220) { //println(Pair(cycle, X)) return cycle * X } return 0 } fun part1(input: List<String>): Int { var X = 1 var cycle = 1 var signalStrengthSum = 0 input.forEach { if (it == "noop") { cycle++ signalStrengthSum += signalStrength(cycle, X) } else { val valueToAdd = it.substringAfter(" ").toInt() cycle++ signalStrengthSum += signalStrength(cycle, X) X += valueToAdd cycle++ signalStrengthSum += signalStrength(cycle, X) } } return signalStrengthSum } fun printCRT(crt: Array<Char>) { for (row in 0 until 6) { val line = StringBuilder() for (col in 0 until 40) { line.append(crt[row*40+col]) } println(line) } } fun draw(crt: Array<Char>, cycle: Int, X: Int) { val colNum = (cycle-1) % 40 if((colNum) in X-1..X+1) { crt[cycle-1] = '#' } } fun part2(input: List<String>) { var X = 1 var cycle = 1 var crt = Array(240) { '.' } // To draw first pixel in top left corner draw(crt, cycle, X) input.forEach { if (it == "noop") { cycle++ draw(crt, cycle, X) } else { val valueToAdd = it.substringAfter(" ").toInt() cycle++ draw(crt, cycle, X) X += valueToAdd cycle++ draw(crt, cycle, X) } } printCRT(crt) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
ef41300d53c604fcd0f4d4c1783cc16916ef879b
2,156
advent-of-code-2022
Apache License 2.0
kotlin/684.Redundant Connection(冗余连接).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p> In this problem, a tree is an <b>undirected</b> graph that is connected and has no cycles. </p><p> The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed. </p><p> The resulting graph is given as a 2D-array of <code>edges</code>. Each element of <code>edges</code> is a pair <code>[u, v]</code> with <code>u < v</code>, that represents an <b>undirected</b> edge connecting nodes <code>u</code> and <code>v</code>. </p><p> Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge <code>[u, v]</code> should be in the same format, with <code>u < v</code>. </p><p><b>Example 1:</b><br /> <pre> <b>Input:</b> [[1,2], [1,3], [2,3]] <b>Output:</b> [2,3] <b>Explanation:</b> The given undirected graph will be like this: 1 / \ 2 - 3 </pre> </p> <p><b>Example 2:</b><br /> <pre> <b>Input:</b> [[1,2], [2,3], [3,4], [1,4], [1,5]] <b>Output:</b> [1,4] <b>Explanation:</b> The given undirected graph will be like this: 5 - 1 - 2 | | 4 - 3 </pre> </p> <p><b>Note:</b><br /> <li>The size of the input 2D-array will be between 3 and 1000.</li> <li>Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.</li> </p> <br /> <p> <b><font color="red">Update (2017-09-26):</font></b><br> We have overhauled the problem description + test cases and specified clearly the graph is an <b><i>undirected</i></b> graph. For the <b><i>directed</i></b> graph follow up please see <b><a href="https://leetcode.com/problems/redundant-connection-ii/description/">Redundant Connection II</a></b>). We apologize for any inconvenience caused. </p><p>在本问题中, 树指的是一个连通且无环的<strong>无向</strong>图。</p> <p>输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。</p> <p>结果图是一个以<code>边</code>组成的二维数组。每一个<code>边</code>的元素是一对<code>[u, v]</code>&nbsp;,满足&nbsp;<code>u &lt; v</code>,表示连接顶点<code>u</code>&nbsp;和<code>v</code>的<strong>无向</strong>图的边。</p> <p>返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边&nbsp;<code>[u, v]</code> 应满足相同的格式&nbsp;<code>u &lt; v</code>。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> [[1,2], [1,3], [2,3]] <strong>输出:</strong> [2,3] <strong>解释:</strong> 给定的无向图为: 1 / \ 2 - 3 </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> [[1,2], [2,3], [3,4], [1,4], [1,5]] <strong>输出:</strong> [1,4] <strong>解释:</strong> 给定的无向图为: 5 - 1 - 2 | | 4 - 3 </pre> <p><strong>注意:</strong></p> <ul> <li>输入的二维数组大小在 3 到 1000。</li> <li>二维数组中的整数在1到N之间,其中N是输入数组的大小。</li> </ul> <p><strong>更新(2017-09-26):</strong><br> 我们已经重新检查了问题描述及测试用例,明确图是<em><strong>无向&nbsp;</strong></em>图。对于有向图详见<strong><a href="https://leetcodechina.com/problems/redundant-connection-ii/description/">冗余连接II</a>。</strong>对于造成任何不便,我们深感歉意。</p> <p>在本问题中, 树指的是一个连通且无环的<strong>无向</strong>图。</p> <p>输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。</p> <p>结果图是一个以<code>边</code>组成的二维数组。每一个<code>边</code>的元素是一对<code>[u, v]</code>&nbsp;,满足&nbsp;<code>u &lt; v</code>,表示连接顶点<code>u</code>&nbsp;和<code>v</code>的<strong>无向</strong>图的边。</p> <p>返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边&nbsp;<code>[u, v]</code> 应满足相同的格式&nbsp;<code>u &lt; v</code>。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> [[1,2], [1,3], [2,3]] <strong>输出:</strong> [2,3] <strong>解释:</strong> 给定的无向图为: 1 / \ 2 - 3 </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> [[1,2], [2,3], [3,4], [1,4], [1,5]] <strong>输出:</strong> [1,4] <strong>解释:</strong> 给定的无向图为: 5 - 1 - 2 | | 4 - 3 </pre> <p><strong>注意:</strong></p> <ul> <li>输入的二维数组大小在 3 到 1000。</li> <li>二维数组中的整数在1到N之间,其中N是输入数组的大小。</li> </ul> <p><strong>更新(2017-09-26):</strong><br> 我们已经重新检查了问题描述及测试用例,明确图是<em><strong>无向&nbsp;</strong></em>图。对于有向图详见<strong><a href="https://leetcodechina.com/problems/redundant-connection-ii/description/">冗余连接II</a>。</strong>对于造成任何不便,我们深感歉意。</p> **/ class Solution { fun findRedundantConnection(edges: Array<IntArray>): IntArray { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
5,584
leetcode
MIT License
src/LongestUniqueSubSequence.kt
philipphofmann
236,017,177
false
{"Kotlin": 17647}
/** * Returns the longest subsequence with unique character. */ fun longestUniqueSubSequence(value: String): String { var longestUniqueSubSequence = "" value.forEachIndexed { index, _ -> val uniqueSubsequence = uniqueSubSequence(value.subSequence(index, value.length)) if (longestUniqueSubSequence.length < uniqueSubsequence.length) { longestUniqueSubSequence = uniqueSubsequence } } return longestUniqueSubSequence } private fun uniqueSubSequence(sequence: CharSequence): String { var uniqueSubSequence = "" sequence.forEach { char -> if (!uniqueSubSequence.contains(char)) { uniqueSubSequence += char } else { return uniqueSubSequence } } return uniqueSubSequence }
0
Kotlin
0
1
db0889c8b459af683149530f9aad93ce2926a658
789
coding-problems
Apache License 2.0
src/Day16.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
//class Day16(val lines: List<String>) { // fun partOne(): Int { // val (tunnelMap, paths) = preProcess(getTunnelList()) // return findBestPressure("AA", 0, 30, tunnelMap, paths, emptySet()) // } // // fun partTwo() : Int { // val (tunnelMap, paths) = preProcess(getTunnelList()) // return findBestPressureTwo("AA", "AA", 0, 0, 26, tunnelMap, paths, emptySet()) // } // // private fun getTunnelList(): List<Tunnel> { // return lines.map { line -> // val parts = line.split(" ") // val id = parts[1] // val flowRate = parts[4].split("=")[1].dropLast(1).toInt() // val neighboringTunnelIds = parts.drop(9).map { it.take(2) } // // Tunnel(id, flowRate, neighboringTunnelIds) // } // // Valve AA has flow rate=0; tunnels lead to valves DD, II, BB // } // // private fun preProcess(input: List<Tunnel>): Pair<Map<String, Tunnel>, Map<Tunnel, Map<TunnelNode, Int>>> { // val tunnelMap = mutableMapOf<String, Tunnel>().apply { // input.forEach { this[it.id] = it } // } // // val solver = TunnelDijkstra() // val paths = tunnelMap.values.associateWith { // solver.solve(TunnelNode(it.id).usingTunnels(tunnelMap)) // } // // return tunnelMap.filter { it.key == "AA" || it.value.flowRate > 0 } to paths // } // // private fun findBestPressure( // currentLocation: String, // timeAtLocation: Int, // totalTimeAllowed: Int, // tunnelMap: Map<String, Tunnel>, // paths: Map<Tunnel, Map<TunnelNode, Int>>, // previouslyOpenedValues: Set<String> // ): Int { // val tunnelOptions = paths[tunnelMap[currentLocation]!!]!!.filter { (tn, _) -> // (tunnelMap[tn.tunnelId]?.flowRate ?: 0) > 0 && !previouslyOpenedValues.contains(tn.tunnelId) // } // // return tunnelOptions.maxOfOrNull { (valveToOpen, costToTravelToNode) -> // val timeAtLocationAfterOpening = timeAtLocation + costToTravelToNode + TIME_TO_OPEN_VALVE // if (timeAtLocationAfterOpening >= totalTimeAllowed) { // 0 // } else { // val tunnel = tunnelMap[valveToOpen.tunnelId]!! // val minutesOpen = totalTimeAllowed - timeAtLocationAfterOpening // val totalPressureGained = minutesOpen * tunnel.flowRate // // totalPressureGained + findBestPressure( // currentLocation = valveToOpen.tunnelId, // timeAtLocation = timeAtLocationAfterOpening, // totalTimeAllowed = totalTimeAllowed, // tunnelMap = tunnelMap, // paths = paths, // previouslyOpenedValues = previouslyOpenedValues.plus(valveToOpen.tunnelId) // ) // } // } ?: 0 // in case we have no tunnel options we'd have a null max // } // // private fun findBestPressureTwo( // myLocation: String, // elephantLocation: String, // myTimeAfterOpeningMyValve: Int, // elephantTimeAfterOpeningTheirValve: Int, // totalTimeAllowed: Int, // tunnelMap: Map<String, Tunnel>, // paths: Map<Tunnel, Map<TunnelNode, Int>>, // previouslyOpenedValues: Set<String> // ): Int { // val myOptions = paths[tunnelMap[myLocation]!!]!!.filter { (tn, _) -> // ((tunnelMap[tn.tunnelId]?.flowRate) ?: 0) > 0 && !previouslyOpenedValues.contains(tn.tunnelId) // } // val elephantOptions = paths[tunnelMap[elephantLocation]!!]!!.filter { (tn, _) -> // ((tunnelMap[tn.tunnelId]?.flowRate) ?: 0) > 0 && !previouslyOpenedValues.contains(tn.tunnelId) // } // // return myOptions.maxOfOrNull { (myValve, myTravelCost) -> // val myTimeAtLocationAfterOpening = myTimeAfterOpeningMyValve + myTravelCost + TIME_TO_OPEN_VALVE // if (myTimeAtLocationAfterOpening < totalTimeAllowed) { // val myTunnel = tunnelMap[myValve.tunnelId]!! // val myMinutesToOpen = totalTimeAllowed - myTimeAtLocationAfterOpening // val myTotalPressureGained = myMinutesToOpen * myTunnel.flowRate // // myTotalPressureGained + (elephantOptions.maxOfOrNull { (elephantValve, elephantTravelCost) -> // if (myValve == elephantValve) { // -1 // } else { // val elephantTimeAtLocationAfterOpening = elephantTimeAfterOpeningTheirValve + elephantTravelCost + TIME_TO_OPEN_VALVE // if (elephantTimeAtLocationAfterOpening < totalTimeAllowed) { // val elephantTunnel = tunnelMap[elephantValve.tunnelId]!! // val elephantMinutesToOpen = totalTimeAllowed - elephantTimeAtLocationAfterOpening // val elephantTotalPressureGained = elephantMinutesToOpen * elephantTunnel.flowRate // // elephantTotalPressureGained + findBestPressureTwo( // myLocation = myValve.tunnelId, // elephantLocation = elephantValve.tunnelId, // myTimeAfterOpeningMyValve = myTimeAtLocationAfterOpening, // elephantTimeAfterOpeningTheirValve = elephantTimeAtLocationAfterOpening, // totalTimeAllowed = totalTimeAllowed, // tunnelMap = tunnelMap, // paths = paths, // previouslyOpenedValues = previouslyOpenedValues.plus(myValve.tunnelId).plus(elephantValve.tunnelId), // ) // } else { 0 } // going to and opening would take too long // } // } ?: 0) // } else { 0 } // going to and opening would take too long // } ?: 0 // } // // data class Tunnel(val id: String, val flowRate: Int, val neighboringTunnelIds: List<String>) // // data class TunnelNode(val tunnelId: String) : GenericIntDijkstra.DijkstraNode<TunnelNode> { // lateinit var tunnelMap: Map<String, Tunnel> // // fun usingTunnels(tunnelMap: Map<String, Tunnel>) = apply { this.tunnelMap = tunnelMap } // // override fun neighbors(): Map<TunnelNode, Int> { // return tunnelMap[tunnelId]!! // .neighboringTunnelIds // .map { TunnelNode(it).usingTunnels(tunnelMap) } // .associateWith { 1 } // } // } // // class TunnelDijkstra : GenericIntDijkstra<TunnelNode>() // // companion object { // private const val TIME_TO_OPEN_VALVE = 1 // } //} // //fun main() { // val input = readInput("day16_input") // println(Day16(input).partTwo()) // //}
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
6,902
advent22
Apache License 2.0
kmath-functions/src/commonMain/kotlin/space/kscience/kmath/functions/Piecewise.kt
therealansh
373,284,570
true
{"Kotlin": 1071813, "ANTLR": 887}
/* * Copyright 2018-2021 KMath contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package space.kscience.kmath.functions import space.kscience.kmath.operations.Ring /** * Represents piecewise-defined function. * * @param T the piece key type. * @param R the sub-function type. */ public fun interface Piecewise<T, R> { /** * Returns the appropriate sub-function for given piece key. */ public fun findPiece(arg: T): R? } /** * Represents piecewise-defined function where all the sub-functions are polynomials. */ public fun interface PiecewisePolynomial<T : Any> : Piecewise<T, Polynomial<T>> /** * Basic [Piecewise] implementation where all the pieces are ordered by the [Comparable] type instances. * * @param T the comparable piece key type. */ public class OrderedPiecewisePolynomial<T : Comparable<T>>(delimiter: T) : PiecewisePolynomial<T> { private val delimiters: MutableList<T> = arrayListOf(delimiter) private val pieces: MutableList<Polynomial<T>> = arrayListOf() /** * Dynamically adds a piece to the right side (beyond maximum argument value of previous piece) * * @param right new rightmost position. If is less then current rightmost position, an error is thrown. * @param piece the sub-function. */ public fun putRight(right: T, piece: Polynomial<T>) { require(right > delimiters.last()) { "New delimiter should be to the right of old one" } delimiters += right pieces += piece } /** * Dynamically adds a piece to the left side (beyond maximum argument value of previous piece) * * @param left the new leftmost position. If is less then current rightmost position, an error is thrown. * @param piece the sub-function. */ public fun putLeft(left: T, piece: Polynomial<T>) { require(left < delimiters.first()) { "New delimiter should be to the left of old one" } delimiters.add(0, left) pieces.add(0, piece) } public override fun findPiece(arg: T): Polynomial<T>? { if (arg < delimiters.first() || arg >= delimiters.last()) return null else { for (index in 1 until delimiters.size) if (arg < delimiters[index]) return pieces[index - 1] error("Piece not found") } } } /** * Return a value of polynomial function with given [ring] an given [arg] or null if argument is outside of piecewise * definition. */ public fun <T : Comparable<T>, C : Ring<T>> PiecewisePolynomial<T>.value(ring: C, arg: T): T? = findPiece(arg)?.value(ring, arg) public fun <T : Comparable<T>, C : Ring<T>> PiecewisePolynomial<T>.asFunction(ring: C): (T) -> T? = { value(ring, it) }
0
null
0
0
4065466be339017780b0ac4b98a9eda2cc2378e4
2,837
kmath
Apache License 2.0
src/main/kotlin/days/Day4.kt
teunw
573,164,590
false
{"Kotlin": 20073}
package days class Day4 : Day(4) { private fun containsTheOther(rangeA: IntRange, rangeB: IntRange): Boolean = (rangeA.contains(rangeB.first) && rangeA.contains(rangeB.last)) || (rangeB.contains(rangeA.first) && rangeB.contains(rangeA.last)) private fun parseLines(): List<Pair<IntRange, IntRange>> = inputList .map { line -> line.split(',').map { it.split('-') } } .map { Pair(IntRange(it[0][0].toInt(), it[0][1].toInt()), IntRange(it[1][0].toInt(), it[1][1].toInt())) } override fun partOne(): Int = parseLines() .count { containsTheOther(it.first, it.second) } override fun partTwo(): Int = parseLines() .count { (first, second) -> first.any { second.contains(it) } } }
0
Kotlin
0
0
149219285efdb1a4d2edc306cc449cce19250e85
790
advent-of-code-22
Creative Commons Zero v1.0 Universal
year2020/day16/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day16/part2/Year2020Day16Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Now that you've identified which tickets contain invalid values, discard those tickets entirely. Use the remaining valid tickets to determine which field is which. Using the valid ranges for each field, determine what order the fields appear on the tickets. The order is consistent between all tickets: if seat is the third field, it is the third field on every ticket, including your ticket. For example, suppose you have the following notes: class: 0-1 or 4-19 row: 0-5 or 8-19 seat: 0-13 or 16-19 your ticket: 11,12,13 nearby tickets: 3,9,18 15,1,5 5,14,9 Based on the nearby tickets in the above example, the first position must be row, the second position must be class, and the third position must be seat; you can conclude that in your ticket, class is 12, row is 11, and seat is 13. Once you work out which field is which, look for the six fields on your ticket that start with the word departure. What do you get if you multiply those six values together? */ package com.curtislb.adventofcode.year2020.day16.part2 import com.curtislb.adventofcode.common.io.forEachSection import com.curtislb.adventofcode.common.number.product import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 16, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), fieldRegex: Regex = Regex("""departure.*""") ): Long { val file = inputPath.toFile() var sectionIndex = 0 val fieldNames = mutableListOf<String>() val fieldRanges = mutableListOf<List<IntRange>>() val validTickets = mutableListOf<List<Int>>() val nearbyTickets = mutableListOf<List<Int>>() file.forEachSection { lines -> when (sectionIndex) { 0 -> { for ((field, ranges) in parseFieldsSection(lines)) { fieldNames.add(field) fieldRanges.add(ranges) } } 1 -> { validTickets.add(parseYourTicketSection(lines)) } 2 -> { nearbyTickets.addAll(parseNearbyTicketsSection(lines)) } else -> Unit } sectionIndex++ } val validRanges = fieldRanges.flatten() for (ticketValues in nearbyTickets) { var isValidTicket = true for (value in ticketValues) { var isValidValue = false for (range in validRanges) { if (value in range) { isValidValue = true break } } if (!isValidValue) { isValidTicket = false break } } if (isValidTicket) { validTickets.add(ticketValues) } } val initialIndices = List(fieldNames.size) { fieldNames.indices.toSet() } val possibleFieldsByIndex = validTickets.fold(initialIndices) { possibleIndices, ticketValues -> val currentPossibleIndices = ticketValues.map { value -> fieldNames.indices.filter { fieldIndex -> fieldRanges[fieldIndex].any { range -> value in range } }.toSet() } possibleIndices.mapIndexed { index, fieldIndices -> fieldIndices intersect currentPossibleIndices[index] } }.map { indices -> indices.map { index -> fieldNames[index] }.toMutableSet() } val fieldAssignments = mutableMapOf<String, Int>() while (fieldAssignments.size < fieldNames.size) { for (index in possibleFieldsByIndex.indices) { if (possibleFieldsByIndex[index].size == 1) { val field = possibleFieldsByIndex[index].first() fieldAssignments[field] = index for (possibleFields in possibleFieldsByIndex) { possibleFields.remove(field) } } } } return fieldAssignments.filter { (field, _) -> fieldRegex.matches(field) }.map { (_, index) -> validTickets[0][index].toLong() }.product() } private fun parseFieldsSection(lines: List<String>): List<Pair<String, List<IntRange>>> { return lines.map { line -> val fieldName = line.takeWhile { it != ':' } val matchResults = Regex("""\d+-\d+""").findAll(line).toList() Pair(fieldName, matchResults.map { result -> result.value.toIntRange(separator = "-") }) } } private fun String.toIntRange(separator: String = ".."): IntRange { val (minValue, maxValue) = trim().split(separator).map { it.trim().toInt() } return minValue..maxValue } private fun parseYourTicketSection(lines: List<String>): List<Int> { return lines[1].trim().split(',').map { token -> token.toInt() } } private fun parseNearbyTicketsSection(lines: List<String>): List<List<Int>> { return lines.subList(1, lines.size) .map { line -> line.trim().split(',').map { token -> token.toInt() } } } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
5,052
AdventOfCode
MIT License
src/main/kotlin/com/dambra/adventofcode2018/day18/Forest.kt
pauldambra
159,939,178
false
null
package com.dambra.adventofcode2018.day18 class Forest(map: String) { private var acres: MutableMap<Coord, Acre> private val maxX: Int private val maxY: Int fun resourceValue() : Int { val trees = acres .values .count { it.type == Acre.trees } val lumberyard = acres .values .count { it.type == Acre.lumberyard } return trees * lumberyard } init { val xs = mutableMapOf<Coord, Acre>() map.split("\n").forEachIndexed { y, row -> row.split("").drop(1).dropLast(1).forEachIndexed { x, s -> val coord = Coord(x, y) xs[coord] = Acre(s) } } acres = xs maxX = acres.keys.maxBy { it.x }!!.x maxY = acres.keys.maxBy { it.y }!!.y } private val seenStates = mutableSetOf(acres) private var firstRepeatingState: MutableMap<Coord, Acre>? = null private var firstRepeatAt = 0 fun after(minutes: Int): String { var minute = 0 while (minute < minutes) { acres = acres.map { x: Map.Entry<Coord, Acre> -> val surroundingTypes = x.key .surroundingCoords() .map { it -> acres.getOrElse(it) { null } } .filterNot { it == null } .map { it!!.type } .groupingBy { it } .eachCount() x.key to x.value.tick(surroundingTypes) } .toMap() .toMutableMap() if (firstRepeatingState != null) { if (firstRepeatingState == acres) { // first repeat is seen at minite `firstRepeatAt` // we know the forest is in a loop of cycle length minute - firstRepeatAt // we want to jump forwards by to the highest value // that is a multiple of `cycle length` after minute and lower than max minutes val cycleLength = minute - firstRepeatAt val tillEnd = 1000000000 - minute val endOfCycleClosestToMax = tillEnd - (tillEnd % cycleLength) minute += endOfCycleClosestToMax } } else if (!seenStates.add(acres)) { firstRepeatingState = acres firstRepeatAt = minute } minute++ } return print(acres) } private fun print(forest: Map<Coord, Acre>): String { var s = "" (0..maxY).forEach { y -> (0..maxX).forEach { x -> s += forest[Coord(x, y)]!!.type } s += "\n" } return s.trimIndent() } }
0
Kotlin
0
1
7d11bb8a07fb156dc92322e06e76e4ecf8402d1d
2,777
adventofcode2018
The Unlicense
leetcode2/src/leetcode/odd-even-linked-list.kt
hewking
68,515,222
false
null
package leetcode import leetcode.structure.ListNode /** * 328. 奇偶链表 * https://leetcode-cn.com/problems/odd-even-linked-list/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-10-18 21:09 * 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 示例 1: 输入: 1->2->3->4->5->NULL 输出: 1->3->5->2->4->NULL 示例 2: 输入: 2->1->3->5->6->4->7->NULL 输出: 2->3->6->7->1->5->4->NULL 说明: 应当保持奇数节点和偶数节点的相对顺序。 链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/odd-even-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object OddEvenLinkedList { class Solution { /** * 思路: * 解决链表问题最好的办法是在脑中或者纸上把链表画出来。 * 画个图 就一目了然了 */ fun oddEvenList(head: ListNode?): ListNode? { var p1 = head var p2 = head?.next var evenP1 = head?.next while (p2?.next != null) { p1?.next = p2.next p1 = p2.next p2.next = p1.next p2 = p1.next } p1?.next = evenP1 return head } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,719
leetcode
MIT License
app/src/main/java/eu/kanade/tachiyomi/util/ChapterExtensions.kt
johnwtt
537,907,731
true
{"Kotlin": 3018671}
package eu.kanade.tachiyomi.util import eu.kanade.tachiyomi.source.model.SChapter import org.nekomanga.domain.chapter.ChapterItem import kotlin.math.floor /** * Calculate the missing chapters for a given list of chapters. Return null if none are missing */ fun List<SChapter>.getMissingChapterCount(mangaStatus: Int): String? { //if (mangaStatus == SManga.COMPLETED) return null var count = 0 if (this.isNotEmpty()) { val chapterNumberArray = this.asSequence().distinctBy { if (it.chapter_txt.isNotEmpty()) { it.vol + it.chapter_txt } else { it.name } }.sortedBy { it.chapter_number } .map { floor(it.chapter_number).toInt() }.toList().toIntArray() if (chapterNumberArray.isNotEmpty()) { if (chapterNumberArray.first() > 1) { while (count != (chapterNumberArray[0] - 1)) { count++ if (count > 5000) { break } } } chapterNumberArray.forEachIndexed { index, chpNum -> val lastIndex = index - 1 if (lastIndex >= 0 && (chpNum - 1) > chapterNumberArray[lastIndex]) { count += (chpNum - chapterNumberArray[lastIndex]) - 1 } } } } if (count <= 0) return null return count.toString() } /** * Calculate the missing chapters for a given list of chapters. Return null if none are missing */ fun List<ChapterItem>.getMissingCount(mangaStatus: Int): String? { //if (mangaStatus == SManga.COMPLETED) return null var count = 0 if (this.isNotEmpty()) { val chapterNumberArray = this.asSequence().map { it.chapter }.distinctBy { if (it.chapterText.isNotEmpty()) { it.volume + it.chapterText } else { it.name } }.sortedBy { it.chapterNumber } .map { floor(it.chapterNumber).toInt() }.toList().toIntArray() if (chapterNumberArray.isNotEmpty()) { if (chapterNumberArray.first() > 1) { while (count != (chapterNumberArray[0] - 1)) { count++ if (count > 5000) { break } } } chapterNumberArray.forEachIndexed { index, chpNum -> val lastIndex = index - 1 if (lastIndex >= 0 && (chpNum - 1) > chapterNumberArray[lastIndex]) { count += (chpNum - chapterNumberArray[lastIndex]) - 1 } } } } if (count <= 0) return null return count.toString() }
1
Kotlin
0
0
4925e28fdf4490004372eae120b738470fbeea58
2,775
Neko-Reader
Apache License 2.0
src/kickstart2020/c/Candies.kt
vubogovich
256,984,714
false
null
package kickstart2020.c // TODO still slow fun main() { val inputFileName = "src/kickstart2020/c/Candies.in" java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) } for (case in 1..readLine()!!.toInt()) { val (_, q) = readLine()!!.split(' ').map { it.toInt() } val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray() val divider = Math.min(a.size, 330) val calcSection: (Int) -> Pair<Long, Long> = { section -> var sum1 = 0L var sum2 = 0L var mul = 1 for (i in 0 until divider) { sum1 += mul * (i + 1) * a[section * divider + i] sum2 += mul * a[section * divider + i] mul = -mul } sum1 to sum2 } val cache = (0 until a.size / divider).map(calcSection).toTypedArray() var result = 0L repeat(q) { val operation = readLine()!!.split(' ') when (operation[0]) { "Q" -> { val (l, r) = operation.slice(1..2).map { it.toInt() } val startSection = (l + divider - 2) / divider val endSection = r / divider var mul = 1 // ok since divider is even if (((l - 1) % divider > 0) || (startSection >= endSection)) { val r0 = if (startSection >= endSection) r else startSection * divider for (i in l..r0) { result += mul * (i - l + 1) * a[i - 1] mul = -mul } } for (section in startSection until endSection) { result += mul * cache[section].let { it.first + (section * divider - l + 1) * it.second } } if ((r % divider > 0) && (startSection < endSection)) { val l0 = endSection * divider + 1 for (i in l0..r) { result += mul * (i - l + 1) * a[i - 1] mul = -mul } } } "U" -> { val (x, v) = operation.slice(1..2).map { it.toInt() } val section = (x - 1) / divider a[x - 1] = v cache[section] = calcSection(section) } } } println("Case #$case: $result") } }
0
Kotlin
0
0
fc694f84bd313cc9e8fcaa629bafa1d16ca570fb
2,574
kickstart
MIT License
neat-core/src/main/kotlin/neat/novelty/Levenshtein.kt
MikeDepies
325,124,905
false
{"CSS": 7942948, "Kotlin": 700526, "Python": 545415, "TypeScript": 76204, "Svelte": 50830, "JavaScript": 6857, "HTML": 2446, "Dockerfile": 772}
package neat.novelty import kotlin.math.min fun levenshtein(lhs: CharSequence, rhs: CharSequence): Int { if (lhs == rhs) { return 0 } if (lhs.isEmpty()) { return rhs.length } if (rhs.isEmpty()) { return lhs.length } val lhsLength = lhs.length + 1 val rhsLength = rhs.length + 1 var cost = Array(lhsLength) { it } var newCost = Array(lhsLength) { 0 } for (i in 1 until rhsLength) { newCost[0] = i for (j in 1 until lhsLength) { val match = if (lhs[j - 1] == rhs[i - 1]) 0 else 1 val costReplace = cost[j - 1] + match val costInsert = cost[j] + 1 val costDelete = newCost[j - 1] + 1 newCost[j] = min(min(costInsert, costDelete), costReplace) } val swap = cost cost = newCost newCost = swap } return cost[lhsLength - 1] } fun levenshtein(lhs: List<Int>, rhs: List<Int>): Int { if (lhs == rhs) { return 0 } if (lhs.isEmpty()) { return rhs.size } if (rhs.isEmpty()) { return lhs.size } val lhsLength = lhs.size + 1 val rhsLength = rhs.size + 1 var cost = Array(lhsLength) { it } var newCost = Array(lhsLength) { 0 } for (i in 1 until rhsLength) { newCost[0] = i for (j in 1 until lhsLength) { val match = if (lhs[j - 1] == rhs[i - 1]) 0 else 1 val costReplace = cost[j - 1] + match val costInsert = cost[j] + 1 val costDelete = newCost[j - 1] + 1 newCost[j] = min(min(costInsert, costDelete), costReplace) } val swap = cost cost = newCost newCost = swap } return cost[lhsLength - 1] }
0
CSS
0
3
215f13fd4140e32b882e3a8c68900b174d388d9f
1,768
NeatKotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordLadder2BFS.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 fun interface AbstractWordLadder2Strategy { operator fun invoke(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> } class WordLadder2 : AbstractWordLadder2Strategy { override operator fun invoke(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> { val dict = wordList.toHashSet() val res: MutableList<List<String>> = ArrayList() if (!dict.contains(endWord)) { return res } val map: Map<String, List<String>> = getChildren(beginWord, endWord, dict) val path: MutableList<String> = ArrayList() path.add(beginWord) findLadders(beginWord, endWord, map, res, path) return res } private fun findLadders( beginWord: String, endWord: String, map: Map<String, List<String>>, res: MutableList<List<String>>, path: MutableList<String>, ) { if (beginWord == endWord) { res.add(ArrayList(path)) } if (!map.containsKey(beginWord)) { return } for (next in map[beginWord] ?: error("svw")) { path.add(next) findLadders(next, endWord, map, res, path) path.removeAt(path.size - 1) } } private fun getChildren(beginWord: String, endWord: String, dict: Set<String>): Map<String, List<String>> { val map: MutableMap<String, MutableList<String>> = HashMap() var start: MutableSet<String> = HashSet() start.add(beginWord) var end: MutableSet<String> = HashSet() val visited: MutableSet<String> = HashSet() end.add(endWord) var isFound = false var isBackward = false while (start.isNotEmpty() && !isFound) { if (start.size > end.size) { val temp: MutableSet<String> = start start = end end = temp isBackward = !isBackward } val set: MutableSet<String> = HashSet() for (cur in start) { visited.add(cur) for (next in getNext(cur, dict)) { if (visited.contains(next) || start.contains(next)) { continue } if (end.contains(next)) { isFound = true } set.add(next) val parent = if (isBackward) next else cur val child = if (isBackward) cur else next if (!map.containsKey(parent)) { map[parent] = ArrayList() } map[parent]?.add(child) } } start = set } return map } private fun getNext(cur: String, dict: Set<String>): List<String> { val res: MutableList<String> = ArrayList() val chars = cur.toCharArray() for (i in chars.indices) { val old = chars[i] for (c in 'a'..'z') { if (c == old) { continue } chars[i] = c val next = String(chars) if (dict.contains(next)) { res.add(next) } } chars[i] = old } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,034
kotlab
Apache License 2.0
src/main/kotlin/str/Anagram.kt
yx-z
106,589,674
false
null
package str import java.util.* import kotlin.collections.HashMap // Determine If 2 Strings are Anagram (re-ordering of each other) fun main(args: Array<String>) { // test strings val s1 = "abcd" val s2 = "dcab" // true println(isAnagram(s1, s2)) // test array val sArr = arrayOf("abc", "123", "cba", "132", "213") // should be ("abc", "cba", "123", "132", "213") or something like that println(Arrays.toString(groupAnagram(sArr))) } fun isAnagram(s1: String, s2: String): Boolean { // support lowercase standard english letters only val count = Array(26) { 0 } s1.chars().forEach { count[it - 'a'.toInt()]++ } s2.chars().forEach { count[it - 'a'.toInt()]-- } return count.asSequence().all { it == 0 } } fun groupAnagram(arr: Array<String>): Array<String> { val ans = Array(arr.size) { "" } val map = HashMap<String, ArrayList<String>>() arr.forEach { val key = it.sorted() if (map.containsKey(key)) { map[key]?.add(it) } else { map.put(key, ArrayList(Arrays.asList(it))) } } var idx = 0 map.values.forEach { it.forEach { ans[idx++] = it } } return ans } fun String.sorted(): String = asSequence().sorted().joinToString()
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,174
AlgoKt
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindDuplicateNumber.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Find the Duplicate Number * @see <a href="https://leetcode.com/problems/find-the-duplicate-number/">Source</a> */ fun interface FindDuplicateNumber { operator fun invoke(nums: IntArray): Int } /** * Time complexity : O(n lg n) * Space complexity : O(1) or O(n) */ class FindDuplicateSort : FindDuplicateNumber { override operator fun invoke(nums: IntArray): Int { nums.sort() for (i in 1 until nums.size) { if (nums[i] == nums[i - 1]) { return nums[i] } } return 0 } } /** * Time complexity : O(n) * Space complexity : O(n) */ class FindDuplicateSet : FindDuplicateNumber { override operator fun invoke(nums: IntArray): Int { val seen: MutableSet<Int> = HashSet() nums.forEach { if (seen.contains(it)) { return it } else { seen.add(it) } } return 0 } } class FindDuplicateArray : FindDuplicateNumber { override fun invoke(nums: IntArray): Int { // Initialize a count array of size nums.size with zeros val cnt = IntArray(nums.size) { 0 } var ind = 0 if (nums.size == 1) { return 0 } // Store the count of each value in the count array for (i in nums.indices) { cnt[nums[i]]++ } for (i in cnt.indices) { // If cnt[i] > 1, this means that the element occurs more than once in nums // Return i as the duplicate value if (cnt[i] > 1) { ind = i break } } return ind } } class FindDuplicateMap : FindDuplicateNumber { override fun invoke(nums: IntArray): Int { val map = mutableMapOf<Int, Int>() var duplicate = 0 for (num in nums) { map[num] = map.getOrDefault(num, 0) + 1 } for ((key, value) in map) { if (value > 1) { duplicate = key break } } return duplicate } } class FindDuplicateBS : FindDuplicateNumber { override fun invoke(nums: IntArray): Int { var low = 0 var high = nums.size - 1 if (nums.size == 1) { return 0 } while (low <= high) { val mid = low + (high - low) / 2 var cnt = 0 // Count numbers less than or equal to mid for (n in nums) { if (n <= mid) { cnt++ } } // Binary search on the left if (cnt <= mid) { low = mid + 1 } else { // Binary search on the right high = mid - 1 } } return low } } class FindDuplicateTortoise : FindDuplicateNumber { override fun invoke(nums: IntArray): Int { if (nums.isEmpty() || nums.size == 1) { return 0 } var fast = nums[0] var slow = nums[0] // Phase 1: Detect intersection point of the two pointers do { fast = nums[nums[fast]] slow = nums[slow] } while (fast != slow) // Phase 2: Find the entrance to the cycle fast = nums[0] while (fast != slow) { fast = nums[fast] slow = nums[slow] } return slow } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,105
kotlab
Apache License 2.0
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day11.kt
giacomozama
572,965,253
false
{"Kotlin": 75671}
package me.giacomozama.adventofcode2022.days import java.io.File import java.util.* class Day11 : Day() { private class Monkey( val startingItems: List<Long>, val operation: (Long) -> Long, val test: IntArray ) private lateinit var input: List<Monkey> private fun parseOperation(s: String): (Long) -> Long { val operation: (Long, Long) -> Long = when (s[0]) { '+' -> Long::plus '-' -> Long::minus '*' -> Long::times else -> Long::div } val operand = s.drop(2) if (operand == "old") { return { operation(it, it) } } else { val parsedOperand = operand.toLong() return { operation(it, parsedOperand) } } } override fun parseInput(inputFile: File) { input = inputFile.useLines { lines -> lines.chunked(7).map { chunk -> Monkey( startingItems = chunk[1].substringAfter(": ").split(", ").map { it.toLong() }, operation = parseOperation(chunk[2].substringAfter("= old ")), test = IntArray(3) { chunk[it + 3].substringAfter("y ").toInt() } ) }.toList() } } // n = number of rounds, m = number of items, o = number of monkeys // time: O(n * m), space: O(m + o) override fun solveFirstPuzzle(): Int { val activity = IntArray(input.size) val held = Array(input.size) { LinkedList(input[it].startingItems) } for (round in 1..20) { for (i in input.indices) { activity[i] += held[i].size var cur = held[i].poll() while (cur != null) { val mk = input[i] val upd = mk.operation(cur) / 3 held[mk.test[if (upd % mk.test[0] == 0L) 1 else 2]].offer(upd) cur = held[i].poll() } } } var top1 = 0 var top2 = 0 for (c in activity) { if (c >= top1) { top2 = top1 top1 = c } else if (c > top2) { top2 = c } } return top1 * top2 } // time: O(n * m), space: O(m + o) override fun solveSecondPuzzle(): Long { val modulo = input.fold(1) { p, m -> p * m.test[0] } val activity = IntArray(input.size) val held = Array(input.size) { LinkedList(input[it].startingItems) } for (round in 1..10000) { for (i in input.indices) { activity[i] += held[i].size var cur = held[i].poll() while (cur != null) { val mk = input[i] val upd = mk.operation(cur) % modulo held[mk.test[if (upd % mk.test[0] == 0L) 1 else 2]].offer(upd) cur = held[i].poll() } } } var top1 = 0 var top2 = 0 for (c in activity) { if (c >= top1) { top2 = top1 top1 = c } else if (c > top2) { top2 = c } } return top1 * top2.toLong() } }
0
Kotlin
0
0
c30f4a37dc9911f3e42bbf5088fe246aabbee239
3,272
aoc2022
MIT License
src/main/kotlin/twentytwenty/Day9.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
fun main() { val input = {}.javaClass.getResource("twentytwenty/input9.txt").readText().lines().map { it.toLong() } val key = input.findElementWhichHasNoSumInPreamble(25) println(key) println(input.findRangeThatSumsTo(key).sumOfMinAndMax()) } fun List<Long>.findElementWhichHasNoSumInPreamble(preamble: Int): Long { for (i in preamble until size) if (this.subList(i - preamble, i).hasNoPairThatSumsTo(this[i])) return this[i] error("not found") } fun List<Long>.hasNoPairThatSumsTo(number: Long) = find { (number - it) in this && it != number } == null fun List<Long>.findRangeThatSumsTo(number: Long): List<Long> { for (i in indices) for (j in indices.reversed()) { if (j < i) break val sub = subList(i, j) if (sub.sum() == number) return sub } error("not found") } fun List<Long>.sumOfMinAndMax() = minOrNull()!! + maxOrNull()!!
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
895
aoc202xkotlin
The Unlicense
src/main/kotlin/homeworks/homework8/task1/model/MinimaxAlgorithm.kt
GirZ0n
210,118,779
false
null
package homeworks.homework7.task2.model object MinimaxAlgorithm { private const val MAX_VALUE = 1000 private const val MIN_VALUE = -MAX_VALUE private const val BASIC_VALUE = 10 fun getBestMove(board: Array<CharArray>, playerSign: Char, opponentSign: Char, emptySign: Char): Pair<Int, Int> { var bestValue = MIN_VALUE var bestMove = Pair(-1, -1) for (i in 0..2) { for (j in 0..2) { if (board[i][j] == emptySign) { board[i][j] = playerSign val moveValue = minimax(board, false, playerSign, opponentSign, emptySign) val move = Pair(i, j) board[i][j] = emptySign // Undo bestMove = move.takeIf { bestValue < moveValue } ?: bestMove bestValue = moveValue.takeIf { bestValue < it } ?: bestValue } } } return bestMove } private fun minimax( board: Array<CharArray>, isPlayer: Boolean, // !isPlayer = isOpponent playerSign: Char, opponentSign: Char, emptySign: Char ): Int { val score = evaluateCurrentState(board, playerSign, opponentSign) return if (score == BASIC_VALUE) { score } else if (score == -BASIC_VALUE) { score } else if (!isMovesLeft(board, emptySign)) { 0 } else if (isPlayer) { playerHandling(board, isPlayer, playerSign, opponentSign, emptySign) } else { opponentHandling(board, isPlayer, playerSign, opponentSign, emptySign) } } private fun playerHandling( board: Array<CharArray>, isPlayer: Boolean, playerSign: Char, opponentSign: Char, emptySign: Char ): Int { var best = MIN_VALUE for (i in 0..2) { for (j in 0..2) { if (board[i][j] == emptySign) { board[i][j] = playerSign best = best.coerceAtLeast(minimax(board, !isPlayer, playerSign, opponentSign, emptySign)) board[i][j] = emptySign // Undo } } } return best } private fun opponentHandling( board: Array<CharArray>, isPlayer: Boolean, playerSign: Char, opponentSign: Char, emptySign: Char ): Int { var best = MAX_VALUE for (i in 0..2) { for (j in 0..2) { if (board[i][j] == emptySign) { board[i][j] = opponentSign best = best.coerceAtMost(minimax(board, !isPlayer, playerSign, opponentSign, emptySign)) board[i][j] = emptySign // Undo } } } return best } private fun isMovesLeft(board: Array<CharArray>, emptySign: Char): Boolean { for (raw in board) { for (elem in raw) { if (elem == emptySign) { return true } } } return false } private fun evaluateCurrentState(board: Array<CharArray>, playerSign: Char, opponentSign: Char): Int { val results = emptyList<Int>().toMutableList() results.add(checkRowsForWinningCombinations(board, playerSign, opponentSign)) results.add(checkColumnsForWinningCombinations(board, playerSign, opponentSign)) results.add(checkMainDiagonalForWinningCombination(board, playerSign, opponentSign)) results.add(checkAntidiagonalForWinningCombination(board, playerSign, opponentSign)) for (result in results) { if (result == BASIC_VALUE || result == -BASIC_VALUE) { return result } } return 0 } /* The following 4 functions return: BASIC_VALUE - when player wins; -BASIC_VALUE - when opponent wins; 0 - when tie. */ private fun checkRowsForWinningCombinations(board: Array<CharArray>, playerSign: Char, opponentSign: Char): Int { for (row in 0..2) { if (board[row][0] == board[row][1] && board[row][1] == board[row][2]) { return if (board[row][0] == playerSign) { BASIC_VALUE } else if (board[row][0] == opponentSign) { -BASIC_VALUE } else continue } } return 0 } private fun checkColumnsForWinningCombinations(board: Array<CharArray>, playerSign: Char, opponentSign: Char): Int { for (column in 0..2) { if (board[0][column] == board[1][column] && board[1][column] == board[2][column]) { return if (board[0][column] == playerSign) { BASIC_VALUE } else if (board[0][column] == opponentSign) { -BASIC_VALUE } else continue } } return 0 } private fun checkMainDiagonalForWinningCombination( board: Array<CharArray>, playerSign: Char, opponentSign: Char ): Int { if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) { return when (board[1][1]) { playerSign -> BASIC_VALUE opponentSign -> -BASIC_VALUE else -> 0 } } return 0 } private fun checkAntidiagonalForWinningCombination( board: Array<CharArray>, playerSign: Char, opponentSign: Char ): Int { if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) { return when (board[1][1]) { playerSign -> BASIC_VALUE opponentSign -> -BASIC_VALUE else -> 0 } } return 0 } }
0
Kotlin
0
0
05f2bda1d4480681e616fba94c75da5937436961
5,863
SPBU-Homework-2
The Unlicense
src/main/kotlin/io/tree/MinPathSum.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.tree import io.utils.runTests // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/530/week-3/3303/ class MinPathSum { fun execute(grid: Array<IntArray>): Int { val height = grid.size val width: Int = grid.first().size for (row in 0 until height) { for (col in 0 until width) { grid[row][col] = if (row == 0 && col == 0) grid[row][col] else if (row == 0 && col != 0) grid[row][col] + grid[row][col - 1] else if (col == 0 && row != 0) grid[row][col] + grid[row - 1][col] else grid[row][col] + minOf(grid[row - 1][col], grid[row][col - 1]) } } return grid[height - 1][width - 1] } } fun main() { runTests(listOf( arrayOf(intArrayOf(1, 3, 1), intArrayOf(1, 5, 1), intArrayOf(4, 2, 1)) to 7, arrayOf( intArrayOf(3, 8, 6, 0, 5, 9, 9, 6, 3, 4, 0, 5, 7, 3, 9, 3), intArrayOf(0, 9, 2, 5, 5, 4, 9, 1, 4, 6, 9, 5, 6, 7, 3, 2), intArrayOf(8, 2, 2, 3, 3, 3, 1, 6, 9, 1, 1, 6, 6, 2, 1, 9), intArrayOf(1, 3, 6, 9, 9, 5, 0, 3, 4, 9, 1, 0, 9, 6, 2, 7), intArrayOf(8, 6, 2, 2, 1, 3, 0, 0, 7, 2, 7, 5, 4, 8, 4, 8), intArrayOf(4, 1, 9, 5, 8, 9, 9, 2, 0, 2, 5, 1, 8, 7, 0, 9), intArrayOf(6, 2, 1, 7, 8, 1, 8, 5, 5, 7, 0, 2, 5, 7, 2, 1), intArrayOf(8, 1, 7, 6, 2, 8, 1, 2, 2, 6, 4, 0, 5, 4, 1, 3), intArrayOf(9, 2, 1, 7, 6, 1, 4, 3, 8, 6, 5, 5, 3, 9, 7, 3), intArrayOf(0, 6, 0, 2, 4, 3, 7, 6, 1, 3, 8, 6, 9, 0, 0, 8), intArrayOf(4, 3, 7, 2, 4, 3, 6, 4, 0, 3, 9, 5, 3, 6, 9, 3), intArrayOf(2, 1, 8, 8, 4, 5, 6, 5, 8, 7, 3, 7, 7, 5, 8, 3), intArrayOf(0, 7, 6, 6, 1, 2, 0, 3, 5, 0, 8, 0, 8, 7, 4, 3), intArrayOf(0, 4, 3, 4, 9, 0, 1, 9, 7, 7, 8, 6, 4, 6, 9, 5), intArrayOf(6, 5, 1, 9, 9, 2, 2, 7, 4, 2, 7, 2, 2, 3, 7, 2), intArrayOf(7, 1, 9, 6, 1, 2, 7, 0, 9, 6, 6, 4, 4, 5, 1, 0), intArrayOf(3, 4, 9, 2, 8, 3, 1, 2, 6, 9, 7, 0, 2, 4, 2, 0), intArrayOf(5, 1, 8, 8, 4, 6, 8, 5, 2, 4, 1, 6, 2, 2, 9, 7) ) to 83, arrayOf( intArrayOf(1, 4, 8, 6, 2, 2, 1, 7), intArrayOf(4, 7, 3, 1, 4, 5, 5, 1), intArrayOf(8, 8, 2, 1, 1, 8, 0, 1), intArrayOf(8, 9, 2, 9, 8, 0, 8, 9), intArrayOf(5, 7, 5, 7, 1, 8, 5, 5), intArrayOf(7, 0, 9, 4, 5, 6, 5, 6), intArrayOf(4, 9, 9, 7, 9, 1, 9, 0) ) to 47 )) { (input, value) -> value to MinPathSum().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,505
coding
MIT License
advent-of-code-2019/src/test/java/Day7AmplificationCircuit.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toPersistentList import org.assertj.core.api.Assertions.assertThat import org.junit.Test class Day7AmplificationCircuit { private fun evaluateThrustersPower(inputs: List<Int>, program: PersistentList<Int>): Int { return inputs.fold(0) { power, input -> intCodeComputer(program, input = *intArrayOf(input, power)) .runToHalt() .out .first() .toInt() } } private fun evaluateThrustersPowerWithFeedbackLoop(inputs: List<Int>, program: PersistentList<Int>): Int { val seed = listOf( intCodeComputer(program, input = *intArrayOf(inputs[0])), intCodeComputer(program, input = *intArrayOf(inputs[1])), intCodeComputer(program, input = *intArrayOf(inputs[2])), intCodeComputer(program, input = *intArrayOf(inputs[3])), intCodeComputer(program, input = *intArrayOf(inputs[4])) ) return generateSequence(0 to seed) { (feed, amplifiers) -> try { val a = amplifiers[0].addInput { it + feed }.runToOutputOrHalt() val b = amplifiers[1].addInput { it + a.out.first() }.runToOutputOrHalt() val c = amplifiers[2].addInput { it + b.out.first() }.runToOutputOrHalt() val d = amplifiers[3].addInput { it + c.out.first() }.runToOutputOrHalt() val e = amplifiers[4].addInput { it + d.out.first() }.runToOutputOrHalt() e.out.first().toInt() to listOf(a, b, c, d, e) } catch (e: Exception) { if (e.message == "halted") { null } else { throw e } } }.takeWhile { (feed, amplifiers) -> amplifiers.all { it.pc >= 0 } } .last() .second .last() .out .first() .toInt() } @Test fun verifyTestData() { examples.forEach { (max, inputs, program) -> assertThat(evaluateThrustersPower(inputs, program)).isEqualTo(max) } } @Test fun verifyTestDataGold() { examplesGold.forEach { (max, inputs, program) -> assertThat(evaluateThrustersPowerWithFeedbackLoop(inputs, program)).isEqualTo(max) } } @Test fun findOptimum() { val max = listOf(0, 1, 2, 3, 4).permutations() .maxBy { evaluateThrustersPower(it, program) }!! println(evaluateThrustersPower(max, program)) } @Test fun findOptimumGold() { val max = listOf(9, 8, 7, 6, 5).permutations() .maxBy { evaluateThrustersPowerWithFeedbackLoop(it, program) }!! println(evaluateThrustersPowerWithFeedbackLoop(max, program)) } @Test fun testPermutations() { assertThat(listOf(0, 1, 2, 3, 4).permutations()).hasSize(120) } } fun <T> List<T>.permutations(): PersistentList<PersistentList<T>> { if (size == 1) return persistentListOf(toPersistentList()) val droppedFirst = first() val permutationsOfTheRest = drop(1).permutations() return permutationsOfTheRest.flatMap { permutation -> // for every permutation move the dropped first through the list // droppedFirst = 1 // drop(1).permutations().first = 2 3 4 5 // 1 2 3 4 5 // 2 1 3 4 5 // 2 3 1 4 5 // 2 3 4 1 5 // 2 3 4 5 1 // do the same for other permutations of 2 3 4 5 (0..permutation.size).map { index -> permutation.add(index, droppedFirst) } }.toPersistentList() } private val examples: List<Triple<Int, List<Int>, PersistentList<Int>>> = listOf( Triple<Int, List<Int>, PersistentList<Int>>( 43210, listOf<Int>(4, 3, 2, 1, 0), persistentListOf<Int>(3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0) ), Triple<Int, List<Int>, PersistentList<Int>>( 54321, listOf<Int>(0, 1, 2, 3, 4), persistentListOf<Int>( 3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23, 101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0, 0 ) ), Triple<Int, List<Int>, PersistentList<Int>>( 65210, listOf<Int>(1, 0, 4, 3, 2), persistentListOf<Int>( 3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33, 1002, 33, 7, 33, 1, 33, 31, 31, 1, 32, 31, 31, 4, 31, 99, 0, 0, 0 ) ) ) private val examplesGold: List<Triple<Int, List<Int>, PersistentList<Int>>> = listOf( Triple<Int, List<Int>, PersistentList<Int>>( 139629729, listOf<Int>(9, 8, 7, 6, 5), persistentListOf<Int>( 3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26, 27, 4, 27, 1001, 28, -1, 28, 1005, 28, 6, 99, 0, 0, 5 ) ), Triple<Int, List<Int>, PersistentList<Int>>( 18216, listOf<Int>(9, 7, 8, 5, 6), persistentListOf<Int>( 3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005, 55, 26, 1001, 54, -5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55, 1001, 55, 1, 55, 2, 53, 55, 53, 4, 53, 1001, 56, -1, 56, 1005, 56, 6, 99, 0, 0, 0, 0, 10 ) ) ) private val program = persistentListOf( 3, 8, 1001, 8, 10, 8, 105, 1, 0, 0, 21, 42, 55, 76, 89, 114, 195, 276, 357, 438, 99999, 3, 9, 1001, 9, 3, 9, 1002, 9, 3, 9, 1001, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 99, 3, 9, 102, 2, 9, 9, 101, 5, 9, 9, 4, 9, 99, 3, 9, 102, 3, 9, 9, 101, 5, 9, 9, 1002, 9, 2, 9, 101, 4, 9, 9, 4, 9, 99, 3, 9, 102, 5, 9, 9, 1001, 9, 3, 9, 4, 9, 99, 3, 9, 1001, 9, 4, 9, 102, 5, 9, 9, 1001, 9, 5, 9, 1002, 9, 2, 9, 101, 2, 9, 9, 4, 9, 99, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 99, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 99, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 99, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1001, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 99, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 101, 1, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 3, 9, 1001, 9, 1, 9, 4, 9, 3, 9, 1002, 9, 2, 9, 4, 9, 3, 9, 102, 2, 9, 9, 4, 9, 3, 9, 101, 2, 9, 9, 4, 9, 99 )
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
11,806
advent-of-code
MIT License
2018/kotlin/day6p2/src/main/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min data class Coord(val x: Int, val y: Int) fun main(args: Array<String>) { val start = Date() val input = "292, 73\n" + "204, 176\n" + "106, 197\n" + "155, 265\n" + "195, 59\n" + "185, 136\n" + "54, 82\n" + "209, 149\n" + "298, 209\n" + "274, 157\n" + "349, 196\n" + "168, 353\n" + "193, 129\n" + "94, 137\n" + "177, 143\n" + "196, 357\n" + "272, 312\n" + "351, 340\n" + "253, 115\n" + "109, 183\n" + "252, 232\n" + "193, 258\n" + "242, 151\n" + "220, 345\n" + "336, 348\n" + "196, 203\n" + "122, 245\n" + "265, 189\n" + "124, 57\n" + "276, 204\n" + "309, 125\n" + "46, 324\n" + "345, 228\n" + "251, 134\n" + "231, 117\n" + "88, 112\n" + "256, 229\n" + "49, 201\n" + "142, 108\n" + "150, 337\n" + "134, 109\n" + "288, 67\n" + "297, 231\n" + "310, 131\n" + "208, 255\n" + "246, 132\n" + "232, 45\n" + "356, 93\n" + "356, 207\n" + "83, 97" println(regionWithinDistance(parseInput(input), 9999).size) println("in ${Date().time - start.time}ms") } fun regionWithinDistance(coords: List<Coord>, maxDistance: Int): Set<Coord> { val distances = mutableMapOf<Coord, Int>() val pending = mutableSetOf(center(coords)) while (!pending.isEmpty()) { val p = pending.first() pending.remove(p) for (c in coords) { val tmp = distanceBetween(c, p) distances[p] = (distances[p] ?: 0) + tmp } if (distances[p]!! < maxDistance) { val nextPoints = listOf( Coord(p.x - 1, p.y), Coord(p.x + 1, p.y), Coord(p.x, p.y - 1), Coord(p.x, p.y + 1) ) .filter { !distances.containsKey(it) } for (np in nextPoints) { pending.add(np) } } } return distances .filter { kv -> kv.value <= maxDistance } .map { kv -> kv.key } .toSet() } fun center(points: List<Coord>): Coord { var minX = Int.MAX_VALUE var maxX = Int.MIN_VALUE var minY = Int.MAX_VALUE var maxY = Int.MIN_VALUE for (p in points) { minX = min(minX, p.x) maxX = max(maxY, p.x) minY = min(minY, p.y) maxY = max(maxY, p.y) } return Coord( (maxX - minX) / 2 + minX, (maxY - minY) / 2 + minY ) } fun distanceBetween(a: Coord, b: Coord): Int { return abs(a.x - b.x) + abs(a.y - b.y) } fun parseInput(input: String): List<Coord> { return input.split('\n') .map { line -> val nums = line.split(", ") .map { t -> t.toInt() } Coord(nums[0], nums[1]) } }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
3,342
adventofcode
MIT License
src/main/kotlin/y2023/Day1.kt
juschmitt
725,529,913
false
{"Kotlin": 18866}
package y2023 import utils.Day class Day1 : Day(1, 2023, false) { override fun partOne(): Any { return inputList.findSumOfFirstAndLastDigit().sum() } override fun partTwo(): Any { return inputList.findSumOfFirstAndLastNumber().sum() } } private fun List<String>.findSumOfFirstAndLastDigit(): List<Int> = map { line -> line.first { it.isDigit() }.digitToInt() * 10 + line.last { it.isDigit() }.digitToInt() } private fun List<String>.findSumOfFirstAndLastNumber(): List<Int> = map { line -> line.findFirstNumber() * 10 + line.findLastNumber() } private fun String.findFirstNumber(): Int { var startIdx = 0 (1 .. length).forEach { i -> val current = substring(startIdx, i) Number.entries.forEach { if(current.contains(it.name.lowercase())) { return it.ordinal+1 } } current.firstOrNull { it.isDigit() }?.let { return it.digitToInt() } if (i > 5) startIdx++ } error("Something wrong here. No numbers in $this") } private fun String.findLastNumber(): Int { var endIdx = length (length - 1 downTo 0).forEach { i -> val current = substring(i, endIdx) Number.entries.forEach { if(current.contains(it.name.lowercase())) { return it.ordinal+1 } } current.lastOrNull { it.isDigit() }?.let { return it.digitToInt() } if (i < length-5) endIdx-- } error("Something wrong here. No numbers in $this") } private enum class Number { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, }
0
Kotlin
0
0
b1db7b8e9f1037d4c16e6b733145da7ad807b40a
1,551
adventofcode
MIT License
Retos/Reto #47 - LA PALABRA DE 100 PUNTOS [Fácil]/kotlin/nicodevelop.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
fun main() { println("Introduce un nuevo numero para empezar el juego") execute(readLine() ?: "") } var sum : Int = 0 fun execute(letters: String) { if (!containsOnlyLetters(letters) || letters.isEmpty()) { println("Introduce un valor correcto") execute(readLine() ?: "") return } val result = calculate(letters) println("current result: $result") sum += result println("total sum: $sum") if (sum < 100) { println("Introduce un nuevo valor") execute(readLine() ?: "") return } if (sum > 100) { println("Te has pasado :( vuelve a intentarlo") sum = 0 return } sum = 0 println("Has ganado!!!") } fun calculate(letters: String) : Int { return letters.toList().mapNotNull { letter -> alphabet[letter] }.sum() } fun containsOnlyLetters(input: String): Boolean { return input.all { it.isLetter() } } val alphabet: Map<Char, Int> = mapOf( 'a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5, 'f' to 6, 'g' to 7, 'h' to 8, 'i' to 9, 'j' to 10, 'k' to 11, 'l' to 12, 'm' to 13, 'n' to 14, 'ñ' to 15, 'o' to 16, 'p' to 17, 'q' to 18, 'r' to 19, 's' to 20, 't' to 21, 'u' to 22, 'v' to 23, 'w' to 24, 'x' to 25, 'y' to 26, 'z' to 27 )
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
1,491
retos-programacion-2023
Apache License 2.0
src/Day6/December6.kt
Nandi
47,216,709
false
null
package Day6 import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Stream /** * 6.December challenge from www.adventofcode.com * * Because your neighbors keep defeating you in the holiday house decorating contest year after year, you've decided to * deploy one million lights in a 1000x1000 grid. * * Furthermore, because you've been especially nice this year, Santa has mailed you instructions on how to display the * ideal lighting configuration. * * Part 1 * * Lights in your grid are numbered from 0 to 999 in each direction; the lights at each corner are at 0,0, 0,999, * 999,999, and 999,0. The instructions include whether to turn on, turn off, or toggle various inclusive ranges * given as coordinate pairs. Each coordinate pair represents opposite corners of a rectangle, inclusive; a coordinate * pair like 0,0 through 2,2 therefore refers to 9 lights in a 3x3 square. The lights all start turned off. * * To defeat your neighbors this year, all you have to do is set up your lights by doing the instructions Santa sent * you in order. * * After following the instructions, how many lights are lit? * * Part 2 * * You just finish implementing your winning light pattern when you realize you mistranslated Santa's message from * <NAME>. * * The light grid you bought actually has individual brightness controls; each light can have a brightness of zero or * more. The lights all start at zero. * * The phrase turn on actually means that you should increase the brightness of those lights by 1. * * The phrase turn off actually means that you should decrease the brightness of those lights by 1, to a minimum of * zero. * * The phrase toggle actually means that you should increase the brightness of those lights by 2. * * What is the total brightness of all lights combined after following Santa's instructions? * * Created by Simon on 06/12/2015. */ class December6 { enum class State(val string: String) { TOGGLE("toggle"), TURN_OFF("turn off"), TURN_ON("turn on"); } var lightsV1 = Array(1000, { BooleanArray(1000) }) var lightsV2 = Array(1000, { IntArray(1000) }) fun main() { val lines = loadFile("src/Day6/6.dec_input.txt") for (line in lines) { val state = determineState(line) val parts = line.substringAfter(state.string + " ").split(" "); val start = parts[0].split(",") val end = parts[2].split(",") for (i in start[0].toInt()..end[0].toInt()) { for (j in start[1].toInt()..end[1].toInt()) { when (state) { State.TOGGLE -> { lightsV1[i][j] = !lightsV1[i][j]; lightsV2[i][j] += 2; } State.TURN_ON -> { lightsV1[i][j] = true lightsV2[i][j] += 1 } State.TURN_OFF -> { lightsV1[i][j] = false if (lightsV2[i][j] > 0) lightsV2[i][j] -= 1 } } } } } var count = 0; for (light in lightsV1) { for (state in light) { if (state) { count++ } } } val brightnes = lightsV2.sumBy { a -> a.sum() } println(count) println(brightnes) } fun determineState(line: String): State { if (line.startsWith(State.TOGGLE.string)) { return State.TOGGLE } else if (line.startsWith(State.TURN_OFF.string)) { return State.TURN_OFF } else if (line.startsWith(State.TURN_ON.string)) { return State.TURN_ON } else { return State.TOGGLE; } } fun loadFile(path: String): Stream<String> { val input = Paths.get(path); val reader = Files.newBufferedReader(input); return reader.lines(); } } fun main(args: Array<String>) { December6().main() }
0
Kotlin
0
0
34a4b4c0926b5ba7e9b32ca6eeedd530f6e95bdc
4,229
adventofcode
MIT License
src/main/kotlin/g0001_0100/s0072_edit_distance/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0001_0100.s0072_edit_distance // #Hard #Top_100_Liked_Questions #String #Dynamic_Programming // #Algorithm_II_Day_18_Dynamic_Programming #Dynamic_Programming_I_Day_19 // #Udemy_Dynamic_Programming #Big_O_Time_O(n^2)_Space_O(n2) // #2023_07_10_Time_182_ms_(92.16%)_Space_36.2_MB_(98.04%) class Solution { fun minDistance(word1: String, word2: String): Int { val n1 = word1.length val n2 = word2.length if (n2 > n1) { return minDistance(word2, word1) } val dp = IntArray(n2 + 1) for (j in 0..n2) { dp[j] = j } for (i in 1..n1) { var pre = dp[0] dp[0] = i for (j in 1..n2) { val tmp = dp[j] dp[j] = if (word1[i - 1] != word2[j - 1]) 1 + Math.min(pre, Math.min(dp[j], dp[j - 1])) else pre pre = tmp } } return dp[n2] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
936
LeetCode-in-Kotlin
MIT License
2015/kt/src/test/kotlin/org/adventofcode/Day18.kt
windmaomao
225,344,109
false
{"JavaScript": 538717, "Ruby": 89779, "Kotlin": 58408, "Rust": 21350, "Go": 19106, "TypeScript": 9930, "Haskell": 8908, "Dhall": 3201, "PureScript": 1488, "HTML": 1307, "CSS": 1092}
package org.adventofcode class Day18 { var n = 0 var m = 0 fun setSize(s: Int) { n = s m = n + 2 } private fun neighbors() = listOf( -m-1, -m, -m+1, -1 , +1, m-1, m , m+1 ) private fun pos(i: Int, j: Int) = i * m + j fun extractState(str: List<String>): BooleanArray { val arr = BooleanArray(m * m) { false } str.forEachIndexed { i, s -> s.forEachIndexed { j, c -> val p = pos(i+1, j+1) arr[p] = (c == '#') } } return arr } fun nextState(prev: BooleanArray): BooleanArray { val state = prev.clone() val ns = neighbors() (1..n).forEach { i -> (1..n).forEach { j -> val p = pos(i, j) val c = ns.map { prev[it+p] }.count { it } state[p] = if (state[p]) (c == 2 || c == 3) else (c == 3) } } return state } fun part1(str: List<String>): Int { var state = extractState(str) (1..n).forEach { state = nextState(state) } return state.count { it } } fun fixState(prev: BooleanArray): BooleanArray { val state = prev.clone() state[pos(1, 1)] = true state[pos(1, n)] = true state[pos(n, 1)] = true state[pos(n, n)] = true return state } fun part2(str: List<String>): Int { var state = fixState(extractState(str)) (1..n).forEach { state = fixState(nextState(state)) } return state.count { it } } }
5
JavaScript
0
0
1d64d7fffa6fcfc6825e6aa9322eda76e790700f
1,400
adventofcode
MIT License
src/chapter3/section2/ex8.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter3.section2 /** * 编写一个静态方法optCompares(),接受一个整型参数N并计算一颗最优(完美平衡的)二叉查找树中的 * 一次随机查找命中平均所需的比较次数, * 如果树中的链接数量为2的幂,那么所有的空链接都应该在同一层,否则则分布在最底部的两层中。 * * 解:第i层的一个元素需要比较i次才可以查找命中(根结点为第一层), * i不断自增,将每层所有元素需要比较的次数相加,直到完全二叉查找树的总数大于等于N */ fun optCompares(N: Int): Int { if (N <= 0) return 0 //第i层的结点数量 var compares = 0 //当前二叉查找树的总结点数 var count = 0 //结点的层级,等于命中查找需要的比较次数 var i = 1 while (true) { //增加一层后,总结点数量为原结点数量的两倍加一 val maxCount = count * 2 + 1 if (maxCount >= N) { //最后一层未填满或刚好填满 compares += (N - count) * i count = maxCount break } else { //最后一层填满后仍然后剩余 compares += (maxCount - count) * i count = maxCount i++ } } return compares / N } fun main() { val checkArray = arrayOf( 1 to 1, 3 to 1, 7 to 2, 4 to 2, 15 to 3, 17 to 3, 27 to 4 ) checkArray.forEach { check(optCompares(it.first) == it.second) } println("check succeed.") }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,632
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/me/peckb/aoc/_2023/calendar/day03/Day03.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2023.calendar.day03 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day03 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> val (symbolLocations, parts) = createData(input) { !it.isDigit() && it != '.' } var partSum = 0 symbolLocations.forEach { (rowIndex, colIndex) -> listOfNotNull(parts[rowIndex - 1], parts[rowIndex], parts[rowIndex + 1]) .flatten() .filter { it.location.extendedRange.contains(colIndex) } .forEach { partSum += it.value } } partSum } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> val (symbolLocations, parts) = createData(input) { it == '*' } var gearRatioSum = 0 symbolLocations.forEach { (rowIndex, colIndex) -> val nearbyParts = listOfNotNull(parts[rowIndex - 1], parts[rowIndex], parts[rowIndex + 1]) .flatten() .filter { part -> part.location.extendedRange.contains(colIndex) } if (nearbyParts.size == 2) { gearRatioSum += (nearbyParts.first().value * nearbyParts.last().value) } } gearRatioSum } private fun createData( input: Sequence<String>, check: (Char) -> Boolean ): Pair<List<SymbolLocation>, Map<Int, List<Part>>> { val validSymbols = mutableListOf<SymbolLocation>() val parts: MutableMap<Int, MutableList<Part>> = mutableMapOf() input.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, c -> if (check(c)) { validSymbols.add(SymbolLocation(rowIndex, colIndex)) } } findPartData(row).forEach { (intRange, value) -> val location = Location(rowIndex, intRange) val part = Part(value, location) parts[rowIndex] = parts.getOrDefault(rowIndex, mutableListOf()).also { it.add(part) } } } return (validSymbols to parts) } private fun findPartData(row: String): List<Pair<IntRange, Int>> { val parts = mutableListOf<Pair<IntRange, Int>>() var currentDigit = "" row.forEachIndexed { colIndex, c -> if (c.isDigit()) { currentDigit += c } else { currentDigit.toIntOrNull()?.let { number -> val range = (colIndex - currentDigit.length - 1)..colIndex parts.add(range to number) } currentDigit = "" } } currentDigit.toIntOrNull()?.let { number -> val range = (row.length - currentDigit.length - 1)..row.length parts.add(range to number) } return parts } data class SymbolLocation(val rowIndex: Int, val colIndex: Int) data class Part(val value: Int, val location: Location) data class Location(val row: Int, val extendedRange: IntRange) }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,868
advent-of-code
MIT License
src/Day18.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min private const val EXPECTED_1 = 62L private const val EXPECTED_2 = 952408144115L private class Day18(isTest: Boolean) : Solver(isTest) { data class Point(val y: Int, val x: Int) fun part1Bfs(): Any { val walls = mutableSetOf<Point>() var y = 0 var x = 0 var Y = 0 var X = 0 var mx = 0 var my = 0 for (line in readAsLines()) { val dir = when(line[0]) { 'R' -> 0 to 1 'L' -> 0 to -1 'U' -> -1 to 0 'D' -> 1 to 0 else -> error(line) } val len = line.split(" ")[1].toInt() repeat(len) { y += dir.first x += dir.second mx = min(x, mx) my = min(y, my) Y = max(y, Y) X = max(x, X) walls.add(Point(y,x)) } } val outside = mutableSetOf<Point>() val q = ArrayDeque<Point>() q.add(Point(my - 1, 0).also { outside.add(it) }) while (!q.isEmpty()) { val p = q.removeFirst() for (d in listOf(0 to 1, 0 to -1, -1 to 0, 1 to 0, 1 to -1, 1 to 1, -1 to -1, -1 to 1, 1 to -1)) { val p2 = Point(p.y + d.first, p.x + d.second) // println("Trying $p2 -- ${walls.contains(p2)}") if (p2.x in (mx - 1)..(X+1) && p2.y in (my-1)..(Y+1) && !walls.contains(p2)) { if (outside.add(p2)) { // println("Adding $p2") q.add(p2) } } } } return (X - mx + 2 + 1) * (Y-my+2 + 1) - outside.size } fun part1(): Any { val walls = mutableListOf<Pair<Point, Point>>() var y = 0 var x = 0 for (line in readAsLines()) { val len = line.split(" ")[1].toInt() val oy = y val ox = x when (line[0]) { 'R' -> x += len 'L' -> x -= len 'U' -> y -= len 'D' -> y += len else -> error(line) } walls.add(Point(oy,ox) to Point(y, x)) } return gridpoints(walls) } fun part2(): Long { val walls = mutableListOf<Pair<Point, Point>>() var x = 0 var y = 0 var maxY = 0 for (line in readAsLines()) { val parts = line.split("#") val len = parts[1].substring(0, 5).toLong(radix = 16).toInt() val dir = parts[1][5] val ox = x val oy = y when (dir) { '0' -> x += len '1' -> y += len '2' -> x -= len '3' -> y -= len } walls.add(Point(oy, ox) to Point(y,x)) maxY = max(y, maxY) } return gridpoints(walls) } fun gridpoints(walls: List<Pair<Point, Point>>): Long { var boundaryPoints = 0L var area = 0L for (w in walls) { boundaryPoints += (w.first.y - w.second.y).absoluteValue + (w.first.x - w.second.x).absoluteValue if (w.first.y == w.second.y) { area += w.first.y * (w.second.x - w.first.x.toLong()) } } // Pick's theorem val interiorPoints = area.absoluteValue - boundaryPoints / 2 + 1 return interiorPoints + boundaryPoints } } fun main() { val testInstance = Day18(true) val instance = Day18(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2 -- (${it - EXPECTED_2})" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
3,992
advent-of-code-2022
Apache License 2.0
year2023/src/cz/veleto/aoc/year2023/Day01.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2023 import cz.veleto.aoc.core.AocDay class Day01(config: Config) : AocDay(config) { private val spelledOutDigits: Map<String, Int> = listOf( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ).mapIndexed { index, s -> s to index + 1 }.toMap() private val spelledOutDigitsRegex = spelledOutDigits.keys.joinToString("|") private val anyDigitRegex = """($spelledOutDigitsRegex|[1-9])""" private val firstDigitRegex = """.*?$anyDigitRegex.*""".toRegex() private val lastDigitRegex = """.*$anyDigitRegex.*?""".toRegex() override fun part1(): String = solve( findFirstDigit = { line -> line.first { it.isDigit() }.digitToInt() }, findLastDigit = { line -> line.last { it.isDigit() }.digitToInt() }, ) override fun part2(): String = solve( findFirstDigit = { it.findAnyDigit(firstDigitRegex) }, findLastDigit = { it.findAnyDigit(lastDigitRegex) }, ) private fun solve( findFirstDigit: (line: String) -> Int, findLastDigit: (line: String) -> Int, ): String = input .map { line -> val first = findFirstDigit(line) val last = findLastDigit(line) "$first$last".toInt() } .sum() .toString() private fun String.findAnyDigit(regex: Regex): Int = regex.matchEntire(this)!!.groupValues[1].let { it.toIntOrNull() ?: spelledOutDigits[it]!! } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
1,531
advent-of-pavel
Apache License 2.0
src/Day05.kt
timmiller17
577,546,596
false
{"Kotlin": 44667}
fun main() { fun part1(input: List<String>): String { val indexOfColumnRow = input.indexOfFirst { it.contains("1") } val numberOfStacks = input[indexOfColumnRow].trim().takeLast(1).toInt() val crateIds = mutableListOf<List<String>>() for (row in input.take(indexOfColumnRow)) { val crates = row.chunked(4).map { it.substring(1, 2) } crateIds += crates } val stacks = mutableListOf<ArrayDeque<String>>() for (stack in 1..numberOfStacks) { stacks += ArrayDeque<String>() } for (row in crateIds.reversed()) { for ((stackIndex, crateId) in row.withIndex()) { if (crateId != " ") { stacks[stackIndex].addLast(crateId) } } } val instructions = input.subList(indexOfColumnRow + 2, input.size) for (instruction in instructions) { for (move in 1..instruction.quantity()) { val crate: String = stacks[instruction.fromStack() - 1].removeLast() stacks[instruction.toStack() - 1].addLast(crate) } } var topCrates = "" for (stack in stacks) { topCrates += stack.last() } return topCrates } fun part2(input: List<String>): String { val indexOfColumnRow = input.indexOfFirst { it.contains("1") } val numberOfStacks = input[indexOfColumnRow].trim().takeLast(1).toInt() val crateIds = mutableListOf<List<String>>() for (row in input.take(indexOfColumnRow)) { val crates = row.chunked(4).map { it.substring(1, 2) } crateIds += crates } val stacks = mutableListOf<ArrayDeque<String>>() for (stack in 1..numberOfStacks) { stacks += ArrayDeque<String>() } for (row in crateIds.reversed()) { for ((stackIndex, crateId) in row.withIndex()) { if (crateId != " ") { stacks[stackIndex].addLast(crateId) } } } val instructions = input.subList(indexOfColumnRow + 2, input.size) for (instruction in instructions) { // original version also works but loops through moved crates twice // val cratesToMove = mutableListOf<String>() // for (move in 1..instruction.quantity()) { // cratesToMove += stacks[instruction.fromStack() - 1].removeLast() // } // // for (crate in cratesToMove.reversed()) { // stacks[instruction.toStack() - 1].addLast(crate) // } // this version is more efficient because it only loops through once // to preserve the order of a multi crate move, it removes the bottom crate in the move first // and places it on the new stack // I had to do it this way because while you can use takeLast(n) to get the group of // several crates, that does not remove them from the originating stack. var moveQuantity = instruction.quantity() while (moveQuantity > 0) { val sizeOfStack = stacks[instruction.fromStack() - 1].size val crate: String = stacks[instruction.fromStack() - 1].removeAt(sizeOfStack - moveQuantity) stacks[instruction.toStack() - 1].addLast(crate) moveQuantity-- } } var topCrates = "" for (stack in stacks) { topCrates += stack.last() } return topCrates } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") part1(input).println() part2(input).println() } fun String.quantity(): Int { return this.substring(5, this.indexOf("from") - 1).toInt() } fun String.fromStack(): Int { return this.substring(this.indexOf("from") + 5, this.indexOf("to") - 1).toInt() } fun String.toStack(): Int { return this.substring(this.indexOf("to") + 3).toInt() }
0
Kotlin
0
0
b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c
4,217
advent-of-code-2022
Apache License 2.0
src/main/kotlin/recur/MedianTwoArr.kt
yx-z
106,589,674
false
null
package recur import util.OneArray import util.append import util.get import util.oneArrayOf // given two sorted arrays A[1..n] and B[1..n], // find the median of sorted(A append B)[1..2n] // that is the n-th smallest element in their concatenated sorted array infix fun OneArray<Int>.medianUnion(B: OneArray<Int>): Int { val A = this val n = size if (n < 7) { // or any arbitrary constant return (A append B).sorted()[n] } val m = n / 2 return if (A[m] > B[m]) { // A[m] is bigger than A[1..m] and B[1..m], // so the upper half of A cannot be the median of sorted(A append B) // similarly, the lower half of B is smaller than A[m + 1..n] and B[m + 1..n] // so the lower half of B cannot be the median of sorted(A append B) A[1..m] medianUnion B[m + 1..n] // discard upper half of A and lower half of B } else { A[m + 1..n] medianUnion B[1..m] // discard lower half of A and upper half of B } // here we assume there is no copying between arrays since we can set // lo/hi bounds for indices } fun main(args: Array<String>) { val A = oneArrayOf(0, 1, 6, 9, 12, 13, 18, 20) val B = oneArrayOf(2, 4, 5, 8, 17, 19, 21, 23) println(A medianUnion B) // should be 9 }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,194
AlgoKt
MIT License
client/logistics.kt
GitProger
400,501,895
false
null
import java.io.InputStreamReader import java.net.URL import java.util.* import kotlin.math.absoluteValue import java.io.File data class Kettle(val id: Int, val room: String, var boilTime: Long, var ml: Int) var room = "1" var ml = 200 private const val MILLIES_IN_DAY = 86_400_000 private val start = "http://192.168.43.217:1000/" //File("ip.txt").readLines()[0] private fun query(query: String): List<String> { val url = URL(start + query) return InputStreamReader(url.openConnection().getInputStream()).readLines() } private fun ask() = query("ask.php").map { it.toKettle() } fun update(id: Int, boilTime: Long, ml: Int): List<String> { val query = "boil.php?id=$id&boil_time=$boilTime&ml=$ml" return query(query) } fun add(room: String) = query("add.php?room=$room").first().toInt() fun delete(id: Int) = query("remove.php?id=$id") fun byId(id: Int) = query("by_id.php?id=$id").first().toKettle() var graph: TreeMap<String, TreeMap<String, Int>>? = null private fun getMap() { if (graph == null) { graph = TreeMap<String, TreeMap<String, Int>>() val query = query("map.php") query.forEach { val (u, v, dist) = it.split(' ') graph!![u] = graph!!.getOrDefault(u, TreeMap<String, Int>()) graph!![v] = graph!!.getOrDefault(v, TreeMap<String, Int>()) graph!![u]!![v] = dist.toInt() graph!![v]!![u] = dist.toInt() } } } fun String.toKettle(): Kettle { val (id, room, boilTime, ml) = split(' ') return Kettle(id.toInt(), room, boilTime.toLong(), ml.toInt()) } fun updateAllKettles() = ask() fun nearKettles(currentRoom: String, ml: Int, currentTime: Long): List<Pair<Kettle, Int>> { getMap() val distance = TreeMap<String, Int>() //distance from currentRoom, calculated using Dijkstra algorithm distance[currentRoom] = 0 val dijkstra = TreeSet<String> { s1, s2 -> distance.getOrDefault(s1, Int.MAX_VALUE) - distance.getOrDefault(s2, Int.MAX_VALUE) } dijkstra.add(currentRoom) while (dijkstra.isNotEmpty()) { val cur = dijkstra.first() //nearest that's not processed yet dijkstra.remove(cur) for ((next, dist) in (graph!![cur] ?: TreeMap<String, Int>())) { if (distance.getOrDefault(next, Int.MAX_VALUE) > distance[cur]!! + dist) { dijkstra.remove(next) distance[next] = distance[cur]!! + dist dijkstra.add(next) } } } val candidates = ask().filter { it.ml >= ml } .sortedWith(compareByDescending<Kettle> { it.boilTime.coerceAtMost(currentTime) }.thenBy { distance[it.room]!! }) var currentBestDistance = Int.MAX_VALUE val optimums = mutableListOf<Pair<Kettle, Int>>() for (kettle in candidates) { if (currentBestDistance > distance.getOrDefault(kettle.room, Int.MAX_VALUE)) { optimums.add(kettle to distance[kettle.room]!!) currentBestDistance = distance[kettle.room]!! } } return optimums.filter { (kettle, _) -> (kettle.boilTime - System.currentTimeMillis()).absoluteValue < MILLIES_IN_DAY } } fun boilKettle(id: Int, volume: Int) { val boilingTime = (180L * 1000L * volume) / 1000L update(id, System.currentTimeMillis() + boilingTime, volume) } fun drink(id: Int, volumeRemaining: Int) = update(id, byId(id).boilTime, volumeRemaining)
0
Kotlin
0
0
cb1cd6d58125fb0ed983e5af0aef998c75b6ea63
3,392
Alferov-Lyceum-PTHS
MIT License
solutions/aockt/y2023/Y2023D24.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.math.distinctPairs import aockt.util.parse import aockt.util.spacial3d.Point3D import io.github.jadarma.aockt.core.Solution /** * This complicated day was only possible due to amazing insights and other solutions shared by the community: * - Collision formulae for part 1: [HyperNeutrino](https://www.youtube.com/watch?v=guOyA7Ijqgk) * - Reducing velocity search space: [u/abnew123](https://old.reddit.com/r/adventofcode/comments/18pptor/2023_day_24_part_2java_is_there_a_trick_for_this/kepxbew/) * - Use rock's reference frame: [u/xiaowuc1](https://old.reddit.com/r/adventofcode/comments/18pptor/2023_day_24_part_2java_is_there_a_trick_for_this/keps780/) * - Validating velocities by brute force: [u/Smooth-Aide-1751](https://old.reddit.com/r/adventofcode/comments/18pnycy/2023_day_24_solutions/ker8l05/) */ object Y2023D24 : Solution { /** Snapshot in time of the location and velocity of a hailstone. */ private data class HailStone(val x: Long, val y: Long, val z: Long, val vx: Long, val vy: Long, val vz: Long) { constructor(location: Point3D, velocity: Point3D) : this( location.x, location.y, location.z, velocity.x, velocity.y, velocity.z ) } /** Determine where the hailstones [h1] and [h2] will collide _(if ignoring the Z axis)_, if at all. */ private fun intersectionInXYPlane(h1: HailStone, h2: HailStone): Pair<Double, Double>? { val c1: Double = (h1.vy * h1.x - h1.vx * h1.y).toDouble() val c2: Double = (h2.vy * h2.x - h2.vx * h2.y).toDouble() val slopeDiff = h1.vy * -h2.vx - h2.vy * -h1.vx if (slopeDiff == 0L) return null val x = (c1 * -h2.vx - c2 * -h1.vx) / slopeDiff val y = (c2 * h1.vy - c1 * h2.vy) / slopeDiff val intersectsInFuture = listOf( (x - h1.x < 0) == (h1.vx < 0), (y - h1.y < 0) == (h1.vy < 0), (x - h2.x < 0) == (h2.vx < 0), (y - h2.y < 0) == (h2.vy < 0), ).all { it } return (x to y).takeIf { intersectsInFuture } } /** Returns the position of this hailstone after it moved with its velocity for a given amount of [time]. */ private fun HailStone.positionAfterTime(time: Double): Triple<Double, Double, Double> = Triple( first = x + vx * time, second = y + vy * time, third = z + vz * time, ) /** * Checks if the two hailstones will collide together in the future. * Returns false if the stones are parallel, the collision would have occurred in the past, or it isn't possible */ private fun HailStone.willCollideWith(other: HailStone): Boolean { val t = when { vx != other.vx -> (other.x - x).toDouble() / (vx - other.vx) vy != other.vy -> (other.y - y).toDouble() / (vy - other.vy) vz != other.vz -> (other.z - z).toDouble() / (vz - other.vz) else -> return false } if (t < 0) return false return positionAfterTime(t) == other.positionAfterTime(t) } /** * Determines the search space for throwing rocks at hailstones by assuming a solution in a given range and then * pruning away obviously invalid values. * * Take any two hailstones: `h1` and `h2`, such that `h2.x > h1.x` and `h2.vx > h1.vx`. * Now suppose the rock has a thrown velocity of h2.vx >= r.vx >= h1.vx. * A thrown rock must hit both `h1` and `h2` eventually. * But once it hits `h1`, we know that `r.x < h2.x`, and also that `r.vx < h2.vx`, therefore it will be impossible * for the rock to _"catch up"_ to the second hailstone. * As such, we can rule out any rock velocity within the `h1.vx..h2.vx` range. * The same logic holds for the Y and Z axes. * We can use these impossible ranges to exclude velocities which would miss at least one rock. * * @param amplitude The throwing velocity range to consider brute-forcing. * @return All possible velocity vectors that are not guaranteed to miss. */ private fun List<HailStone>.possibleRockVelocities(amplitude: Int): Sequence<Point3D> = sequence { require(amplitude > 0) { "Rock throwing amplitude must be positive." } val hailstones = this@possibleRockVelocities val velocityRange = -amplitude.toLong()..amplitude.toLong() val invalidXRanges = mutableSetOf<LongRange>() val invalidYRanges = mutableSetOf<LongRange>() val invalidZRanges = mutableSetOf<LongRange>() fun MutableSet<LongRange>.testImpossible(p0: Long, v0: Long, p1: Long, v1: Long) { if (p0 > p1 && v0 > v1) add(v1..v0) if (p1 > p0 && v1 > v0) add(v0..v1) } for ((h1, h2) in hailstones.distinctPairs()) { invalidXRanges.testImpossible(h1.x, h1.vx, h2.x, h2.vx) invalidYRanges.testImpossible(h1.y, h1.vy, h2.y, h2.vy) invalidZRanges.testImpossible(h1.z, h1.vz, h2.z, h2.vz) } val possibleX = velocityRange.filter { x -> invalidXRanges.none { x in it } } val possibleY = velocityRange.filter { y -> invalidYRanges.none { y in it } } val possibleZ = velocityRange.filter { z -> invalidZRanges.none { z in it } } for (vx in possibleX) { for (vy in possibleY) { for (vz in possibleZ) { yield(Point3D(vx, vy, vz)) } } } } /** * Given two hailstones [h1] and [h2], together with the assumed rock [velocity], calculate the point from which to * throw the rock to collide with both hailstones. * Returns null if no such throw is possible. */ private fun deduceThrowingLocation(h1: HailStone, h2: HailStone, velocity: Point3D): Point3D? { // Horrible naming scheme, read as: hailstone relative velocity; translated to rock's inertial frame. val h1rvx = h1.vx - velocity.x val h1rvy = h1.vy - velocity.y val h2rvx = h2.vx - velocity.x val h2rvy = h2.vy - velocity.y val slopeDiff = h1rvx * h2rvy - h1rvy * h2rvx if (slopeDiff == 0L) return null val t: Long = (h2rvy * (h2.x - h1.x) - h2rvx * (h2.y - h1.y)) / slopeDiff if (t < 0) return null return Point3D( x = h1.x + (h1.vx - velocity.x) * t, y = h1.y + (h1.vy - velocity.y) * t, z = h1.z + (h1.vz - velocity.z) * t, ) } /** Parse the [input] and return the states of all hailstones at time zero. */ private fun parseInput(input: String): List<HailStone> = parse { val lineRegex = Regex("""^(-?\d+), (-?\d+), (-?\d+) @ (-?\d+), (-?\d+), (-?\d+)$""") input .lineSequence() .map { line -> lineRegex.matchEntire(line)!!.destructured } .map { (x, y, z, vx, vy, vz) -> HailStone( x = x.toLong(), y = y.toLong(), z = z.toLong(), vx = vx.toLong(), vy = vy.toLong(), vz = vz.toLong(), ) } .toList() } override fun partOne(input: String): Any { val hailStones = parseInput(input) val area = if (hailStones.size < 10) 7.0..27.0 else 200000000000000.0..400000000000000.0 return hailStones.distinctPairs() .mapNotNull { (h1, h2) -> intersectionInXYPlane(h1, h2) } .count { (x, y) -> x in area && y in area } } override fun partTwo(input: String): Any { val hailStones = parseInput(input) val (h1, h2) = hailStones val amplitude = if (hailStones.size < 10) 5 else 250 return hailStones .possibleRockVelocities(amplitude = amplitude) .mapNotNull { velocity -> deduceThrowingLocation(h1, h2, velocity)?.let { HailStone(it, velocity) } } .first { rock -> hailStones.all { rock.willCollideWith(it) } } .let { it.x + it.y + it.z } } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
7,976
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/g2401_2500/s2452_words_within_two_edits_of_dictionary/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2452_words_within_two_edits_of_dictionary // #Medium #Array #String #2023_07_04_Time_256_ms_(100.00%)_Space_40.8_MB_(100.00%) class Solution { private var root: Node? = null internal class Node { var childs = HashMap<Char, Node?>() } private fun insert(s: String) { var curr = root for (ch in s.toCharArray()) { if (curr!!.childs[ch] == null) { curr.childs[ch] = Node() } curr = curr.childs[ch] } } private fun search(word: String, curr: Node?, i: Int, edits: Int): Boolean { // if reached the end with less than or equal 2 edits then return truem if (i == word.length) { return edits <= 2 } // more than 2 mismatch don't go further if (edits > 2) { return false } // there might be a case start is matching but others are diff and that's a edge case to // handle var ans = false for (ch in curr!!.childs.keys) { ans = ans or search( word, curr.childs[ch], i + 1, if (ch == word[i]) edits else edits + 1 ) } return ans } fun twoEditWords(queries: Array<String>, dictionary: Array<String>): List<String> { root = Node() for (s in dictionary) { insert(s) } val ans: MutableList<String> = ArrayList() for (s in queries) { val found = search(s, root, 0, 0) if (found) { ans.add(s) } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,670
LeetCode-in-Kotlin
MIT License
src/main/kotlin/org/vitrivr/cottontail/database/index/va/signature/MarksGenerator.kt
corner4world
368,444,276
true
{"Kotlin": 1810422, "Dockerfile": 478}
package org.vitrivr.cottontail.database.index.va.signature import kotlin.math.max import kotlin.math.min import kotlin.math.pow object MarksGenerator { /** */ const val EPSILON = 1E-9 /** * Get marks. * Todo: Tests indicate that these marks are less tight than the equidistant ones */ fun getNonUniformMarks(data: Array<DoubleArray>, marksPerDimension: IntArray): Marks { val marks = getEquidistantMarks(data, marksPerDimension) /** * Iterate over dimensions. * Get marks of d-th dimension. * Do k-means. */ marksPerDimension.indices.map { d -> var delta: Double var deltaBar = Double.POSITIVE_INFINITY do { // k-means delta = deltaBar // pseudocode line 3 /** * Iterate over marks of d-th dimension. * Iterate over data. * Check if data point is in interval of marks. * Calculate mean of data points in interval (rj). * Return list of mean of every interval in d (rjs). */ val rjs = Array(marks.marks[d].size - 1) { c -> var rj = 0.0 var rjAll = 0.0 var count = 0 var countAll = 0 data.forEach { if (it[d] >= marks.marks[d][c] && it[d] < marks.marks[d][c + 1]) { rj += it[d] count += 1 } rjAll += it[d] countAll += 1 } if (count == 0) { rjAll / countAll } else { rj / count } } // pseudocode line 7 /** * Iterate over marks of d-th dimension. * Adjust marks (moving along distance, no long equidistance) * The mark at position c is adjusted with "(first mean value + second mean value) / 2" */ (1 until marks.marks[d].size - 1).forEach { c -> marks.marks[d][c] = (rjs[c - 1] + rjs[c]) / 2 } // pseudocode line 8 /** * Iterate over marks of d-th dimension. * Iterate over data. * Check if data point is in interval of (new) marks. * If so, apply formula: * tmp = (difference between data point and c).pow(2) = euclidean distance * if distance > 0.999 then break */ deltaBar = (0 until marks.marks[d].size - 1).sumByDouble { c -> var tmp = 0.0 data.forEach { if (it[d] >= marks.marks[d][c] && it[d] < marks.marks[d][c + 1]) { tmp += (it[d] - rjs[c]).pow(2) } } tmp } } while ((delta - deltaBar) / delta < 0.999) marks.marks[d].sort() } return marks } /** * Create marks per dimension (equally spaced). Min and Max of data are included -> only makes sense to require * at least 3 marks * note: blott & weber are referring to marks that yield equally populated regions, not equidistant marks */ fun getEquidistantMarks(data: Array<DoubleArray>, marksPerDimension: IntArray): Marks { val min = getMin(data) val max = getMax(data) return getEquidistantMarks(min, max, marksPerDimension) } fun getEquidistantMarks(min: DoubleArray, max: DoubleArray, marksPerDimension: IntArray): Marks { return Marks(Array(min.size) { i -> require(marksPerDimension[i] > 2) { "Need to request more than 2 mark per dimension! (Faulty dimension: $i)" } val a = DoubleArray(marksPerDimension[i]) { min[i] + it * (max[i] - min[i]) / (marksPerDimension[i] - 1) }// subtract small amount to ensure min is included to avoid problems with FP approximations // also add small amount for last a[0] -= EPSILON a[a.lastIndex] += EPSILON a }) } /** * Create marks per dimension (equally spaced). Min and max of data are not included! -> 1 mark is in middle * of data range, 2 marks divide the range into 3 thirds, etc... */ fun getEquidistantMarksWithoutMinMax(data: Array<DoubleArray>, marksPerDimension: IntArray): Marks { val min = getMin(data) val max = getMax(data) return Marks(Array(min.size) { i -> require(marksPerDimension[i] > 0) { "Need to request at least 1 mark per dimension! (Faulty dimension: $i)" } val range = max[i] - min[i] val spacing = range / (marksPerDimension[i] + 1) DoubleArray(marksPerDimension[i]) { min[i] + (it + 1) * spacing } }) } /** * pseudocode: we have k = N / (marksPerDimension[d] - 1) elements per region for dimension d * easiest is to just sort each dimension and take kth and k+1th value and put mark in between * quickSelect would probably have better performance, but needs custom implementation * */ fun getEquallyPopulatedMarks(data: Array<DoubleArray>, marksPerDimension: IntArray): Marks { // can we do a transpose of the data so that we have an array of components for each dimension that // we can sort? Easiest is probably to copy, but this isn't gonna be cheap on ram... return Marks(Array(marksPerDimension.size) { dim -> val n = marksPerDimension[dim] val vecsPerRegion = (data.size / (n - 1)) // check effects of constant rounding down... probably last region gets more on avg require(vecsPerRegion > 0) { "More regions than data! Better use equidistant marks!" } val dimData = DoubleArray(data.size) { data[it][dim] } dimData.sort() val firstMark = dimData.first() - EPSILON val lastMark = dimData.last() + EPSILON DoubleArray(n) { m -> when (m) { 0 -> firstMark marksPerDimension[dim] - 1 -> lastMark else -> { dimData[m * vecsPerRegion] + (dimData[m * vecsPerRegion + 1] - dimData[m * vecsPerRegion]) / 2 } } } }) } /** * Get vector ([DoubleArray]) which values are minimal. */ private fun getMin(data: Array<DoubleArray>): DoubleArray { val out = DoubleArray(data.first().size) { Double.MAX_VALUE } for (array in data) { for (i in array.indices) { out[i] = min(out[i], array[i]) } } return out } /** * Get vector ([DoubleArray]) which values are maximal. */ private fun getMax(data: Array<DoubleArray>): DoubleArray { val out = DoubleArray(data.first().size) { Double.MIN_VALUE } for (array in data) { for (i in array.indices) { out[i] = max(out[i], array[i]) } } return out } }
0
Kotlin
0
0
dd722bd144642ae7ee91e482cb313d2813471afe
7,475
cottontaildb
MIT License
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Boyer_Moore_Algorithm/Boyer_Moore.kt
rajatenzyme
325,100,742
false
{"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189}
/* Boyer Moore String Matching Algorithm in Kotlin Author: <NAME> (@darkmatter18) */ import java.util.* internal object Main { private var NO_OF_CHARACTERS = 256 private fun maxOfAAndB(a: Int, b: Int): Int { return a.coerceAtLeast(b) } private fun badCharacterHeuristic(str: CharArray, size: Int, badcharacter: IntArray) { // Initialize all elements of bad character as -1 var i = 0 while (i < NO_OF_CHARACTERS) { badcharacter[i] = -1 i++ } // Fill the actual value of last occurrence of a character i = 0 while (i < size) { badcharacter[str[i].toInt()] = i i++ } } // A pattern searching function private fun search(text: CharArray, pattern: CharArray) { val m = pattern.size val n = text.size val badCharacterHeuristic = IntArray(NO_OF_CHARACTERS) // Fill the bad character array by calling the preprocessing function badCharacterHeuristic(pattern, m, badCharacterHeuristic) // s is shift of the pattern with respect to text var s = 0 while (s <= n - m) { var j = m - 1 // Keep reducing index j of pattern while characters of pattern and text are matching at this shift s while (j >= 0 && pattern[j] == text[s + j]) j-- // If the pattern is present at current shift, then index j will become -1 after the above loop s += if (j < 0) { println("Patterns occur at shift = $s") // Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. // The condition s+m < n is necessary for the case when pattern occurs at the end of text if (s + m < n) m - badCharacterHeuristic[text[s + m].toInt()] else 1 } else maxOfAAndB(1, j - badCharacterHeuristic[text[s + j].toInt()]) } } /* Driver program*/ @JvmStatic fun main(args: Array<String>) { val sc = Scanner(System.`in`) var s = sc.nextLine() val text = s.toCharArray() s = sc.nextLine() val pattern = s.toCharArray() search(text, pattern) } } /* Sample Input: AABAACAADAABAABA AABA Sample Output: Patterns occur at shift = 0 Patterns occur at shift = 9 Patterns occur at shift = 12 */
0
C++
0
0
65a0570153b7e3393d78352e78fb2111223049f3
2,428
Coding-Journey
MIT License
src/main/kotlin/com/adventofcode/Day.kt
reactivedevelopment
572,826,252
false
{"Kotlin": 2883, "Dockerfile": 379}
package com.adventofcode import com.adventofcode.Figure.* import com.adventofcode.Game.game import com.adventofcode.Game.rightScores import com.adventofcode.Round.* enum class Round(val scores: Long) { Win(6), Lose(0), Draw(3), } enum class Figure(val scores: Long) { Rock(1) { override fun roundWith(other: Figure): Round { return when (other) { Rock -> Draw Scissors -> Win Paper -> Lose } } }, Paper(2) { override fun roundWith(other: Figure): Round { return when (other) { Paper -> Draw Rock -> Win Scissors -> Lose } } }, Scissors(3) { override fun roundWith(other: Figure): Round { return when (other) { Scissors -> Draw Rock -> Lose Paper -> Win } } }; abstract fun roundWith(other: Figure): Round } fun parseFigure(s: String): Figure { return when (s) { "A" -> Rock "B" -> Paper "C" -> Scissors else -> throw IllegalStateException() } } object Game { var leftScores = 0L; private set var rightScores = 0L; private set fun game(left: Figure, right: Figure) { leftScores += left.scores leftScores += left.roundWith(right).scores rightScores += right.scores rightScores += right.roundWith(left).scores } } fun tryBruteforceGame(other: Figure, needScores: Long): Figure { for (me in setOf(Rock, Paper, Scissors)) { if (me.roundWith(other).scores == needScores) { return me } } throw IllegalStateException() } fun tryWin(other: Figure): Figure { return tryBruteforceGame(other, Win.scores) } fun tryLose(other: Figure): Figure { return tryBruteforceGame(other, Lose.scores) } fun tryDraw(other: Figure): Figure { return tryBruteforceGame(other, Draw.scores) } fun selectRightFigure(left: Figure, prompt: String): Figure { return when (prompt) { "X" -> tryLose(left) "Y" -> tryDraw(left) "Z" -> tryWin(left) else -> throw IllegalStateException() } } fun process(line: String) { val (leftMarker, rightPrompt) = line.split(' ') val left = parseFigure(leftMarker) val right = selectRightFigure(left, rightPrompt) game(left, right) } fun solution(): Long { return rightScores } fun main() { ::main .javaClass .getResourceAsStream("/input")!! .bufferedReader() .forEachLine(::process) println(solution()) }
0
Kotlin
0
0
dac46829eb85db869fd73bedf215c7aafd599983
2,396
aoc-2022-2
MIT License
reporter/src/main/kotlin/model/Statistics.kt
mercedes-benz
246,283,016
true
{"Kotlin": 1936701, "JavaScript": 310482, "HTML": 27680, "CSS": 25864, "Python": 21638, "Shell": 5460, "Dockerfile": 4679, "Ruby": 3545, "ANTLR": 1938, "Go": 328, "Rust": 280}
/* * Copyright (C) 2017-2020 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package com.here.ort.reporter.model import com.here.ort.model.OrtIssue import com.here.ort.model.OrtResult import com.here.ort.model.Package import com.here.ort.model.Project import com.here.ort.model.RuleViolation import com.here.ort.model.Scope import com.here.ort.model.Severity import java.util.SortedMap import java.util.SortedSet /** * A class containing statistics for an [OrtResult]. */ data class Statistics( /** * The number of [OrtIssue]s by severity which are not resolved and not excluded. */ val openIssues: IssueStatistics, /** * The number of [RuleViolation]s by severity which are not resolved. */ val openRuleViolations: IssueStatistics, /** * Statistics for the dependency tree. */ val dependencyTree: DependencyTreeStatistics, /** * Statistics of used licenses. */ val licenses: LicenseStatistics ) /** * A class containing the amount of issues per severity. */ data class IssueStatistics( /** * The number of issues with [Severity.ERROR] as severity. */ val errors: Int, /** * The number of issues with [Severity.WARNING] as severity. */ val warnings: Int, /** * The number of issues with [Severity.HINT] as severity. */ val hints: Int ) /** * A class containing statistics about the dependency trees. */ data class DependencyTreeStatistics( /** * The number of included [Project]s. */ val includedProjects: Int, /** * The number of excluded [Project]s. */ val excludedProjects: Int, /** * The number of included [Package]s. */ val includedPackages: Int, /** * The number of excluded [Package]s. */ val excludesPackages: Int, /** * The total depth of the deepest tree in the forest. */ val totalTreeDepth: Int, /** * The depth of the deepest tree in the forest disregarding excluded tree nodes. */ val includedTreeDepth: Int, /** * The set of scope names which have at least one not excluded corresponding [Scope]. */ val includedScopes: SortedSet<String>, /** * The set of scope names which do not have a single not excluded corresponding [Scope]. */ val excludedScopes: SortedSet<String> ) /** * A class containing statistics about licenses. */ data class LicenseStatistics( /** * All declared licenses, mapped to the number of [Project]s and [Package]s they are declared in. */ val declared: SortedMap<String, Int>, /** * All detected licenses, mapped to the number of [Project]s and [Package]s they were detected in. */ val detected: SortedMap<String, Int> )
0
null
1
0
5babc890a34127d4ab20177d823eb31fd76f79a1
3,398
oss-review-toolkit
Apache License 2.0
src/day19/Code.kt
fcolasuonno
225,219,560
false
null
package day19 import IntCode import IntCodeComputer import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.map { it.split(",").map { it.toLong() } }.requireNoNulls().single() fun part1(input: List<Long>) = (0..49).sumBy { j -> (0..49).count { i -> input.isBeamed(i, j).also { print(if (it) '#' else '.') } }.also { println() } } fun part2(input: List<Long>) = (800..1000).flatMap { j -> ((j * 3 / 4 - 3)..(j * 3 / 4 + 150)).map { it to j } }.first { input.isBeamed(it.first + 99, it.second) && input.isBeamed(it.first, it.second + 99) }.let { it.first * 10000 + it.second } private fun List<Long>.isBeamed(i: Int, j: Int): Boolean { val coord = mutableListOf(i, j) var output = 0 IntCodeComputer( this, IntCode.Input { coord.removeAt(0).toLong() }, IntCode.Output { a -> output = a.toInt() }).run() return output == 1 }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
1,258
AOC2019
MIT License
libraries/stdlib/samples/test/samples/collections/grouping.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package samples.collections import samples.* class Grouping { @Sample fun groupingByEachCount() { val words = "one two three four five six seven eight nine ten".split(' ') val frequenciesByFirstChar = words.groupingBy { it.first() }.eachCount() println("Counting first letters:") assertPrints(frequenciesByFirstChar, "{o=1, t=3, f=2, s=2, e=1, n=1}") val moreWords = "eleven twelve".split(' ') val moreFrequencies = moreWords.groupingBy { it.first() }.eachCountTo(frequenciesByFirstChar.toMutableMap()) assertPrints(moreFrequencies, "{o=1, t=4, f=2, s=2, e=2, n=1}") } @Sample fun aggregateByRadix() { val numbers = listOf(3, 4, 5, 6, 7, 8, 9) val aggregated = numbers.groupingBy { it % 3 }.aggregate { key, accumulator: StringBuilder?, element, first -> if (first) // first element StringBuilder().append(key).append(":").append(element) else accumulator!!.append("-").append(element) } assertPrints(aggregated.values, "[0:3-6-9, 1:4-7, 2:5-8]") } @Sample fun aggregateByRadixTo() { val numbers = listOf(3, 4, 5, 6, 7, 8, 9) val aggregated = numbers.groupingBy { it % 3 }.aggregateTo(mutableMapOf()) { key, accumulator: StringBuilder?, element, first -> if (first) // first element StringBuilder().append(key).append(":").append(element) else accumulator!!.append("-").append(element) } assertPrints(aggregated.values, "[0:3-6-9, 1:4-7, 2:5-8]") // aggregated is a mutable map aggregated.clear() } @Sample fun foldByEvenLengthWithComputedInitialValue() { val fruits = listOf("cherry", "blueberry", "citrus", "apple", "apricot", "banana", "coconut") val evenFruits = fruits.groupingBy { it.first() } .fold({ key, _ -> key to mutableListOf<String>() }, { _, accumulator, element -> accumulator.also { (_, list) -> if (element.length % 2 == 0) list.add(element) } }) val sorted = evenFruits.values.sortedBy { it.first } assertPrints(sorted, "[(a, []), (b, [banana]), (c, [cherry, citrus])]") } @Sample fun foldByEvenLengthWithComputedInitialValueTo() { val fruits = listOf("cherry", "blueberry", "citrus", "apple", "apricot", "banana", "coconut") val evenFruits = fruits.groupingBy { it.first() } .foldTo(mutableMapOf(), { key, _: String -> key to mutableListOf<String>() }, { _, accumulator, element -> if (element.length % 2 == 0) accumulator.second.add(element) accumulator }) val sorted = evenFruits.values.sortedBy { it.first } assertPrints(sorted, "[(a, []), (b, [banana]), (c, [cherry, citrus])]") evenFruits.clear() // evenFruits is a mutable map } @Sample fun foldByEvenLengthWithConstantInitialValue() { val fruits = listOf("apple", "apricot", "banana", "blueberry", "cherry", "coconut") // collect only even length Strings val evenFruits = fruits.groupingBy { it.first() } .fold(listOf<String>()) { acc, e -> if (e.length % 2 == 0) acc + e else acc } assertPrints(evenFruits, "{a=[], b=[banana], c=[cherry]}") } @Sample fun foldByEvenLengthWithConstantInitialValueTo() { val fruits = listOf("apple", "apricot", "banana", "blueberry", "cherry", "coconut") // collect only even length Strings val evenFruits = fruits.groupingBy { it.first() } .foldTo(mutableMapOf(), emptyList<String>()) { acc, e -> if (e.length % 2 == 0) acc + e else acc } assertPrints(evenFruits, "{a=[], b=[banana], c=[cherry]}") evenFruits.clear() // evenFruits is a mutable map } @Sample fun reduceByMaxVowels() { val animals = listOf("raccoon", "reindeer", "cow", "camel", "giraffe", "goat") // grouping by first char and collect only max of contains vowels val compareByVowelCount = compareBy { s: String -> s.count { it in "aeiou" } } val maxVowels = animals.groupingBy { it.first() }.reduce { _, a, b -> maxOf(a, b, compareByVowelCount) } assertPrints(maxVowels, "{r=reindeer, c=camel, g=giraffe}") } @Sample fun reduceByMaxVowelsTo() { val animals = listOf("raccoon", "reindeer", "cow", "camel", "giraffe", "goat") val maxVowels = mutableMapOf<Char, String>() // grouping by first char and collect only max of contains vowels val compareByVowelCount = compareBy { s: String -> s.count { it in "aeiou" } } animals.groupingBy { it.first() }.reduceTo(maxVowels) { _, a, b -> maxOf(a, b, compareByVowelCount) } assertPrints(maxVowels, "{r=reindeer, c=camel, g=giraffe}") val moreAnimals = listOf("capybara", "rat") moreAnimals.groupingBy { it.first() }.reduceTo(maxVowels) { _, a, b -> maxOf(a, b, compareByVowelCount) } assertPrints(maxVowels, "{r=reindeer, c=capybara, g=giraffe}") } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
5,420
kotlin
Apache License 2.0
common/src/main/kotlin/combo/bandit/dt/TreeNodes.kt
rasros
148,620,275
false
null
package combo.bandit.dt import combo.bandit.univariate.BanditPolicy import combo.math.VarianceEstimator import combo.sat.Instance import combo.sat.not import combo.sat.toBoolean import combo.sat.toIx import combo.util.IntCollection import combo.util.RandomListCache import combo.util.isEmpty sealed class Node(var data: VarianceEstimator) { /** * Find the exact node that matches the instance. This will always work unless there is an index out of bounds. */ abstract fun findLeaf(instance: Instance): LeafNode /** * Finds all leaves that match the given literals. This can possibly return all leaves if for example the * literals are empty. */ abstract fun findLeaves(setLiterals: IntArray): Sequence<LeafNode> abstract fun update(instance: Instance, result: Float, weight: Float, banditPolicy: BanditPolicy): Node } class SplitNode(val ix: Int, var pos: Node, var neg: Node, data: VarianceEstimator) : Node(data) { override fun update(instance: Instance, result: Float, weight: Float, banditPolicy: BanditPolicy): Node { banditPolicy.update(data, result, weight) if (instance.isSet(ix)) pos = pos.update(instance, result, weight, banditPolicy) else neg = neg.update(instance, result, weight, banditPolicy) return this } override fun findLeaf(instance: Instance) = if (instance.isSet(ix)) pos.findLeaf(instance) else neg.findLeaf(instance) override fun findLeaves(setLiterals: IntArray): Sequence<LeafNode> { for (l in setLiterals) { if (l.toIx() == ix) { return if (l.toBoolean()) pos.findLeaves(setLiterals) else neg.findLeaves(setLiterals) } } return pos.findLeaves(setLiterals) + neg.findLeaves(setLiterals) } } abstract class LeafNode(val literals: IntCollection, data: VarianceEstimator, val blocked: RandomListCache<IntCollection>?) : Node(data) { override fun findLeaf(instance: Instance) = this override fun findLeaves(setLiterals: IntArray) = sequenceOf(this) /** * Checks whether the assumptions can be satisfied by the conjunction formed by literals. * Both arrays are assumed sorted. */ fun matches(assumptions: IntCollection): Boolean { if (assumptions.isEmpty()) return true for (lit in literals) if (!lit in assumptions) return false return true } /** * The block buffer is a set of failed assumptions that should not be immediately tried again. This is applied * in the rare case when the assumptions matches the [literals] and the node is chosen and the solver then tries * to generate an instance with the given assumption and fails. In that case the assumptions are added to the * blocked buffer and a new node is chosen (this node will not be selected due to the assumptions are blocked). */ fun blocks(assumptions: IntCollection): Boolean { if (assumptions.isEmpty() || blocked == null) return false return blocked.find { if (it === assumptions) true else { var covers = true for (lit in it) { if (lit !in assumptions) { covers = false break } } covers } } != null } } class TerminalNode(literals: IntCollection, data: VarianceEstimator, blockQueueSize: Int, randomSeed: Int) : LeafNode(literals, data, if (blockQueueSize > 0) RandomListCache(blockQueueSize, randomSeed) else null) { override fun update(instance: Instance, result: Float, weight: Float, banditPolicy: BanditPolicy) = this.apply { banditPolicy.update(data, result, weight) } }
0
Kotlin
1
2
2f4aab86e1b274c37d0798081bc5500d77f8cd6f
3,820
combo
Apache License 2.0
aoc25/src/main/kotlin/de/havox_design/aoc2022/day25/SNAFUNumber.kt
Gentleman1983
737,309,232
false
{"Kotlin": 342004, "Scala": 9632}
package de.havox_design.aoc2022.day25 import kotlin.math.* enum class SNAFUNumber(private var symbol: Char, private var value: Long) { TWO('2', 2L), ONE('1', 1L), ZERO('0', 0L), MINUS('-', -1L), DOUBLE_MINUS('=', -2L); fun toSnafuSymbol(): Char = symbol fun toLong(): Long = value fun getIncrement(): SNAFUNumber = when (this) { TWO -> DOUBLE_MINUS ONE -> TWO ZERO -> ONE MINUS -> ZERO DOUBLE_MINUS -> MINUS } fun getDecrement(): SNAFUNumber = when (this) { TWO -> ONE ONE -> ZERO ZERO -> MINUS MINUS -> DOUBLE_MINUS DOUBLE_MINUS -> TWO } companion object { fun toLong(number: List<SNAFUNumber>): Long = number .reversed() .mapIndexed { i, value -> 5L.pow(i) * value.toLong() } .sum() fun toSnafu(number: String): List<SNAFUNumber> { val snafuNumber = emptyList<SNAFUNumber>().toMutableList() for (letter in number) { when (letter) { DOUBLE_MINUS.toSnafuSymbol() -> snafuNumber += DOUBLE_MINUS MINUS.toSnafuSymbol() -> snafuNumber += MINUS ZERO.toSnafuSymbol() -> snafuNumber += ZERO ONE.toSnafuSymbol() -> snafuNumber += ONE TWO.toSnafuSymbol() -> snafuNumber += TWO } } return snafuNumber } fun toSnafu(number: Long): List<SNAFUNumber> { if (number == 0L) { return listOf(ZERO) } val snafuNumber = emptyList<SNAFUNumber>().toMutableList() var workingNumber = number while (workingNumber != 0L) { when ("012=-"[workingNumber.mod(5)]) { DOUBLE_MINUS.toSnafuSymbol() -> snafuNumber += DOUBLE_MINUS MINUS.toSnafuSymbol() -> snafuNumber += MINUS ZERO.toSnafuSymbol() -> snafuNumber += ZERO ONE.toSnafuSymbol() -> snafuNumber += ONE TWO.toSnafuSymbol() -> snafuNumber += TWO } workingNumber = (workingNumber + 2).floorDiv(5) } return snafuNumber.reversed() } } } private fun Long.pow(e: Int): Long = this.toDouble().pow(e.toDouble()).toLong()
4
Kotlin
0
1
b94716fbc95f18e68774eb99069c0b703875615c
2,477
aoc2022
Apache License 2.0
Kotlin/days/src/day16.kt
dukemarty
224,307,841
false
null
import java.io.BufferedReader import java.io.FileReader import java.lang.Integer.min import java.lang.Integer.parseInt data class Signal(var data: List<Int>) { constructor(raw: String) : this(raw.toCharArray().map { parseInt(it.toString()) }) fun calcFFT(pattern: FFTPattern) { val resList = mutableListOf<Int>() for (i in IntRange(0, data.size - 1)) { var pos=0 val patt = pattern.getForElem(i).iterator() var res = 0 while (pos < data.size){ val next = patt.next() val toPos = min(data.size, pos+next.first) if (next.second != 0) { res += data.subList(pos, toPos).sum() * next.second } pos = toPos } resList.add(kotlin.math.abs(res) % 10) } data = resList.toList() } } data class FFTPattern(val basePattern: IntArray) { fun getForElem(index: Int) = sequence { val multiplicity = index + 1 if (multiplicity > 1){ yield(Pair(multiplicity -1, basePattern[0])) } var posInPattern = 1 while (true) { yield(Pair(multiplicity, basePattern[posInPattern])) posInPattern = (posInPattern + 1) % basePattern.size } } } fun main(args: Array<String>) { println("--- Day 16: Flawed Frequency Transmission ---"); val br = BufferedReader(FileReader("puzzle_input/day16-input1.txt")) val rawSignal = br.readLine() day16PartOne(rawSignal) // day16PartTwo(rawSignal) } fun day16PartOne(rawSignal: String) { println("\n--- Part One ---") val signal = Signal(rawSignal) val pattern = FFTPattern(intArrayOf(0, 1, 0, -1)) repeat(100) { signal.calcFFT(pattern) } println("Resulting signal after 100 phases:\n$signal") println("\nResult: ${signal.data.subList(0, 8).joinToString(separator = "") { it.toString() }}") } fun day16PartTwo(rawSignal: String) { println("\n--- Part Two ---") val resultPosition = parseInt(rawSignal.substring(0, 7)) val signal = Signal(buildString { (0..10000).forEach { append(rawSignal) } }) val pattern = FFTPattern(intArrayOf(0, 1, 0, -1)) repeat(100) { signal.calcFFT(pattern) println("Fold $it done...") } println("\nResult: ${signal.data.subList(resultPosition+1, resultPosition+9).joinToString(separator = "") { it.toString() }}") }
0
Kotlin
0
0
6af89b0440cc1d0cc3f07d5a62559aeb68e4511a
2,491
dukesaoc2019
MIT License
src/main/kotlin/marais/villagers/game/GameMap.kt
Gui-Yom
315,269,112
false
null
package marais.villagers.game class GameMap(val width: Int, val height: Int) : Iterable<Position> { val inner = Array(width) { Array(height) { Tile.EMPTY } } operator fun get(pos: Position) = get(pos.x, pos.y) operator fun get(x: Int, y: Int): Tile = inner[x][y] operator fun set(pos: Position, tile: Tile) { inner[pos.x][pos.y] = tile } operator fun contains(pos: Position) = isInBounds(pos) fun isInBounds(pos: Position) = pos.x in 0 until width && pos.y in 0 until height fun isTraversable(pos: Position) = isInBounds(pos) && this[pos].isTraversable() fun neighbors(pos: Position, includeDiagonal: Boolean): List<Position> { return if (includeDiagonal) { arrayOf( pos + (-1 to -1), pos + (-1 to 0), pos + (-1 to 1), pos + (0 to -1), pos + (0 to 1), pos + (1 to -1), pos + (1 to 0), pos + (1 to 1) ) .filter { isTraversable(it) } } else { arrayOf( pos + (-1 to 0), pos + (1 to 0), pos + (0 to -1), pos + (0 to 1) ) .filter { isTraversable(it) } } } /** * pos1 & pos2 are adjacent * * @return the cost to go from pos1 to pos2 */ fun cost(pos1: Position, pos2: Position): Float = this[pos2].cost override fun iterator(): Iterator<Position> = Itr() inner class Itr : Iterator<Position> { // We could also use a modulo var i: Int = 0 var j: Int = -1 override fun hasNext(): Boolean = if (i < width - 1) true else j < height - 1 override fun next(): Position { j += 1 if (j >= height) { i += 1 j = 0 } val pos = Position(i, j) return pos } } } enum class Tile(val cost: Float) { EMPTY(1f), WALL(-1f), HARD(2f), VERYHARD(3f); fun isTraversable() = cost >= 0 }
0
Kotlin
0
0
9665ce10f361d151f8ce33adab650809a02f7d82
2,004
villagers
Apache License 2.0
src/test/kotlin/Day6Test.kt
FredrikFolkesson
320,692,155
false
null
import org.junit.jupiter.api.Test import java.io.File import kotlin.test.assertEquals class Day6Test { @Test fun test_demo_input() { assertEquals( 11, getTotalNumberOfQuestionsThatAnyoneAnsweredYesOn( ("abc\n" + "\n" + "a\n" + "b\n" + "c\n" + "\n" + "ab\n" + "ac\n" + "\n" + "a\n" + "a\n" + "a\n" + "a\n" + "\n" + "b") ) ) } @Test fun test_demo_input_strict() { assertEquals( 6, getTotalNumberOfQuestionsThatEveryoneInAGroupAnsweredYesOn( ("abc\n" + "\n" + "a\n" + "b\n" + "c\n" + "\n" + "ab\n" + "ac\n" + "\n" + "a\n" + "a\n" + "a\n" + "a\n" + "\n" + "b") ) ) } @Test fun test_real_input() { print(getTotalNumberOfQuestionsThatAnyoneAnsweredYesOn(readFileAsString("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day6.txt"))) } @Test fun test_real_input_part_2() { print(getTotalNumberOfQuestionsThatEveryoneInAGroupAnsweredYesOn(readFileAsString("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day6.txt"))) } private fun getTotalNumberOfQuestionsThatAnyoneAnsweredYesOn(input: String): Int { return input.split("\n\n").sumBy { getNumberOfYesAnswersForAnyQuestionForGroup(it) } } private fun getNumberOfYesAnswersForAnyQuestionForGroup(input: String): Int { return input.replace("\n", "").fold(setOf<Char>()) { set, yesAnswer -> set.plus(yesAnswer) }.size } private fun getTotalNumberOfQuestionsThatEveryoneInAGroupAnsweredYesOn(input: String): Int { return input.split("\n\n").sumBy { getNumberOfQuestionsThatEveryoneInTheGroupAnsweredYesOn(it) } } private fun getNumberOfQuestionsThatEveryoneInTheGroupAnsweredYesOn(input: String): Int { return input .replace("\n", "") .fold(mapOf<Char, Int>()) { map, yesAnswer -> map + Pair(yesAnswer, map.getOrDefault(yesAnswer, 0) + 1) } .count { it.value == input.lines().size } } object Task2 { fun sumOfPositiveAnswers2(input: String): Int { return input .split("\n\n") .map { it.split("\n") } .map { list -> list.map { it.toSet() } } .map { it.fold(it[0]) { set, n -> set.intersect(n) } } .sumOf { it.size } } } @Test fun `test group answeres`() { assertEquals(4, getNumberOfYesAnswersForAnyQuestionForGroup("abcx")) assertEquals(4, getNumberOfYesAnswersForAnyQuestionForGroup("abcy")) assertEquals(4, getNumberOfYesAnswersForAnyQuestionForGroup("abcz")) assertEquals(3, getNumberOfYesAnswersForAnyQuestionForGroup("abc")) assertEquals( 3, getNumberOfYesAnswersForAnyQuestionForGroup( "a\n" + "b\n" + "c" ) ) assertEquals( 3, getNumberOfYesAnswersForAnyQuestionForGroup( "ab\n" + "ac" ) ) assertEquals( 1, getNumberOfYesAnswersForAnyQuestionForGroup( "a\n" + "a\n" + "a\n" + "a" ) ) assertEquals(1, getNumberOfYesAnswersForAnyQuestionForGroup("b")) } // private fun getTotalNumberOfQuestionsThatAnyoneAnsweredYesOn(input: String): Int { // return input.split("\n\n").sumBy { getNumberOfYesAnswersForAnyQuestionForGroup(it) } // } // private fun getNumberOfYesAnswersForAnyQuestionForGroup(input: String): Int { // return input.replace("\n", "").fold(setOf<Char>()) { // set, yesAnswer -> set.plus(yesAnswer) // }.size // } object Task1 { fun sumOfPositiveAnswers(input: String): Int { return input .split("\n\n") .map { it.replace("\n", "") } .sumOf { it.toSet().size } } } fun readFileAsLinesUsingUseLines(fileName: String): List<String> = File(fileName).useLines { it.toList() } fun readFileAsString(fileName: String): String = File(fileName).readText() }
0
Kotlin
0
0
79a67f88e1fcf950e77459a4f3343353cfc1d48a
4,981
advent-of-code
MIT License
kotlinP/src/main/java/com/jadyn/kotlinp/leetcode/array/array_0.kt
JadynAi
136,196,478
false
null
package com.jadyn.kotlinp.leetcode.array /** *JadynAi since 5/12/21 */ fun main() { println("test ${removeDuplicates(intArrayOf(0, 0, 1, 1, 1, 2, 2))}") } /** * 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 , * 返回删除后数组的新长度. * * 双指针:快慢指针 * 关键点:实时修改数组的值 * 快指针对比的条件是什么? * * */ fun removeDuplicates(nums: IntArray): Int { if (nums.size <= 1) { return nums.size } var fast = 1 var slow = 1 while (fast < nums.size) { if (nums[fast] != nums[fast - 1]) { nums[slow] = nums[fast] slow++ } fast++ } return slow }
0
Kotlin
6
17
9c5efa0da4346d9f3712333ca02356fa4616a904
757
Kotlin-D
Apache License 2.0
src/chapter2/problem4/solution2.kts
neelkamath
395,940,983
false
null
/* Question: Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. EXAMPLE Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition=5] Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 Answer: Creating one linked list. */ class LinkedListNode(var data: Int, var next: LinkedListNode? = null) { fun partition(value: Int): LinkedListNode { var head: LinkedListNode? = null var tail: LinkedListNode? = null var current: LinkedListNode? = this while (current != null) { val node = LinkedListNode(current.data) if (current.data < value) { node.next = head head = node if (tail == null) tail = head } else { if (tail == null) { tail = node head = tail } else { tail.next = node tail = tail.next } } current = current.next } return head!! } override fun toString(): String { val builder = StringBuilder() var node: LinkedListNode? = this while (node != null) { if (!builder.isEmpty()) builder.append(" -> ") builder.append(node.data) node = node.next } builder.insert(0, "[") builder.append("]") return builder.toString() } } /** Throws an [IndexOutOfBoundsException] if the [Collection] has no elements. */ fun Collection<Int>.toLinkedList(): LinkedListNode { if (size == 0) throw IndexOutOfBoundsException() val head = LinkedListNode(first()) var node = head (1 until size).forEach { node.next = LinkedListNode(elementAt(it)) node = node.next!! } return head } with(listOf(3, 5, 8, 5, 10, 2, 1).toLinkedList()) { println("Input: $this\nOutput: ${partition(5)}") }
0
Kotlin
0
0
4421a061e5bf032368b3f7a4cee924e65b43f690
2,223
ctci-practice
MIT License
src/day14/Cave.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day14 import kotlin.math.sign enum class Detected (val symbol: Char, val isEmpty: Boolean) { AIR ('.', true), ROCK ('#', false), SAND ('o', false), SOURCE ('+', true) } data class Cave (val paths: List<List<Point>>) { var x0: Int = paths.fold<Point, Int> (null) { s, _, _, p -> if (s == null) p.x else Math.min (s, p.x) } as Int var x1: Int = paths.fold<Point, Int> (null) { s, _, _, p -> if (s == null) p.x else Math.max (s, p.x) } as Int var y0: Int = 0 var y1: Int = paths.fold<Point, Int> (null) { s, _, _, p -> if (s == null) p.y else Math.max (s, p.y) } as Int var xw: Int = x1 - x0 + 1 var yw: Int = y1 - y0 + 1 val sand: Int = 500 var grid: Array<Detected> = Array(xw * yw) { Detected.AIR }.apply { paths.forEach { path -> for (i in 0 until path.size - 1) { for (point in path[i] .. path[i + 1]) { this[toIndex (point.x, point.y)] = Detected.ROCK } } this[toIndex (sand, 0)] = Detected.SOURCE } } fun addFloor () { y1 += 2 yw += 2 grid = Array<Detected> (xw * yw) { Detected.AIR }.apply { for (i in grid.indices) { this[i] = grid[i] } for (i in 0 until xw) { this[grid.size + xw + i] = Detected.ROCK } } return } /** * Expands the cave mapping either to the left (-1) or right (1). */ fun grow (direction: Int, times: Int = 1) { repeat (times) { val cs0 = CoordinateSystem (xw, yw, x0, y0) if (direction < 0) { x0 -= 1 } else { x1 += 1 } xw += 1 val cs1 = CoordinateSystem (xw, yw, x0, y0) grid = Array (xw * yw) { Detected.AIR }.apply { for (i in grid.indices) { val p = cs0.fromIndex (i) this[cs1.toIndex (p)] = grid[i] } if (direction < 0) { this[cs1.toIndex (x0, y1)] = Detected.ROCK } else { this[cs1.toIndex (x1, y1)] = Detected.ROCK } } } return } fun contains (point: Point): Boolean { val (x, y) = point return x in x0 .. x1 && y in y0 .. y1 } fun newSand (): Point? { var curr = Point (sand, 0) outer@while (true) { if (! grid[toIndex (curr)].isEmpty) { return null } for (dx in listOf (0, -1, 1)) { val maybe = curr.move (dx, 1) if (! contains (maybe)) { return null } if (grid[toIndex (maybe)].isEmpty) { curr = maybe continue@outer } } grid[toIndex (curr)] = Detected.SAND return curr } // NOT REACHED } fun newSand2 (): Point? { var curr = Point (sand, 0) outer@while (true) { if (! grid[toIndex (curr)].isEmpty) { return null } for (dx in listOf (0, -1, 1)) { val maybe = curr.move (dx, 1) if (! contains (maybe)) { grow (dx) } if (grid[toIndex (maybe)].isEmpty) { curr = maybe continue@outer } } grid[toIndex (curr)] = Detected.SAND return curr } // NOT REACHED } fun toIndex (x: Int, y: Int): Int = (y - y0) * xw + (x - x0) fun toIndex (point: Point) = toIndex (point.x, point.y) fun dump () { println (toString ()) return } override fun toString (): String { val xw = x1.toString().length val yw = y1.toString().length val buf = StringBuffer () for (i in 0 until xw) { buf.append (" ".repeat (yw + 2)) buf.append (x0.toString()[i]) buf.append (" ".repeat (x1 - x0 - 1)) buf.append (x1.toString()[i]) buf.append ("\n") } for (y in y0 .. y1) { buf.append (String.format ("%${yw}d", y)) buf.append (": ") for (x in x0 .. x1) { buf.append (grid[toIndex (x, y)].symbol) } buf.append ("\n") } return buf.toString () } } fun main () { val example = true val cave = readCave (example) cave.dump () cave.addFloor () cave.dump () cave.grow (-1, 5) cave.grow (1, 5) cave.dump () return } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
4,790
advent_of_code_2022
Apache License 2.0
src/main/kotlin/g0501_0600/s0547_number_of_provinces/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0547_number_of_provinces // #Medium #Depth_First_Search #Breadth_First_Search #Graph #Union_Find // #Algorithm_II_Day_6_Breadth_First_Search_Depth_First_Search // #Graph_Theory_I_Day_8_Standard_Traversal #Level_2_Day_19_Union_Find // #2023_01_17_Time_229_ms_(79.73%)_Space_43_MB_(66.22%) class Solution { fun findCircleNum(arr: Array<IntArray>): Int { val parent = IntArray(arr.size) parent.fill(-1) var ans = 0 for (i in 0 until arr.size - 1) { for (j in i + 1 until arr[i].size) { if (arr[i][j] == 1) { ans += union(i, j, parent) } } } return arr.size - ans } private fun union(a: Int, b: Int, arr: IntArray): Int { val ga = find(a, arr) val gb = find(b, arr) if (ga != gb) { arr[gb] = ga return 1 } return 0 } private fun find(a: Int, arr: IntArray): Int { if (arr[a] == -1) { return a } arr[a] = find(arr[a], arr) return arr[a] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,116
LeetCode-in-Kotlin
MIT License
src/main/kotlin/days/Day9.kt
wmichaelshirk
315,495,224
false
null
package days class Day9 : Day(9) { private fun sums(input: Iterable<Long>): Sequence<Long> = sequence { input.forEachIndexed { i, a -> input.forEachIndexed { j, b -> if (i != j) yield(a + b) } } } private val inputData = inputList.map(String::toLong) override fun partOne(): Long? { val preambleSize = 25 return inputData .windowed(preambleSize + 1) .find { val target = it.last() val preamble = it.dropLast(1) !sums(preamble).contains(target) }?.last() } override fun partTwo(): Long { val invalidNumber = partOne() ?: 0L println("target: $invalidNumber") val foo = inputData .asSequence() .withIndex() .drop(1) .mapNotNull { el -> var sum = 0L val target = inputData.drop(el.index - 1) .takeWhile { sum += it sum <= invalidNumber } if (target.sum() == invalidNumber) target else null }.find { it.count() > 1 } return (foo?.minOrNull() ?: 0) + (foo?.maxOrNull() ?: 0) } }
0
Kotlin
0
0
b36e5236f81e5368f9f6dbed09a9e4a8d3da8e30
1,325
2020-Advent-of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/kt/kotlinalgs/app/tree/FirstCommonAncestor.ws.kts
sjaindl
384,471,324
false
null
println("test") val root = Node(20) root.left = Node(10) root.right = Node(30) root.left?.right = Node(15) root.left?.right?.right = Node(17) root.left?.left = Node(5) root.left?.left?.left = Node(3) root.left?.left?.right = Node(7) val tree = BinarySearchTree<Int>() println(tree.firstCommonAncestor( // 10 root.left!!.left!!.right!!, // 7 root.left!!.right!!.right!!, // 17 root // 20 )) data class Node<T>( val value: T, var left: Node<T>? = null, var right: Node<T>? = null ) class BinarySearchTree<T> { fun firstCommonAncestor(p: Node<T>, q: Node<T>, root: Node<T>): Node<T>? { // recursive search return firstCommonAncestorRec(p, q, root).ancestor } fun firstCommonAncestorRec(p: Node<T>, q: Node<T>, cur: Node<T>?): Result<T> { if (cur == null) return Result(false, false, null) val left = firstCommonAncestorRec(p, q, cur.left) if (left.ancestor != null) return left val right = firstCommonAncestorRec(p, q, cur.right) if (right.ancestor != null) return right val containsP = left.containsP || right.containsP || cur == p val containsQ = left.containsQ || right.containsQ || cur == q val ancestor = if(containsP && containsQ) cur else null return Result(containsP, containsQ, ancestor) } data class Result<T>( val containsP: Boolean, val containsQ: Boolean, val ancestor: Node<T>? ) }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
1,463
KotlinAlgs
MIT License
src/days/Day11.kt
EnergyFusion
572,490,067
false
{"Kotlin": 48323}
import java.io.BufferedReader fun main() { val day = 11 fun createMonkeys(inputReader: BufferedReader): List<Monkey> { val monkeys = mutableListOf<Monkey>() var currentListOfItems = mutableListOf<Long>() var testStrings = mutableListOf<String>() var testDiv = 0L lateinit var operation: (Long) -> Long lateinit var test: (Long) -> Int inputReader.forEachLine { line -> when { line.trim().isEmpty() -> { monkeys.add(Monkey(0L, testDiv, currentListOfItems, operation, test)) currentListOfItems = mutableListOf() testStrings = mutableListOf() } line.trim().startsWith("Starting items:") -> { val numsString = line.substringAfter(":").trim() val nums = numsString.split(",") for (num in nums) { currentListOfItems.add(num.trim().toLong()) } } line.trim().startsWith("Operation:") -> { val opString = line.substringAfter(":").substringAfter("=").substringAfter("d").trim() val ops = opString.split(" ") val op = ops[0].trim() val v = ops[1].trim() when (op) { "*" -> { operation = if (v == "old") { {old -> old * old} } else { {old -> old * v.toInt()} } } "+" -> { operation = if (v == "old") { {old -> old + old} } else { {old -> old + v.toLong()} } } } } line.trim().startsWith("Test:") -> { testStrings.add(line.substringAfter(":")) } line.trim().startsWith("If true:") -> { testStrings.add(line.substringAfter(":")) } line.trim().startsWith("If false:") -> { testStrings.add(line.substringAfter(":").trim()) val div = testStrings[0].split(" ").last().trim().toLong() testDiv = div val tMonkeyIndex = testStrings[1].split(" ").last().trim().toInt() val fMonkeyIndex = testStrings[2].split(" ").last().trim().toInt() test = {worry -> if (worry % div == 0L) { tMonkeyIndex } else { fMonkeyIndex } } } else -> {} } } monkeys.add(Monkey(0, testDiv, currentListOfItems, operation, test)) return monkeys.toList() } fun playRounds(monkeys: List<Monkey>, rounds: Int, worryLevelFun: (Long) -> Long) { for (i in 0..rounds) { for (monkey in monkeys) { for (item in monkey.items) { monkey.inspections++ var worryLevel = monkey.operation(item) worryLevel = worryLevelFun(worryLevel) val nextMonkey = monkey.test(worryLevel) monkeys[nextMonkey].items.add(worryLevel) } monkey.items.clear() } } } fun part1(inputReader: BufferedReader): Long { val monkeys = createMonkeys(inputReader) // println(monkeys) playRounds(monkeys, 19) {worryLevel -> worryLevel/3} // println() // println(monkeys) // println() val result = monkeys.map { it.inspections }.sorted().takeLast(2).reduce{ left, right -> left * right } println(result) println() return result } fun part2(inputReader: BufferedReader): Long { val monkeys = createMonkeys(inputReader) // println(monkeys) val modProduct = monkeys.map { it.testDiv }.reduce {left, right -> left*right} playRounds(monkeys, 9999) {worryLevel -> worryLevel%modProduct} // println(monkeys) val result = monkeys.map { it.inspections }.sorted().takeLast(2).reduce{ left, right -> left * right } println(result) return result } val testInputReader = readBufferedInput("tests/Day%02d".format(day)) // check(part1(testInputReader) == 10605L) check(part2(testInputReader) == 2713310158L) val input = readBufferedInput("input/Day%02d".format(day)) // println(part1(input)) println(part2(input)) } data class Monkey(var inspections: Long, val testDiv: Long, val items: MutableList<Long>, val operation: (Long) -> Long, val test: (Long) -> Int)
0
Kotlin
0
0
06fb8085a8b1838289a4e1599e2135cb5e28c1bf
5,118
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/nl/meine/aoc/_2023/Day5.kt
mtoonen
158,697,380
false
{"Kotlin": 201978, "Java": 138385}
package nl.meine.aoc._2023 class Day5 { fun one( seeds: String, seed2soil: String, soil2fertilizer: String, fertilizer2water: String, water2light: String, light2temp: String, temp2humid: String, humidity2loc: String ): Long { val seed2soilMap = parseString(seed2soil) val soil2fertilizerMap = parseString(soil2fertilizer) val fertilizer2waterMap = parseString(fertilizer2water) val water2lightMap = parseString(water2light) val light2tempMap = parseString(light2temp) val temp2humidMap = parseString(temp2humid) val humidity2locMap = parseString(humidity2loc) val lines = seeds.split(" ") .map { it.toLong() } .map { getLocation( it, seed2soilMap, soil2fertilizerMap, fertilizer2waterMap, water2lightMap, light2tempMap, temp2humidMap, humidity2locMap ) } .min() return lines } fun getLocation( seed: Long, seed2soilMap: Intervals, soil2fertilizerMap: Intervals, fertilizer2waterMap: Intervals, water2lightMap: Intervals, light2tempMap: Intervals, temp2humidMap: Intervals, humidity2locMap: Intervals, ): Long { val soil = getAnswer(seed2soilMap, seed) val fert = getAnswer(soil2fertilizerMap, soil) val water = getAnswer(fertilizer2waterMap, fert) val light = getAnswer(water2lightMap, water) val temp = getAnswer(light2tempMap, light) val humid = getAnswer(temp2humidMap, temp) val loc = getAnswer(humidity2locMap, humid) return loc } fun parseString(input: String): Intervals { val ints = input.split("\n") .map { parseLine(it) } return Intervals(ints) } fun parseLine(line: String): Interval { val tokens = line.split(" ") val destStart = tokens[0].toLong() val sourceStart = tokens[1].toLong() val length = tokens[2].toLong() return Interval(sourceStart, length, destStart) } fun getAnswer(intervals: Intervals, start: Long): Long { return intervals.contains(start) } fun two( seeds: String, seed2soil: String, soil2fertilizer: String, fertilizer2water: String, water2light: String, light2temp: String, temp2humid: String, humidity2loc: String ): Long { val seedMap = parseSeeds(seeds) val seed2soilMap = parseString(seed2soil) val soil2fertilizerMap = parseString(soil2fertilizer) val fertilizer2waterMap = parseString(fertilizer2water) val water2lightMap = parseString(water2light) val light2tempMap = parseString(light2temp) val temp2humidMap = parseString(temp2humid) val humidity2locMap = parseString(humidity2loc) // val seedss = seeds.split(" ").first().substringAfter(" ").split(" ").map { it.toLong() }.chunked(2).map { it.first()..<it.first() + it.last() } val locs =humidity2locMap.getValuesList() var lowest:Long=99999 for(loc in locs){ val humid = humidity2locMap.containsReverse(loc) val temp =temp2humidMap.containsReverse(humid) val light = light2tempMap.containsReverse(temp) val water = water2lightMap.containsReverse(light) val fertilizer = fertilizer2waterMap.containsReverse(water) val soil = soil2fertilizerMap.containsReverse(fertilizer) val seed = seed2soilMap.containsReverse(soil) val containsSeed =containsSeed(seed,seedMap) if(containsSeed){ lowest=loc break } } //humidity2locMap.map return lowest } fun containsSeed(seed:Long, seeds:MutableList<Pair<Long, Long>>):Boolean{ for(range in seeds){ if(seed >= range.first && seed <= range.second){ return true } } return false } fun parseSeeds(input: String): MutableList<Pair<Long, Long>> { val seeds = input.split(" ") val pairs: MutableList<Pair<Long, Long>> = mutableListOf() for (i in 0..<seeds.size step 2) { val start = seeds[i].toLong() val length = seeds[i + 1].toLong() pairs += Pair(start, start + length) } return pairs } } //20358600 //20358600 fun main() { val seeds = "2149186375 163827995 1217693442 67424215 365381741 74637275 1627905362 77016740 22956580 60539394 586585112 391263016 2740196667 355728559 2326609724 132259842 2479354214 184627854 3683286274 337630529" val seed2soil = """3229936931 3770233758 236381937 3646926122 3757559297 12674461 938394995 626913497 352323383 2516043511 0 51589736 3224558845 3632370674 5378086 3154383669 3733142176 3946275 2567633247 1181073360 126906268 0 1307979628 138466492 286338057 1446446120 652056938 3626455276 3737088451 20470846 1290718378 2229802472 3472788 2327189933 569558202 57355295 3026168476 4006615695 128215193 3158329944 3566141773 66228901 3915379752 3026168476 379587544 1627676565 2233275260 461264255 2515844642 385075135 198869 2088940820 385274004 184284198 3819986336 3637748760 95393416 2273225018 979236880 53964915 3466318868 4134830888 160136408 1294191166 51589736 333485399 138466492 1033201795 147871565 3659600583 3405756020 160385753 2384545228 2098503058 131299414""" val soil2fertilizer = """2991238558 2151391892 144378737 1183223769 2295770629 113964757 1297188526 1089334530 386627390 1089334530 3060803751 93889239 1683815916 3154692990 1140274306 3135617295 2409735386 483920029 4282117858 2138542454 12849438 3619537324 1475961920 662580534 2824090222 2893655415 167148336""" val fertilizer2water = """1781174267 3172095614 252304554 1777350394 205858418 3823873 3481300219 2900371834 228938690 629285174 3911240322 150964034 4139459951 4244437788 50529508 2729976567 269940901 128857098 910342261 3129310524 42785090 1576648209 1091396587 111088326 1296874963 3585901272 233869698 3710238909 168200356 37658062 1687736535 4154823929 89613859 953127351 4062204356 92619573 552009002 158449435 9750921 2719891798 1038135909 10084769 3223980609 529688260 257319610 2033478821 1532972418 624586061 2858833665 2597021594 303350240 4096284042 1048220678 43175909 626349664 526752750 2935510 794975913 3834497675 58843081 3765796537 1202484913 330487505 853818994 3424400168 56523267 3747896971 3893340756 17899566 1530744661 2157558479 19983260 1045746924 787007870 251128039 132529147 2177541739 419479855 780249208 3819770970 14726705 3163721999 209682291 60258610 2658064882 463387740 61826916 3162183905 525214656 1538094 4189989459 3480923435 104977837 1550727921 132529147 25920288 561759923 398797999 64589741""" val water2light = """3089483450 929490911 132962403 2505150397 1675046001 88332095 3674189474 3881789775 95079143 487699292 2280047063 119590919 2691722732 2904437110 186305619 734683438 2471684433 263879127 424005934 1311132479 63693358 2066817488 1626942755 48103246 4220411699 3381137532 52192686 1272878735 2440662693 31021740 2659005903 2399637982 32716829 1141175611 3090742729 131703124 1324856035 480042365 41880678 4078508529 3341878136 23998484 3392898998 4013676820 206668183 1819185760 360597775 53921179 1584721442 1933117275 234464318 607290211 802097684 127393227 2114920734 1374825837 252116918 4272604385 3859426864 22362911 2036056683 2873676305 30760805 3056075412 768689646 33408038 1375280832 8544119 209440610 112465470 1062453314 248679165 1303900475 521923043 20955560 3341878136 3475705318 51020862 3972027287 3537397184 64106142 3811788516 3601503326 69230778 361144635 542878603 62861299 1366736713 0 8544119 3769268617 3816906965 42519899 1873106939 605739902 162949744 2878028351 2432354811 8307882 2886336233 1763378096 169739179 4130652814 3365876620 15260912 3599567181 4220345003 74622293 0 2167581593 112465470 4209740695 3526726180 10671004 2367037652 2735563560 138112745 3881019294 3976868918 8662101 4036133429 3433330218 42375100 4102507013 3985531019 28145801 3889681395 3670734104 82345892 2593482492 414518954 65523411 4145913726 3753079996 63826969 998562565 217984729 142613046""" val light2temperature = """1941760763 1585007922 25353840 4031153040 1610361762 71241272 4225876754 972893749 69090542 1426899362 2063678063 17216958 852041331 3169727243 149223547 2700225684 2869762423 88404546 1641196592 702579563 136462841 4102394312 1461525480 123482442 1444116320 3910271612 16089747 458934721 4276740328 18226968 2302105532 3036223883 133503360 2537110151 3618113777 89051179 26320902 0 26087247 2788630230 2763464440 106297983 1303054891 656323277 45787557 3803268902 1233641342 227884138 1941402499 3971401567 358264 1001264878 1681603034 301790013 3611611851 1041984291 191657051 3414223295 458934721 197388556 477161689 839042404 133851345 2469953812 3707164956 67156339 2238153332 3971759831 63952200 2435608892 3583768857 34344920 1460206067 3926361359 45040208 1777659433 702110834 468729 1967114603 2057457401 6220662 1348842448 2958166969 78056914 1778128162 2080895021 163274337 1505246275 3774321295 135950317 1973335265 3318950790 264818067 611013034 4035712031 241028297 2894928213 2244169358 519295082 2626161330 1983393047 74064354 0 26087247 26320902""" val temperature2humidity = """2565293924 3936499516 66436363 3537039881 3587821379 320595386 493156596 2133973986 271025354 2631730287 2862507138 166475062 3857635267 3531891893 55929486 2014053518 0 390945822 3340501666 4098429081 196538215 3198273266 4002935879 95493202 4210777967 3447702564 84189329 4119758949 2771488120 91019018 2826288100 3028982200 371985166 764181950 971110280 681277242 401253963 2042071353 91902633 2798205349 3908416765 28082751 3913564753 2565293924 206194196 1445459192 390945822 284651564 1730110756 1652387522 283942762 0 1936330284 105741069 105741069 675597386 295512894 3293766468 3400967366 46735198""" val humidity2location = """2165947883 243164825 185957029 4117181009 1886348582 84328450 1977790778 3003241907 52295181 2621047317 2603926811 3541080 20358599 0 34147766 1910216465 2289280284 67574313 1435321221 2953430520 49811387 3565107101 532688453 509094142 231708454 3055537088 20702669 96040833 2127032834 135667621 2351904912 1321002996 61162541 3338550958 2262700455 26579829 3365130787 429121854 81629660 2723669224 4076568620 55137108 1823192023 3076239757 48333179 4074201243 2558055095 42979766 2413067453 1970677032 156355802 252411123 3815127871 123756213 1871525202 1209106389 38691263 0 34147766 20358599 2616053742 510751514 4993575 2599888132 4283810027 11157269 379059286 3938884084 132676195 569836988 3124572936 428164512 376167336 2601034861 2891950 3463703811 141761535 101403290 1043722202 4131705728 152104299 4201509459 3794875378 20252493 2163402773 1539347871 2545110 1686333106 1072247472 136858917 998001500 96040833 45720702 4221761952 1247797652 73205344 2030085959 1781387701 104960881 2569423255 1041782595 30464877 2135046840 3552737448 28355933 3446760447 515745089 16943364 2778806332 2607467891 345962629 1195826501 1541892981 239494720 1485132608 2356854597 201200498 2611045401 4071560279 5008341 3124768961 3581093381 213781997 511735481 1481246364 58101507 2624588397 1382165537 99080827""" val ins = Day5(); println( ins.two( seeds, seed2soil, soil2fertilizer, fertilizer2water, water2light, light2temperature, temperature2humidity, humidity2location ) ) } class Intervals(val intervals: List<Interval>) { fun getValuesList():List<Long>{ return intervals.map { it.getValuesList() } .flatten() .toSet() .sorted() // .map { it.toList() } } fun containsReverse(point:Long):Long{ return intervals .filter { it.containsPointReverse(point) } .map { it.containsReverse(point) } .firstOrNull() ?: point } fun contains(point: Long): Long { return intervals .filter { it.containsPoint(point) } .map { it.contains(point) } .firstOrNull() ?: point } } class Interval(val startKey: Long, val end: Long, val startValue: Long) { fun getValuesList():Set<Long>{ return (0..(startValue+end)).toSet() } fun containsReverse(point: Long): Long { return if (point >= startValue && point <= end + startValue) { val a =startKey+(point - startValue) a } else { point } } fun contains(point: Long): Long { return if (point >= startKey && point <= end + startKey) { startKey + (point - startKey) } else { point } } fun containsPoint(point: Long): Boolean { return point >= startKey && point <= end + startKey } fun containsPointReverse(point: Long): Boolean { return point >= startValue && point <= end + startValue } }
0
Kotlin
0
0
a36addef07f61072cbf4c7c71adf2236a53959a5
13,408
advent-code
MIT License
src/Day14/Day14.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day14 import readInput import kotlin.math.* class RockStructure(var points: List<Pair<Int, Int>>) { fun maxX(): Int { return points.maxOf { it.first } } fun maxY(): Int { return points.maxOf { it.second } } } class MazePart1() { var matrix: Array<Array<Int>> = arrayOf(arrayOf()) fun print() { for(row in matrix) { for(value in row) { if(value == 0) { print("-") } else { print("X") } } println() } } fun runSimulation(): Int { var piecesOfSand = 0 while(runSimulationForOnePieceOfSand()) { piecesOfSand++ } return piecesOfSand } fun runSimulationForOnePieceOfSand(): Boolean { var x = 500 var y = -1 while(true) { if (y == matrix.size - 1) { return false } if(matrix[y + 1][x] == 0) { y++ } else { if(x == 0) { return false } if(matrix[y + 1][x-1] == 0){ y++ x-- } else { if(x == matrix[0].size - 1) { return false } if(matrix[y+1][x+1] == 0) { y++ x++ } else { matrix[y][x] = 1 return true } } } } } fun processInput(input: List<String>) { var rocks = mutableListOf<RockStructure>() for (row in input) { val rockFormations = row .split("->") .map { it.trim() } .map { it.split(",") } .map { Pair(it[0].toInt(), it[1].toInt()) } rocks.add(RockStructure(rockFormations)) } val matrixX = max(500, rocks.maxOf { it.maxX() } + 1) val matrixY = rocks.maxOf { it.maxY() } + 1 matrix = Array(matrixY) { Array(matrixX) { 0 } } for (rock in rocks) { for (pointIndex in 0 until rock.points.size - 1) { val firstRock = rock.points[pointIndex] val secondRock = rock.points[pointIndex + 1] val maxX = max(firstRock.first, secondRock.first) val minX = min(firstRock.first, secondRock.first) val maxY = max(firstRock.second, secondRock.second) val minY = min(firstRock.second, secondRock.second) for (x in minX..maxX) { for (y in minY..maxY) { matrix[y][x] = 1 } } } } } } class MazePart2() { var matrix: Array<Array<Int>> = arrayOf(arrayOf()) fun print() { for(row in matrix) { for(value in row) { if(value == 0) { print("-") } else { print("X") } } println() } } fun runSimulation(): Int { var piecesOfSand = 0 while(runSimulationForOnePieceOfSand()) { piecesOfSand++ } return piecesOfSand + 1 } fun runSimulationForOnePieceOfSand(): Boolean { var x = 500 var y = -1 while(true) { if(matrix[y + 1][x] == 0) { y++ } else if(matrix[y + 1][x-1] == 0){ y++ x-- } else if(matrix[y+1][x+1] == 0) { y++ x++ } else { if(x == 500 && y == 0) { return false } matrix[y][x] = 1 return true } } } fun processInput(input: List<String>) { var rocks = mutableListOf<RockStructure>() for (row in input) { val rockFormations = row .split("->") .map { it.trim() } .map { it.split(",") } .map { Pair(it[0].toInt(), it[1].toInt()) } rocks.add(RockStructure(rockFormations)) } val matrixX = 50000 //this should be big enough val matrixY = rocks.maxOf { it.maxY() } + 3 matrix = Array(matrixY) { Array(matrixX) { 0 } } for (rock in rocks) { for (pointIndex in 0 until rock.points.size - 1) { val firstRock = rock.points[pointIndex] val secondRock = rock.points[pointIndex + 1] val maxX = max(firstRock.first, secondRock.first) val minX = min(firstRock.first, secondRock.first) val maxY = max(firstRock.second, secondRock.second) val minY = min(firstRock.second, secondRock.second) for (x in minX..maxX) { for (y in minY..maxY) { matrix[y][x] = 1 } } } } for(x in 0 until matrixX) { matrix[matrixY - 1][x] = 1 //install the floor } } } fun main() { fun part1(input: List<String>): Int { val maze = MazePart1() maze.processInput(input) return maze.runSimulation() } fun part2(input: List<String>): Int { val maze = MazePart2() maze.processInput(input) return maze.runSimulation() } val testInput = readInput("Day14","Day14_test") println(part1(testInput)) check(part1(testInput) == 24) println(part2(testInput)) check(part2(testInput) == 93) val input = readInput("Day14","Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
5,898
advent-of-code-2022
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/leetcode/MinimumAbsoluteDifferenceBSTTest.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 java.util.stream.Stream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class MinimumAbsoluteDifferenceBSTTest<out T : MinimumAbsoluteDifferenceBST>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of( TreeNode(4).apply { left = TreeNode(2).apply { left = TreeNode(1) right = TreeNode(3) } right = TreeNode(6) }, 1, ), Arguments.of( TreeNode(1).apply { left = TreeNode(0) right = TreeNode(48).apply { left = TreeNode(12) right = TreeNode(49) } }, 1, ), ) } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `get minimum difference test`(root: TreeNode, expected: Int) { val actual = strategy.getMinimumDifference(root) assertThat(actual).isEqualTo(expected) } } class MinimumAbsoluteDifferenceBSTDFSTest : MinimumAbsoluteDifferenceBSTTest<MinimumAbsoluteDifferenceBST>( MinimumAbsoluteDifferenceBSTDFS(), ) class MinimumAbsoluteDifferenceBSTInOrderTest : MinimumAbsoluteDifferenceBSTTest<MinimumAbsoluteDifferenceBST>( MinimumAbsoluteDifferenceBSTInOrder(), ) class MinimumAbsoluteDifferenceBSTInOrderOptTest : MinimumAbsoluteDifferenceBSTTest<MinimumAbsoluteDifferenceBST>( MinimumAbsoluteDifferenceBSTInOrderOpt(), )
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,647
kotlab
Apache License 2.0
src/Day10.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
import java.lang.RuntimeException import kotlin.math.abs fun main() { fun List<String>.parse(): List<Int?> { val addPattern = "addx (?<num>-?\\d+)".toRegex() return map { val addx = addPattern.matchEntire(it)?.groups?.get("num")?.value when { it == "noop" -> { null } addx != null -> { addx.toInt() } else -> { throw RuntimeException("Unknown pattern $it") } } } } fun part1(input: List<String>): Int { var sum = 0 var registerX = 1 val commands = input.parse() var ip = 0 var cycle = 1 var firstAddXCycle = true while (ip < commands.size) { val current = commands[ip] if ((cycle - 20) % 40 == 0) { sum += cycle * registerX } when (current) { is Int -> { if (firstAddXCycle) { firstAddXCycle = false } else { firstAddXCycle = true registerX += current ip += 1 } } else -> { ip += 1 } } cycle += 1 } return sum } fun part2(input: List<String>): String { val crt = MutableList(40 * 6) { 'x' } var sum = 0 var registerX = 1 val commands = input.parse() var ip = 0 var cycle = 1 var firstAddXCycle = true while (ip < commands.size) { val current = commands[ip] crt[cycle - 1] = if (abs((cycle - 1) % 40 - registerX) <= 1) { '#' } else { '.' } if ((cycle - 20) % 40 == 0) { sum += cycle * registerX } when (current) { is Int -> { if (firstAddXCycle) { firstAddXCycle = false } else { firstAddXCycle = true registerX += current ip += 1 } } else -> { ip += 1 } } cycle += 1 } return crt.chunked(40).joinToString("\n") { it.joinToString("") } } val testInput = readInput("Day10_test") val input = readInput("Day10") assert(part1(testInput), 13140) println(part1(input)) val expected = """##..##..##..##..##..##..##..##..##..##.. |###...###...###...###...###...###...###. |####....####....####....####....####.... |#####.....#####.....#####.....#####..... |######......######......######......#### |#######.......#######.......#######.....""".trimMargin() assert(part2(testInput), expected) println() println(part2(input)) } // Time: 09:36
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
3,192
advent-of-code-2022
Apache License 2.0
aoc-2023/src/main/kotlin/aoc/aoc19.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.getDayInput val testInput = """ px{a<2006:qkq,m>2090:A,rfg} pv{a>1716:R,A} lnx{m>1548:A,A} rfg{s<537:gd,x>2440:R,A} qs{s>3448:A,lnx} qkq{x<1416:A,crn} crn{x>2662:A,R} in{s<1351:px,qqz} qqz{s>2770:qs,m<1801:hdj,R} gd{a>3333:R,R} hdj{m>838:A,pv} {x=787,m=2655,a=1222,s=2876} {x=1679,m=44,a=2067,s=496} {x=2036,m=264,a=79,s=2244} {x=2461,m=1339,a=466,s=291} {x=2127,m=1623,a=2188,s=1013} """.parselines fun String.parseWorkflow(): Workflow { val id = substringBefore("{") val rules = substringAfter("{").substringBefore("}").split(",") return Workflow(id, rules.dropLast(1).map { it.parseRule() }, rules.last()) } fun String.parseRule() = Rule(get(0), get(1), drop(2).substringBefore(":").toInt(), substringAfter(":")) fun String.parseRating(): Rating { val parts = drop(1).dropLast(1).split(",").map { it.split("=").let { it[0] to it[1].toInt() } }.toMap() return Rating(parts["x"]!!, parts["m"]!!, parts["a"]!!, parts["s"]!!) } class Rating(val x: Int, val m: Int, val a: Int, val s: Int) class RatingRange(val xr: IntRange, val mr: IntRange, val ar: IntRange, val sr: IntRange) { fun size(): Long = xr.count().toLong() * mr.count().toLong() * ar.count().toLong() * sr.count().toLong() fun splitOnX(trueRange: IntRange, falseRange: IntRange, result: String): Map<RatingRange, String?> { val trueX = xr.intersectRange(trueRange)?.let { RatingRange(it, mr, ar, sr) to result } val falseX = xr.intersectRange(falseRange)?.let { RatingRange(it, mr, ar, sr) to null } return listOfNotNull(trueX, falseX).toMap() } fun splitOnM(trueRange: IntRange, falseRange: IntRange, result: String): Map<RatingRange, String?> { val trueM = mr.intersectRange(trueRange)?.let { RatingRange(xr, it, ar, sr) to result } val falseM = mr.intersectRange(falseRange)?.let { RatingRange(xr, it, ar, sr) to null } return listOfNotNull(trueM, falseM).toMap() } fun splitOnA(trueRange: IntRange, falseRange: IntRange, result: String): Map<RatingRange, String?> { val trueA = ar.intersectRange(trueRange)?.let { RatingRange(xr, mr, it, sr) to result } val falseA = ar.intersectRange(falseRange)?.let { RatingRange(xr, mr, it, sr) to null } return listOfNotNull(trueA, falseA).toMap() } fun splitOnS(trueRange: IntRange, falseRange: IntRange, result: String): Map<RatingRange, String?> { val trueS = sr.intersectRange(trueRange)?.let { RatingRange(xr, mr, ar, it) to result } val falseS = sr.intersectRange(falseRange)?.let { RatingRange(xr, mr, ar, it) to null } return listOfNotNull(trueS, falseS).toMap() } } fun IntRange.intersectRange(other: IntRange): IntRange? = when { last < other.first || other.last < first -> null first <= other.first && other.last <= last -> other other.first <= first && last <= other.last -> this first <= other.first && last <= other.last -> other.first..last other.first <= first && other.last <= last -> first..other.last else -> error("Unknown intersection of $this and $other") } class Workflow(val id: String, val rules: List<Rule>, val defResult: String) { fun test(rating: Rating): String { var result: String? rules.forEach { result = it.test(rating) if (result != null) return result!! } return defResult } fun test(ratingRange: RatingRange): Map<RatingRange, String> { val result = mutableMapOf<RatingRange, String>() var processing = listOf(ratingRange) rules.forEach { r -> val processNext = mutableListOf<RatingRange>() processing.forEach { r.test(it).forEach { (range, label) -> if (label == null) processNext += range else result[range] = label } } processing = processNext } processing.forEach { result[it] = defResult } return result } } class Rule(val ratingVar: Char, val testOp: Char, val testVal: Int, val result: String) { fun Rating.value() = when (ratingVar) { 'x' -> x 'm' -> m 'a' -> a 's' -> s else -> error("Unknown test variable $ratingVar") } val test: (Int) -> Boolean = when (testOp) { '>' -> { it -> it > testVal } '<' -> { it -> it < testVal } else -> error("Unknown test operator $testOp") } val trueRange = when (testOp) { '>' -> testVal+1..4000 '<' -> 1..testVal-1 else -> error("Unknown test operator $testOp") } val falseRange = when (testOp) { '>' -> 1..testVal '<' -> testVal..4000 else -> error("Unknown test operator $testOp") } fun Rating.test(): Boolean = test(value()) fun test(rating: Rating) = if (rating.test()) result else null fun test(ratingRange: RatingRange): Map<RatingRange, String?> { return when (ratingVar) { 'x' -> ratingRange.splitOnX(trueRange, falseRange, result) 'm' -> ratingRange.splitOnM(trueRange, falseRange, result) 'a' -> ratingRange.splitOnA(trueRange, falseRange, result) 's' -> ratingRange.splitOnS(trueRange, falseRange, result) else -> error("Unknown test variable $ratingVar") } } } fun Map<String, Workflow>.test(rating: Rating): String { val start = get("in")!! var result: String = start.test(rating) while (result != "A" && result != "R") { result = get(result)!!.test(rating) } return result } // part 1 fun List<String>.part1(): Int { val str = joinToString("\n").split("\n\n") val workflows = str[0].split("\n").map { it.parseWorkflow() }.associateBy { it.id } val ratings = str[1].split("\n").map { it.parseRating() } return ratings.filter { workflows.test(it) == "A" }.sumOf { it.x + it.m + it.a + it.s } } // part 2 fun List<String>.part2(): Long { val str = joinToString("\n").split("\n\n") val workflows = str[0].split("\n").map { it.parseWorkflow() }.associateBy { it.id } val ranges = RatingRange(1..4000, 1..4000, 1..4000, 1..4000) var tasks = mutableMapOf("in" to mutableListOf(ranges)) val accepted = mutableListOf<RatingRange>() val rejected = mutableListOf<RatingRange>() while (tasks.isNotEmpty()) { val newTasks = mutableMapOf<String, MutableList<RatingRange>>() tasks.forEach { (w, ranges) -> val workflow = workflows[w]!! ranges.flatMap { workflow.test(it).entries }.forEach { (range, result) -> when (result) { "A" -> accepted += range "R" -> rejected += range else -> newTasks.getOrPut(result) { mutableListOf() } += range } } } tasks = newTasks } return accepted.sumOf { it.size() } } // calculate answers val day = 19 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
7,438
advent-of-code
Apache License 2.0
2022/src/Day21.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src class NewMonkey { var id: String = "" var hasYelled: Boolean = false var operation: String = "" var firstOperand: String = "" var secondOperand: String = "" var firstLong: Long = Long.MIN_VALUE var secondLong: Long = Long.MIN_VALUE var result: Long = Long.MIN_VALUE constructor(id: String, operation: String, firstOperand: String, secondOperand: String) { this.id = id this.operation = operation this.hasYelled = false this.firstOperand = firstOperand this.secondOperand = secondOperand } constructor(id: String, result: Long) { this.id = id this.hasYelled = true this.result = result } @Override override fun toString(): String { return "src.NewMonkey(id='$id', hasYelled=$hasYelled, operation='$operation', firstOperand='$firstOperand', secondOperand='$secondOperand', firstLong=$firstLong, secondLong=$secondLong, result=$result)" } } fun main() { val monkeys = mutableListOf<NewMonkey>() readInput("input21").forEach { val monkeyInfo = it.split(" ", ":").filter { it2 -> it2 != "" } println(monkeyInfo) if (monkeyInfo.size == 2) { monkeys.add(NewMonkey(monkeyInfo[0], monkeyInfo[1].toLong())) } else { val id = monkeyInfo[0] val operation = monkeyInfo[2] val firstOperand = monkeyInfo[1] val secondOperand = monkeyInfo[3] monkeys.add(NewMonkey(id, operation, firstOperand, secondOperand)) } } var monkeysToYell = monkeys.filter { !it.hasYelled } while (monkeysToYell.isNotEmpty()) { val yelledMonkeys = monkeys.filter { it.hasYelled } monkeysToYell = monkeys.filter { !it.hasYelled } monkeysToYell.forEach { monkey -> if (yelledMonkeys.any { monkey.firstOperand == it.id }) { monkey.firstLong = yelledMonkeys.first { monkey.firstOperand == it.id }.result } if (yelledMonkeys.any { monkey.secondOperand == it.id }) { monkey.secondLong = yelledMonkeys.first { monkey.secondOperand == it.id }.result } if (monkey.firstLong != Long.MIN_VALUE && monkey.secondLong != Long.MIN_VALUE) { monkey.result = when (monkey.operation) { "+" -> monkey.firstLong + monkey.secondLong "-" -> monkey.firstLong - monkey.secondLong "*" -> monkey.firstLong * monkey.secondLong "/" -> monkey.firstLong / monkey.secondLong else -> throw Exception("Unknown operation: ${monkey.operation}") } monkey.hasYelled = true } } } println(monkeys.first { it.id == "root" }.result) }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
2,827
AoC
Apache License 2.0
src/main/kotlin/g2801_2900/s2851_string_transformation/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2851_string_transformation // #Hard #String #Dynamic_Programming #Math #String_Matching // #2023_12_18_Time_377_ms_(100.00%)_Space_49_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private lateinit var g: Array<LongArray> fun numberOfWays(s: String, t: String, k: Long): Int { val n = s.length val v = kmp(s + s, t) g = arrayOf(longArrayOf((v - 1).toLong(), v.toLong()), longArrayOf((n - v).toLong(), (n - 1 - v).toLong())) val f = qmi(k) return if (s == t) f[0][0].toInt() else f[0][1].toInt() } private fun kmp(s: String, p: String): Int { var s = s var p = p val n = p.length val m = s.length s = "#$s" p = "#$p" val ne = IntArray(n + 1) var j = 0 for (i in 2..n) { while (j > 0 && p[i] != p[j + 1]) { j = ne[j] } if (p[i] == p[j + 1]) { j++ } ne[i] = j } var cnt = 0 j = 0 for (i in 1..m) { while (j > 0 && s[i] != p[j + 1]) { j = ne[j] } if (s[i] == p[j + 1]) { j++ } if (j == n) { if (i - n + 1 <= n) { cnt++ } j = ne[j] } } return cnt } private fun mul(c: Array<LongArray>, a: Array<LongArray>, b: Array<LongArray>) { val t = Array(2) { LongArray(2) } for (i in 0..1) { for (j in 0..1) { for (k in 0..1) { val mod = 1e9.toInt() + 7 t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % mod } } } for (i in 0..1) { System.arraycopy(t[i], 0, c[i], 0, 2) } } private fun qmi(k: Long): Array<LongArray> { var k = k val f = Array(2) { LongArray(2) } f[0][0] = 1 while (k > 0) { if ((k and 1L) == 1L) { mul(f, f, g) } mul(g, g, g) k = k shr 1 } return f } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,204
LeetCode-in-Kotlin
MIT License
src/Utils.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import java.io.File import java.math.BigInteger import java.security.MessageDigest /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') /** * Reads the input as a single string */ fun readInputLine(name: String) = File("src", "$name.txt").readText() fun readIntegerGrid(name: String) = readInput(name).map { line -> line.toCharArray().map { it.digitToInt() } } fun <T> checkResult(actual: T, expected: T) = check(actual == expected) { "Expected $expected, but got $actual" } fun <T> List<List<T>>.forEachGrid(action: (x: Int, y: Int, T) -> Unit) { forEachIndexed { x, row -> row.forEachIndexed { y, it -> action(x, y, it) } } } fun <T> List<List<T>>.gridSum(action: (x: Int, y: Int, T) -> Int): Int { var sum = 0 forEachIndexed { x, row -> row.forEachIndexed { y, it -> sum += action(x, y, it) } } return sum } fun <T> List<List<T>>.orthogonalNeighbours(x: Int, y: Int, default: T): List<T> { val up = if (x > 0) this[x - 1][y] else default val down = if (x < this.size - 1) this[x + 1][y] else default val left = if (y > 0) this[x][y - 1] else default val right = if (y < this[x].size - 1) this[x][y + 1] else default return listOf(up, right, down, left) } fun <T> List<List<T>>.allNeighbours(x: Int, y: Int, default: T): List<T> { val spaceNorth = x > 0 val spaceEast = y < this[x].size - 1 val spaceSouth = x < this.size - 1 val spaceWest = y > 0 val north = if (spaceNorth) this[x - 1][y] else default val northEast = if (spaceNorth && spaceEast) this[x - 1][y + 1] else default val east = if (spaceEast) this[x][y + 1] else default val southEast = if (spaceSouth && spaceEast) this[x + 1][y + 1] else default val south = if (spaceSouth) this[x + 1][y] else default val southWest = if (spaceSouth && spaceWest) this[x + 1][y - 1] else default val west = if (spaceWest) this[x][y - 1] else default val northWest = if (spaceNorth && spaceWest) this[x - 1][y - 1] else default return listOf(north, northEast, east, southEast, south, southWest, west, northWest) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
2,307
aoc-2022
Apache License 2.0
src/day11/Monkey.kt
quinlam
573,215,899
false
{"Kotlin": 31932}
package day11 import java.util.LinkedList data class Monkey( val items: LinkedList<Long>, val operation: (Long) -> Long, val testNumber: Int, val trueMonkey: Int, val falseMonkey: Int, var inspectionCount: Int = 0 ) { fun inspect(relief: Int, commonModulo: Int, throwTo: (Int, Long) -> Unit) { while (!items.isEmpty()) { inspectionCount++ val worry = (operation(items.pop()) / relief) % commonModulo val nextMonkey = if (worry % testNumber == 0L) trueMonkey else falseMonkey throwTo(nextMonkey, worry) } } fun giveItem(item: Long) { items.add(item) } companion object { fun fromString(input: List<String>): Monkey { return Monkey( items = createItems(input[1]), operation = createOperation(input[2]), testNumber = input[3].substringAfterLast(" ").toInt(), trueMonkey = input[4].substringAfterLast(" ").toInt(), falseMonkey = input[5].substringAfterLast(" ").toInt() ) } private fun createItems(input: String): LinkedList<Long> { val list = input.filter { it.isDigit() || it == ' ' } .trim() .split(" ") .map { it.toLong() } .toList() return LinkedList(list) } private fun createOperation(input: String): (Long) -> Long { val parts = input.split(" ") return { old -> val value = if (parts[7] == "old") old else parts[7].toLong() if (parts[6] == "+") old + value else old * value } } } }
0
Kotlin
0
0
d304bff86dfecd0a99aed5536d4424e34973e7b1
1,739
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/oowekyala/ijcc/lang/model/LexicalState.kt
oowekyala
160,946,520
false
{"Kotlin": 636537, "HTML": 12345, "Lex": 10654, "Shell": 1940, "Just": 101}
package com.github.oowekyala.ijcc.lang.model import com.github.oowekyala.ijcc.lang.psi.JccIdentifier import com.github.oowekyala.ijcc.lang.psi.JccLiteralRegexUnit import com.github.oowekyala.ijcc.lang.psi.JccRefRegularExpression import com.github.oowekyala.ijcc.lang.psi.match import com.intellij.psi.SmartPsiElementPointer import java.util.concurrent.ConcurrentHashMap import java.util.function.Function import java.util.regex.Matcher /** * Represents a lexical state. * * The JavaCC lexical specification is organized into a set of "lexical states". * Each lexical state is named with an identifier. There is a standard lexical state * called DEFAULT. The generated token manager is at any moment in one of these * lexical states. When the token manager is initialized, it starts off in the DEFAULT * state, by default. The starting lexical state can also be specified as a parameter * while constructing a token manager object. * * Each lexical state contains an ordered list of regular expressions; the order is * derived from the order of occurrence in the input file. There are four kinds of * regular expressions: SKIP, MORE, TOKEN, and SPECIAL_TOKEN. These are represented * by the [RegexKind] enum. * * @author <NAME> * @since 1.0 */ class LexicalState private constructor(val lexicalGrammar: LexicalGrammar, val name: String, val tokens: List<Token>, private val declarator: SmartPsiElementPointer<JccIdentifier>?) { val declarationIdent: JccIdentifier? get() = declarator?.element // Grammars often have big number of tokens in the default state, which makes // match computation suboptimal without caching. private val matchedTokenCache = ConcurrentHashMap<MatchParams, Token?>() private fun computeMatchInternal(matchParams: MatchParams): Token? { val (toMatch, exact, consideredRegexKinds) = matchParams return if (exact) filterWith(consideredRegexKinds).firstOrNull { it.matchesLiteral(toMatch) } else filterWith(consideredRegexKinds) // Only remove private regex if we're looking for an exact match // Duplicate private string tokens should still be reported .filter { !it.isPrivate } .mapNotNull { token -> val matcher: Matcher? = token.prefixPattern?.toPattern()?.matcher(toMatch) if (matcher?.matches() == true) Pair(token, matcher.group(0)) else null } .maxWithOrNull(matchComparator) ?.let { it.first } } /** * Returns the token that matches the given string in this lexical state. * * A token is matched as follows: All regular expressions in the current * lexical state are considered as potential match candidates. The token * manager consumes the maximum number of characters from the input stream * possible that match one of these regular expressions. That is, the token * manager prefers the longest possible match. If there are multiple longest * matches (of the same length), the regular expression that is matched is * the one with the earliest order of occurrence in the grammar file. * * @param toMatch String to match * @param exact Consider only definitions of string tokens that match exactly this match * @param consideredRegexKinds Regex kinds to consider for the match. The default is just [RegexKind.TOKEN] * * @return the matched token if it was found in this state */ fun matchLiteral(toMatch: String, exact: Boolean, consideredRegexKinds: Set<RegexKind> = RegexKind.JustToken): Token? = matchedTokenCache.computeIfAbsent(MatchParams(toMatch, exact, consideredRegexKinds)) { this.computeMatchInternal(it) } /** * Returns the string token that matches exactly this regex unit. * * @return the matched token if it was found */ fun matchLiteral(literal: JccLiteralRegexUnit, exact: Boolean, consideredRegexKinds: Set<RegexKind> = RegexKind.JustToken): Token? = matchLiteral(literal.match, exact, consideredRegexKinds) val successors: Set<LexicalState> by lazy { tokens.asSequence() .mapNotNull { it.lexicalStateTransition } .mapNotNull { lexicalGrammar.getLexicalState(it) } .toSet() } val predecessors: Set<LexicalState> by lazy { lexicalGrammar.lexicalStates.filter { this in it.successors }.toSet() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as LexicalState if (name != other.name) return false return true } override fun hashCode(): Int = name.hashCode() override fun toString(): String = "LexicalState($name)" private fun filterWith(consideredRegexKinds: Set<RegexKind>): Sequence<Token> = tokens.asSequence() .filter { consideredRegexKinds.contains(it.regexKind) } private data class MatchParams(val toMatch: String, val exactMatch: Boolean, val consideredRegexKinds: Set<RegexKind>) companion object { /** * Maximal munch. First take the longest match, then take * the highest token in the file. */ private val matchComparator = Comparator.comparingInt<Pair<Token, String>> { it.second.length } .thenComparing<Token>(Function { it.first }, Token.offsetComparator) const val DefaultStateName = "DEFAULT" val JustDefaultState = listOf(DefaultStateName) /** * Builds a lexical state, used by [LexicalGrammar]. */ internal class LexicalStateBuilder(val name: String, private val declarator: SmartPsiElementPointer<JccIdentifier>?) { private val mySpecs = mutableListOf<Token>() /** Must be called in document order. */ fun addToken(token: Token) { if ( // freestanding regex refs are ignored token.regularExpression !is JccRefRegularExpression // don't add duplicate synthetic tokens in the same state && mySpecs.none { Token.areEquivalent(it, token) }) { mySpecs.add(token) } } val currentSpecs: List<Token> get() = mySpecs fun build(lexicalGrammar: LexicalGrammar) = LexicalState(lexicalGrammar, name, mySpecs, declarator) } } }
9
Kotlin
6
39
3c737d631f562e85361480b17c26824b560898a8
6,942
intellij-javacc
MIT License
src/aoc22/Day14.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc2022.day14 import lib.Path import lib.Point import lib.Solution data class Cave( private val bricks: MutableSet<Point>, private val sands: MutableSet<Point>, ) { constructor(bricks: Set<Point> = emptySet()) : this(bricks.toMutableSet(), mutableSetOf()) private var pitLevel: Int = bricks.maxOf { it.y } fun addBase() { pitLevel += 2 bricks += (-pitLevel..pitLevel).map { Point(DROPPING_POINT.x + it, pitLevel) } } fun dropSand(): Boolean { if (DROPPING_POINT.isOccupied()) return false var sand = DROPPING_POINT while (!sand.isStable()) { sand = sand.step() if (sand.isFallingToAbyss()) return false } sands += sand return true } private fun Point.isStable() = potentialDropPoints().all { it.isOccupied() } private fun Point.isOccupied() = this in bricks || this in sands private fun Point.isFallingToAbyss() = y >= pitLevel private fun Point.step(): Point = potentialDropPoints().first { !it.isOccupied() } private fun Point.potentialDropPoints() = DROP_DIRS.map { dir -> this + dir } companion object { private val DROPPING_POINT = Point(500, 0) private val DROP_DIRS = listOf(Point(0, 1), Point(-1, 1), Point(1, 1)) fun parse(caveStr: String): Cave { val bricks = caveStr.lines().map(Path.Companion::parse).flatMap(Path::expand).toSet() return Cave(bricks.toSet()) } } } typealias Input = Cave typealias Output = Int private val solution = object : Solution<Input, Output>(2022, "Day14") { override fun parse(input: String): Input = Cave.parse(input) override fun format(output: Output): String = "$output" override fun solve(part: Part, input: Input): Output { if (part == Part.PART2) input.addBase() var sand = 0 while (input.dropSand()) sand++ return sand } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
1,913
aoc-kotlin
Apache License 2.0
src/Day03.kt
karloti
573,006,513
false
{"Kotlin": 25606}
fun main() { val code = (('a'..'z') + ('A'..'Z')).withIndex().associate { (i, c) -> c to i + 1 } fun part1(input: List<String>): Int = input .map { s -> s.chunked(s.length / 2, CharSequence::toSet) } .map { it.reduce(Set<Char>::intersect).single() } .sumOf { code[it]!! } fun part2(input: List<String>): Int = input .chunked(3) { it.map(String::toSet) } .map { it.reduce(Set<Char>::intersect).single() } .sumOf { code[it]!! } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
1
2
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
691
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CommonChars.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 /** * Find Common Characters */ fun Array<String>.commonChars(): List<String> { val map1: MutableMap<Char, Int?> = HashMap() val map2: MutableMap<Char, Int?> = HashMap() val arr = ArrayList<Char>() if (isEmpty()) return emptyList() for (i in this.first().toCharArray()) { // get the frequency of the string to use to compare against if (map1.containsKey(i)) map1[i] = map1[i]?.plus(1) else map1[i] = 1 } for (h in 1 until this.size) { for (i in this[h].toCharArray()) { // get the frequencies of the next string if (map2.containsKey(i)) map2[i] = map2[i]?.plus(1) else map2[i] = 1 } for (i in map2.keys) if (map1.containsKey(i)) { val x = map2[i]?.coerceAtMost(map1[i]!!) // find the intersection between two pairs of strings map1[i] = x } for (i in map1.keys) { if (!map2.containsKey(i)) { arr.add(i) } } // temporarily store the char rather than delete right away to avoid concurrent modification for (t in arr) map1.remove(t) // remove whatever was not contained in the next string map2.clear() // clear the map } val array = ArrayList<String>() for (k in map1.keys) { // make the required list for (i in 0 until map1[k]!!) { array.add(k.toString()) } } return array }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,040
kotlab
Apache License 2.0
day12/Part2.kt
anthaas
317,622,929
false
null
import java.io.File import kotlin.math.abs fun main(args: Array<String>) { val input = File("input.txt").readLines().map { Pair(it[0], it.substring(1).toInt()) } var northDistanceFromStartWaypoint = 1 var eastDistanceFromStartWaypoint = 10 var northDistanceFromStartShip = 0 var eastDistanceFromStartShip = 0 for (entry in input) { val (instruction, value) = entry when (instruction) { 'N' -> northDistanceFromStartWaypoint += value 'S' -> northDistanceFromStartWaypoint -= value 'E' -> eastDistanceFromStartWaypoint += value 'W' -> eastDistanceFromStartWaypoint -= value 'L', 'R' -> { val new = rotateWaypoint(northDistanceFromStartWaypoint to eastDistanceFromStartWaypoint, instruction, value) northDistanceFromStartWaypoint = new.first eastDistanceFromStartWaypoint = new.second } 'F' -> { northDistanceFromStartShip += value * northDistanceFromStartWaypoint eastDistanceFromStartShip += value * eastDistanceFromStartWaypoint } else -> error("unknown instruction") } } println(abs(northDistanceFromStartShip) + abs(eastDistanceFromStartShip)) } private fun rotateWaypoint(waypoint: Pair<Int, Int>, direction: Char, angle: Int): Pair<Int, Int> { return when (direction) { 'L' -> { when (angle) { 90 -> waypoint.second to -waypoint.first 180 -> -waypoint.first to -waypoint.second 270 -> -waypoint.second to waypoint.first else -> error("wrong angle L") } } 'R' -> { when (angle) { 90 -> -waypoint.second to waypoint.first 180 -> -waypoint.first to -waypoint.second 270 -> waypoint.second to -waypoint.first else -> error("wrong angle R") } } else -> error("wrong direction") } }
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
2,079
Advent-of-Code-2020
MIT License
src/main/kotlin/me/grison/aoc/y2020/Day22.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2020 import me.grison.aoc.* class Day22 : Day(22, 2020) { override fun title() = "Crab Combat" override fun partOne(): Any { val (player1, player2) = decks() while (player1.isNotEmpty() && player2.isNotEmpty()) { val (p1, p2) = p(player1.shift(), player2.shift()) if (p1 > p2) player1.addLast(p1, p2) else player2.addLast(p2, p1) } return (if (player1.isEmpty()) player2 else player1).score() } override fun partTwo() = decks().let { (player1, player2) -> (if (recursiveCombat(player1, player2) == 1) player1 else player2).score() } private fun decks() = inputGroups.map { it.lines().tail().ints().deque() }.pair() private fun Deck.score() = zip((size downTo 1)).sumOf { it.product() } private fun recursiveCombat(player1: Deck, player2: Deck): Int { val previousRounds = hashSetOf<Any>() while (player1.isNotEmpty() && player2.isNotEmpty()) { val round = p(player1, player2) if (!previousRounds.add(round)) return 1 val (a, b) = p(player1.shift(), player2.shift()) val winner = if (a <= player1.size && b <= player2.size) { recursiveCombat(player1[0, a].deque(), player2[0, b].deque()) } else { if (a > b) 1 else 2 } if (winner == 1) player1.addLast(a, b) else player2.addLast(b, a) } return if (player1.isEmpty()) 2 else 1 } } typealias Deck = ArrayDeque<Int>
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
1,584
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day03.kt
mnajborowski
573,619,699
false
{"Kotlin": 7975}
fun main() { val itemPriorities = (('a'..'z') + ('A'..'Z')).mapIndexed { i, e -> e to i + 1 }.toMap() fun part1(input: List<String>): Int = input.sumOf { rucksack -> itemPriorities.getValue( rucksack.chunked(rucksack.length / 2).let { compartments -> compartments[0].first { it in compartments[1] } } ) } fun part2(input: List<String>): Int = input.chunked(3).sumOf { groupRucksacks -> itemPriorities.getValue( groupRucksacks[0].first { it in groupRucksacks[1] && it in groupRucksacks[2] } ) } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e54c13bc5229c6cb1504db7e3be29fc9b9c4d386
745
advent-of-code-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/hard/MergeKLists.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.hard import com.daily.algothrim.leetcode.ListNode /** * 23. 合并K个升序链表 * * 给你一个链表数组,每个链表都已经按升序排列。 * 请你将所有链表合并到一个升序链表中,返回合并后的链表。 */ class MergeKLists { companion object { @JvmStatic fun main(args: Array<String>) { MergeKLists().mergeKLists(arrayOf( ListNode(1).apply { next = ListNode(4).apply { next = ListNode(5) } }, ListNode(1).apply { next = ListNode(3).apply { next = ListNode(4) } }, ListNode(2).apply { next = ListNode(6) } ))?.printAll() } } fun mergeKLists(lists: Array<ListNode?>): ListNode? { if (lists.isNullOrEmpty()) return null return sort(0, lists.size - 1, lists) } private fun sort(l: Int, r: Int, lists: Array<ListNode?>): ListNode? { if (l == r) return lists[l] val m = l + (r - l).shr(1) return merge(sort(l, m, lists), sort(m + 1, r, lists)) } private fun merge(l1: ListNode?, l2: ListNode?): ListNode? { val result = ListNode(-1) var temp: ListNode? = result var left = l1 var right = l2 while (left != null && right != null) { if (left.`val` <= right.`val`) { temp?.next = left left = left.next } else { temp?.next = right right = right.next } temp = temp?.next } if (left != null) { temp?.next = left } if (right != null) { temp?.next = right } return result.next } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,942
daily_algorithm
Apache License 2.0
src/main/kotlin/co/csadev/advent2021/Day18.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 18 * Problem Description: http://adventofcode.com/2021/day/18 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList import com.github.shiguruikai.combinatoricskt.combinations import java.util.LinkedList class Day18(override val input: List<String> = resourceAsList("21day18.txt")) : BaseDay<List<String>, Int, Int> { sealed interface Token { object Open : Token object Close : Token object Separator : Token data class Value(val value: Int) : Token companion object { fun tokenFor(char: Char) = when (char) { '[' -> Open ']' -> Close ',' -> Separator else -> Value(char - '0') // Allows for chars with value higher than 10 (used in a few tests) } } } private val homework: List<LinkedList<Token>> get() = input.map { str -> LinkedList(str.map { Token.tokenFor(it) }) } operator fun LinkedList<Token>.plus(other: LinkedList<Token>) = apply { add(0, Token.Open) add(Token.Separator) addAll(other) add(Token.Close) // Adding two numbers always triggers a reduction while (explode(this) || split(this)) Unit // Keep exploding and splitting until fully reduced } // Adds 'toAdd' to the first regular number in the given range private fun addToFirstRegularNumber(number: LinkedList<Token>, range: IntProgression, toAdd: Int) { for (j in range) { val curr = number[j] if (curr is Token.Value) { number[j] = Token.Value(curr.value + toAdd) return } } } // returns true if an explosion was triggered private fun explode(number: LinkedList<Token>): Boolean { var nesting = 0 for (i in number.indices) { when (number[i]) { Token.Open -> nesting++ Token.Close -> nesting-- else -> Unit } if (nesting == 5) { val left = (number[i + 1] as Token.Value).value addToFirstRegularNumber(number, i - 1 downTo 0, left) // Right value is added to first regular number to the right val right = (number[i + 3] as Token.Value).value addToFirstRegularNumber(number, i + 5 until number.size, right) repeat(5) { number.removeAt(i) } // Remove the current pair number.add(i, Token.Value(0)) // and insert 0 in its place return true } } return false } // returns true if the number was split fun split(number: LinkedList<Token>): Boolean { val idx = number.indexOfFirst { t -> t is Token.Value && t.value >= 10 } val token = number.getOrNull(idx) as? Token.Value ?: return false val l = token.value / 2 val r = token.value - l number.removeAt(idx) number.addAll(idx, listOf(Token.Open, Token.Value(l), Token.Separator, Token.Value(r), Token.Close)) return true } private fun LinkedList<Token>.calculateMagnitude(): Int { val stack = mutableListOf<MutableList<Int>>() for (i in indices) { when (val ch = get(i)) { Token.Open -> stack.add(mutableListOf()) Token.Close -> { val (left, right) = stack.removeLast() val magnitude = 3 * left + 2 * right if (stack.isEmpty()) { return magnitude } stack.last().add(magnitude) } is Token.Value -> stack.last().add(ch.value) Token.Separator -> Unit } } return -1 } override fun solvePart1() = homework.reduce { acc, next -> acc + next }.calculateMagnitude() override fun solvePart2() = homework.combinations(2).maxOf { (LinkedList(it.first().toMutableList()) + it.last()).calculateMagnitude() } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
4,203
advent-of-kotlin
Apache License 2.0
src/main/kotlin/aoc2015/Day17.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2015 import AoCDay // https://adventofcode.com/2015/day/17 object Day17 : AoCDay<Int>( title = "No Such Thing as Too Much", part1Answer = 654, part2Answer = 57, ) { private fun parseContainers(input: String) = input.lines().map(String::toInt).toIntArray() override fun part1(input: String): Int { val containers = parseContainers(input) require(containers.size < 31) { "Bit-trick won't work with containers >= 31" } var combinations = 0 outer@ for (combination in 0..<(1 shl containers.size)) { var total = 0 for (index in containers.indices) { if ((1 shl index) and combination != 0) { total += containers[index] if (total > 150) continue@outer } } if (total == 150) combinations++ } return combinations } override fun part2(input: String): Int { val containers = parseContainers(input) require(containers.size < 31) { "Bit-trick won't work with containers >= 31" } val combinations = mutableListOf<Int>() outer@ for (combination in 0..<(1 shl containers.size)) { var total = 0 var n = 0 for (index in containers.indices) { if ((1 shl index) and combination != 0) { total += containers[index] n++ if (total > 150) continue@outer } } if (total == 150) combinations += n } val min = combinations.min() return combinations.count { it == min } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
1,668
advent-of-code-kotlin
MIT License
src/main/kotlin/numberFraction.kt
AlBovo
574,593,169
false
{"Kotlin": 75843}
class NumberFraction(var numerator: Int, denominatorValue: Int){ var denominator = denominatorValue set(value){ require(value != 0){ "The denominator must be different from 0" } field = value } init{ require(denominatorValue != 0){ "The denominator must be different from 0" } } fun product(number: NumberFraction): NumberFraction{ val numberSecond = reduce(number) reduceCurrentFraction() return reduce(NumberFraction(numerator * numberSecond.numerator, denominator * numberSecond.denominator)) } fun sum(number: NumberFraction): NumberFraction{ val numberSecond = reduce(number) reduceCurrentFraction() return reduce(NumberFraction(numerator*numberSecond.denominator + numberSecond.numerator * denominator, denominator*numberSecond.denominator)) } fun isEqual(number: NumberFraction): Boolean { val numberSecond = reduce(number) reduceCurrentFraction() return numerator == numberSecond.numerator && denominator == numberSecond.denominator } fun isPositive() = (denominator * numerator >= 0) fun calculateGCD(numberFirst: Int, numberSecond: Int): Int { require(numberSecond != 0){ "The number must be positive" } var numberFirst1 = numberFirst var numberSecond1 = numberSecond var numberMaximum = if(numberFirst > numberSecond) numberFirst else numberSecond var gcd = 1 for(i in 2..numberMaximum){ if(numberFirst1 == 1 && numberSecond1 == 1){ break } while(numberFirst1%i == 0 && numberSecond1%i == 0){ gcd *= i numberFirst1 /= i numberSecond1 /= i } } return gcd } fun reduce(numberFraction: NumberFraction): NumberFraction{ val gcd = calculateGCD(numberFraction.numerator, numberFraction.denominator) numberFraction.numerator /= gcd numberFraction.denominator /= gcd return numberFraction } fun reduceCurrentFraction(){ val gcd = calculateGCD(numerator, denominator) numerator /= gcd denominator /= gcd } }
0
Kotlin
0
0
56a31313c53cc3525d2aa3c29b3a2085b1b1b506
2,313
Compiti
MIT License
core/src/main/kotlin/com/bsse2018/salavatov/flt/algorithms/CFPQMatrix.kt
vsalavatov
241,599,920
false
{"Kotlin": 149462, "ANTLR": 1960}
package com.bsse2018.salavatov.flt.algorithms import com.bsse2018.salavatov.flt.grammars.ContextFreeGrammar import com.bsse2018.salavatov.flt.utils.Graph import org.la4j.matrix.SparseMatrix import org.la4j.matrix.sparse.CRSMatrix fun CFPQMatrixQuery(graph: Graph, wcnf: ContextFreeGrammar): HashSet<Pair<Int, Int>> { val nonTerminals = ContextFreeGrammar.NodeAccountant().let { it.consume(wcnf) it.nonTerminals } val nodes = graph.size val matrices = hashMapOf<String, SparseMatrix>() nonTerminals.forEach { matrices[it] = CRSMatrix(nodes, nodes) } val epsilonRules = wcnf.rules.filter { it.isEpsilon() } val symRules = wcnf.rules .filter { it.isTerminal() && !it.isEpsilon() } .groupBy { it.to[0] } val nonTermRules = wcnf.rules.filter { !it.isTerminal() } for (u in graph.indices) { epsilonRules.forEach { rule -> matrices[rule.from]!![u, u] = 1.0 } for ((sym, v) in graph[u]) { symRules[sym]?.forEach { rule -> matrices[rule.from]!![u, v] = 1.0 } } } var changed = true while (changed) { changed = false nonTermRules.forEach { rule -> val nterm1 = rule.to[0] val nterm2 = rule.to[1] val product = matrices[nterm1]!!.multiply(matrices[nterm2]!!).toSparseMatrix() val result = matrices[rule.from]!! product.eachNonZero { i, j, _ -> if (result.isZeroAt(i, j)) { changed = true result[i, j] = 1.0 } } } } val result = hashSetOf<Pair<Int, Int>>() matrices[wcnf.start]!!.eachNonZero { i, j, _ -> result.add(Pair(i, j)) } return result }
0
Kotlin
0
1
c1c229c113546ef8080fc9d3568c5024a22b80a5
1,812
bsse-2020-flt
MIT License
src/main/kotlin/zanagram/DynamicArraySorting.kt
HenriqueRocha
259,845,874
false
null
package zanagram fun <T : Comparable<T>> DynamicArray<out T>.bubbleSort() { var n = size() var swapped: Boolean do { swapped = false for (i in 1 until n) { if (this[i - i] > this[i]) { swap(this, i - 1, i) swapped = true } } n-- } while (swapped) } fun <T : Comparable<T>> DynamicArray<out T>.selectionSort() { val n = size() for (i in 0 until n) { var min = i var j = i while (j < n) { if (this[j] < this[min]) { min = j } j++ } swap(this, i, min) } } fun <T : Comparable<T>> DynamicArray<out T>.insertionSort() { var sortedUntilIndex = 1 while (sortedUntilIndex < size()) { var i = sortedUntilIndex while (i > 0 && this[i] < this[i - 1]) { swap(this, i, i - 1) i-- } sortedUntilIndex++ } } fun <T : Comparable<T>> DynamicArray<out T>.quickSort() { quicksort(this, 0, size() - 1) } fun <T : Comparable<T>> quicksort(array: DynamicArray<out T>, lo: Int, hi: Int) { if (lo < hi) { val p = partition(array, lo, hi) quicksort(array, lo, p) quicksort(array, p + 1, hi) } } fun <T : Comparable<T>> partition(array: DynamicArray<out T>, lo: Int, hi: Int): Int { val pivot: T = array[(hi + lo) / 2] var i = lo - 1 var j = hi + 1 while (true) { do { i++ } while (array[i] < pivot) do { j-- } while (array[j] > pivot) if (i >= j) return j swap(array, i, j) } } internal fun <T> swap(array: DynamicArray<T>, i: Int, j: Int) { val t = array[i] array[i] = array[j] array[j] = t } fun <T : Comparable<T>> DynamicArray<out T>.binarySearch(e: T): Int { var min = 0 var max = size() - 1 while (min <= max) { var mid = (min + max) / 2 if (e < this[mid]) max = mid - 1 else if (e > this[mid]) min = mid + 1 else return mid } return -1 }
1
Kotlin
0
0
fbc4f2fc5489306dbc0eddfcd2a527745e297b78
2,095
zanagram
MIT License
src/main/kotlin/io/undefined/ExclusiveTimeOfFunctions.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.undefined import io.utils.runTests import java.util.* // https://leetcode.com/problems/exclusive-time-of-functions/ class ExclusiveTimeOfFunctions { // https://leetcode.com/problems/exclusive-time-of-functions/discuss/105062/Java-Stack-Solution-O(n)-Time-O(n)-Space fun execute(n: Int, logs: List<String>): IntArray { val logsTriple = logs.toTriple() val result = IntArray(n) val stack = LinkedList<Int>() // startInterval means the start of the interval var startInterval = 0 logsTriple.forEach { (id, action, timestamp) -> if (stack.isNotEmpty()) result[stack.peek()] += timestamp - startInterval startInterval = timestamp when (action) { // timestamp is the start of the next interval, doesn't belong to the current interval. "start" -> stack.push(id) // timestamp is the end of the current interval, belong to the current interval. // That's why result[stack.pop()]++ and startInterval++ "end" -> result[stack.pop()]++.also { startInterval++ } } } return result } private fun List<String>.toTriple(): List<Triple<Int, String, Int>> = this.map { it.split(':').let { (id, action, timestamp) -> Triple(id.toInt(), action, timestamp.toInt()) } } } fun main() { runTests(listOf( Triple(2, listOf("0:start:0", "1:start:2", "1:end:5", "0:end:6"), listOf(3, 4)), Triple(1, listOf("0:start:0", "0:start:1", "0:start:2", "0:end:3", "0:end:4", "0:end:5"), listOf(6)) )) { (n, logs, value) -> value to ExclusiveTimeOfFunctions().execute(n, logs).toList() } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,593
coding
MIT License
src/main/kotlin/com/colinodell/advent2022/Day03.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day03(input: List<String>) { private val rucksacks = input.map { it.toList() } fun solvePart1() = rucksacks .map { it.chunked(it.size / 2) } // Split each line into two compartments .map { it[0].intersect(it[1]) } // Find the common item type .sumOf { priority(it.first()) } // Sum the priorities fun solvePart2() = rucksacks .chunked(3) // Divide rucksacks into groups of 3 .map { it[0].intersect(it[1]).intersect(it[2]) } // Find the common item type in each group .sumOf { priority(it.first()) } // Sum the priorities private fun priority(c: Char): Int = if (c.isUpperCase()) c.code - 38 else c.code - 96 }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
718
advent-2022
MIT License
src/main/kotlin/day12/DayTwelve.kt
Neonader
572,678,494
false
{"Kotlin": 19255}
package day12 import java.io.File import kotlin.math.min val fileList = File("puzzle_input/day12.txt").readLines() // the rows of 'S' and 'E' respectively val startLine = fileList.indexOfFirst { line -> line.contains('S') } val goalLine = fileList.indexOfFirst { line -> line.contains('E') } // the coordinates of 'S' and 'E' respectively val player = Pair(startLine, fileList[startLine].indexOf('S')) val goal = Pair(goalLine, fileList[goalLine].indexOf('E')) // the puzzle input with 'S' -> 'a' and 'E' -> 'z' val heightMap = fileList.map { line -> line.replaceFirst('S', 'a').replaceFirst('E', 'z') } // a map of the amount of steps required to reach a point val stepMap = fileList.map { line -> line.map { 0 }.toMutableList() } val stepBackMap = stepMap fun step(row: Int, col: Int) { val height = heightMap[row][col] val steps = stepMap[row][col] + 1 // step up if (row != 0 && (stepMap[row - 1][col] > steps || stepMap[row - 1][col] == 0) && heightMap[row - 1][col] <= height + 1) { stepMap[row - 1][col] = steps step(row - 1, col) } // step down if (row != heightMap.lastIndex && (stepMap[row + 1][col] > steps || stepMap[row + 1][col] == 0) && heightMap[row + 1][col] <= height + 1) { stepMap[row + 1][col] = steps step(row + 1, col) } // step left if (col != 0 && (stepMap[row][col - 1] > steps || stepMap[row][col - 1] == 0) && heightMap[row][col - 1] <= height + 1) { stepMap[row][col - 1] = steps step(row, col - 1) } // step right if (col != heightMap[0].lastIndex && (stepMap[row][col + 1] > steps || stepMap[row][col + 1] == 0) && heightMap[row][col + 1] <= height + 1) { stepMap[row][col + 1] = steps step(row, col + 1) } } fun stepBack(row: Int, col: Int) { val height = heightMap[row][col] val steps = stepMap[row][col] + 1 // step up if (row != 0 && (stepBackMap[row - 1][col] > steps || stepMap[row - 1][col] == 0) && heightMap[row - 1][col] >= height - 1) { stepBackMap[row - 1][col] = steps stepBack(row - 1, col) } // step down if (row != heightMap.lastIndex && (stepBackMap[row + 1][col] > steps || stepMap[row + 1][col] == 0) && heightMap[row + 1][col] >= height - 1) { stepBackMap[row + 1][col] = steps stepBack(row + 1, col) } // step left if (col != 0 && (stepBackMap[row][col - 1] > steps || stepMap[row][col - 1] == 0) && heightMap[row][col - 1] >= height - 1) { stepBackMap[row][col - 1] = steps stepBack(row, col - 1) } // step right if (col != heightMap[0].lastIndex && (stepBackMap[row][col + 1] > steps || stepMap[row][col + 1] == 0) && heightMap[row][col + 1] >= height - 1) { stepBackMap[row][col + 1] = steps stepBack(row, col + 1) } } fun a(): Int { step(player.first, player.second) return stepMap[goal.first][goal.second] } fun b(): Int { stepBack(goal.first, goal.second) var minSteps = Int.MAX_VALUE stepBackMap.forEachIndexed { row, line -> line.forEachIndexed { col, steps -> if (heightMap[row][col] == 'a' && steps != 0) minSteps = min(steps, minSteps) } } return minSteps }
0
Kotlin
0
3
4d0cb6fd285c8f5f439cb86cb881b4cd80e248bc
3,051
Advent-of-Code-2022
MIT License
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_9_Palindrome_Number.kt
v43d3rm4k4r
515,553,024
false
{"Kotlin": 40113, "Java": 25728}
package leetcode.solutions.concrete.kotlin import leetcode.solutions.* import leetcode.solutions.ProblemDifficulty.* import leetcode.solutions.validation.SolutionValidator.* import leetcode.solutions.annotations.ProblemInputData import leetcode.solutions.annotations.ProblemSolution /** * __Problem:__ Given an integer x, return true if x is palindrome integer. * An integer is a palindrome when it reads the same backward as forward. * * __Constraints:__ * - -2^31 <= x <= 2^31 - 1 * __Solution 1:__ * - Convert a number to a string for iteration. * - Iterate through the array to the middle using counters for the beginning and end, comparing the values. * * __Time:__ O(N) * * __Space:__ O(1) * * __Solution 2:__ * - Reverse half of x while dividing it to become the upper half. * - In the end check if reversed lower half is equal to the above half, or (in case if it's an odd length palindrome) * we check that equality with reversed rhs divided by 10 to skip that middle part. * * __Time:__ O(log(N)) * * __Space:__ O(1) * @author <NAME> */ class Solution_9_Palindrome_Number : LeetcodeSolution(EASY) { @ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(1)") private fun isPalindrome1(x: Int): Boolean { if (x < 0 || (x > 0 && (x % 10 == 0))) return false val asString = x.toString() val digitsCount = asString.length var i = 0; var j = asString.length - 1 while (i < digitsCount / 2) { if (asString[i] != asString[j]) { return false } ++i; --j } return true } @ProblemSolution(timeComplexity = "O(logN)", spaceComplexity = "O(1)") private fun isPalindrome2(x: Int): Boolean { if (x < 0 || (x > 0 && (x % 10 == 0))) return false var xCpy = x; var rhs = 0 while (xCpy > rhs) { rhs *= 10 rhs += xCpy % 10 xCpy /= 10 // mutating x itself is not allowed in this magnificent language } return rhs == xCpy || rhs / 10 == xCpy } @ProblemInputData override fun run() { ASSERT_TRUE(isPalindrome1(321123)) ASSERT_TRUE(isPalindrome1(543212345)) ASSERT_FALSE(isPalindrome1(12345)) ASSERT_TRUE(isPalindrome2(12533521)) ASSERT_FALSE(isPalindrome2(543211234)) ASSERT_FALSE(isPalindrome2(12345)) } }
0
Kotlin
0
1
c5a7e389c943c85a90594315ff99e4aef87bff65
2,411
LeetcodeSolutions
Apache License 2.0
src/Day04.kt
emersonf
572,870,317
false
{"Kotlin": 17689}
@file:OptIn(ExperimentalStdlibApi::class) fun main() { fun String.toIntRange(): IntRange { val (lowerBound, upperBound) = split("-") return lowerBound.toInt()..upperBound.toInt() } fun String.asRangePair(): Pair<IntRange, IntRange> { val (first, second) = split(",") return Pair(first.toIntRange(), second.toIntRange()) } fun IntRange.containedIn(other: IntRange): Boolean = first in other && last in other fun IntRange.containsOrIsContainedIn(other: IntRange): Boolean = this.containedIn(other) || other.containedIn(this) fun part1(input: List<String>): Int = input .map { line -> line.asRangePair() } .count { pair -> pair.first.containsOrIsContainedIn(pair.second) } fun IntRange.overlaps(other: IntRange): Boolean = first in other || last in other || other.first in this || other.last in this fun part2(input: List<String>): Int = input .map { line -> line.asRangePair() } .count { pair -> pair.first.overlaps(pair.second) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0e97351ec1954364648ec74c557e18ccce058ae6
1,367
advent-of-code-2022-kotlin
Apache License 2.0
kotlin/src/katas/kotlin/graph/Traversal3.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.graph import katas.kotlin.graph.Graph.Node import nonstdlib.join import datsok.shouldEqual import org.junit.Test import java.util.* class Traversal3 { @Test fun `depth-first traversal`() { "[a]".toGraph().dft("a").join("-") shouldEqual "a" "[a-b]".toGraph().dft("a").join("-") shouldEqual "a-b" "[a-b, b-c]".toGraph().let { it.dft("a").join("-") shouldEqual "a-b-c" it.dft("b").join("-") shouldEqual "b-a-c" it.dft("c").join("-") shouldEqual "c-b-a" } // a──b1──c // └──b2──┘ "[a-b1, a-b2, b1-c, b2-c]".toGraph().let { it.dft("a").join("-") shouldEqual "a-b1-c-b2" it.dft("b1").join("-") shouldEqual "b1-a-b2-c" it.dft("b2").join("-") shouldEqual "b2-a-b1-c" it.dft("c").join("-") shouldEqual "c-b1-a-b2" } } @Test fun `breadth-first traversal`() { "[a]".toGraph().bft("a").join("-") shouldEqual "a" "[a-b]".toGraph().bft("a").join("-") shouldEqual "a-b" "[a-b, b-c]".toGraph().let { it.bft("a").join("-") shouldEqual "a-b-c" it.bft("b").join("-") shouldEqual "b-a-c" it.bft("c").join("-") shouldEqual "c-b-a" } // a──b1──c // └──b2──┘ "[a-b1, a-b2, b1-c, b2-c]".toGraph().let { it.bft("a").join("-") shouldEqual "a-b1-b2-c" it.bft("b1").join("-") shouldEqual "b1-a-c-b2" it.bft("b2").join("-") shouldEqual "b2-a-c-b1" it.bft("c").join("-") shouldEqual "c-b1-b2-a" } } private fun <T, U> Graph<T, U>.bft(value: T) = node(value).bft() private fun <T, U> Node<T, U>.bft(): List<T> { val result = LinkedHashSet<T>() val queue = LinkedList<Node<T, U>>() queue.add(this) while (queue.isNotEmpty()) { val node = queue.removeFirst() if (!result.contains(node.value)) { result.add(node.value) queue.addAll(node.neighbors()) } } return result.toList() } private fun <T, U> Graph<T, U>.dft(value: T) = node(value).dft() private fun <T, U> Node<T, U>.dft(visited: HashSet<Node<T, U>> = HashSet()): List<T> { val added = visited.add(this) return if (!added) emptyList() else listOf(this.value) + this.neighbors().flatMap { it.dft(visited) } } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,481
katas
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/IsPossible.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Collections import java.util.PriorityQueue /** * Construct Target Array With Multiple Sums * @see <a href="https://leetcode.com/problems/construct-target-array-with-multiple-sums/">Source</a> */ fun interface IsPossible { operator fun invoke(target: IntArray): Boolean } /** * Approach 1: Working Backward * Time Complexity : O(n + k⋅log n). * Space Complexity : O(n). */ class IPWorkingBackward : IsPossible { override operator fun invoke(target: IntArray): Boolean { // Handle the n = 1 case. if (target.size == 1) { return target[0] == 1 } var totalSum: Int = target.sum() val pq: PriorityQueue<Int> = PriorityQueue<Int>(Collections.reverseOrder()) for (num in target) { pq.add(num) } while (pq.element() > 1) { val largest: Int = pq.remove() val x = largest - (totalSum - largest) if (x < 1) return false pq.add(x) totalSum = totalSum - largest + x } return true } } /** * Approach 2: Working Backward with Optimizations * Time Complexity : O(n+log k⋅log n). * Space Complexity : O(n). */ class IPWorkingBackwardOptmz : IsPossible { override operator fun invoke(target: IntArray): Boolean { // Handle the n = 1 case. if (target.size == 1) { return target[0] == 1 } var totalSum: Int = target.sum() val pq: PriorityQueue<Int> = PriorityQueue<Int>(Collections.reverseOrder()) for (num in target) { pq.add(num) } while (pq.element() > 1) { val largest: Int = pq.remove() val rest = totalSum - largest // This will only occur if n = 2. if (rest == 1) { return true } val x = largest % rest // If x is now 0 (invalid) or didn't // change, then we know this is impossible. if (x == 0 || x == largest) { return false } pq.add(x) totalSum = totalSum - largest + x } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,826
kotlab
Apache License 2.0
day06/kotlin/RJPlog/day2306_1_2.kt
mr-kaffee
720,687,812
false
{"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314}
import java.io.File fun waitForIt(in1: Int): Long { val pattern = """(\d)+""".toRegex() var lines = File("day2306_puzzle_input.txt").readLines() var line0 = pattern.findAll(lines[0]).map { it.value }.toList() var line1 = pattern.findAll(lines[1]).map { it.value }.toList() var time = mutableListOf<Pair<Long, Long>>() if (in1 == 1) { for (i in 0..line0.size - 1) { time.add(Pair(line0[i].toLong(), line1[i].toLong())) } } else { time.add(Pair(line0.joinToString("").toLong(), line1.joinToString("").toLong())) } var result = 1L time.forEach { var wins = 0L for (i in 0..it.first) { var dist = i * (it.first - i) if (dist > it.second) { wins += 1L } } result *= wins } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = waitForIt(1) var solution2 = waitForIt(2) // print solution for part 1 println("*******************************") println("--- Day 6: Wait For It ---") println("*******************************") println("Solution for part1") println(" $solution1 do you get if you multiply these numbers together") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 many ways can you beat the record in this one much longer race") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
0
Rust
2
0
5cbd13d6bdcb2c8439879818a33867a99d58b02f
1,403
aoc-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ArrayOfDoubledPairs.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeMap /** * 954. Array of Doubled Pairs * @see <a href="https://leetcode.com/problems/array-of-doubled-pairs/">Source</a> */ fun interface ArrayOfDoubledPairs { operator fun invoke(arr: IntArray): Boolean } class ArrayOfDoubledPairsGreedy : ArrayOfDoubledPairs { override fun invoke(arr: IntArray): Boolean { val count: MutableMap<Int, Int> = TreeMap() for (a in arr) { count[a] = count.getOrDefault(a, 0) + 1 } for (x in count.keys) { if (count[x] == 0) continue val want = if (x < 0) x / 2 else x * 2 if (x < 0 && x % 2 != 0 || count.getOrDefault(x, 0) > count.getOrDefault(want, 0)) { return false } count[want] = count.getOrDefault(want, 0) - count.getOrDefault(x, 0) } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,504
kotlab
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2022/Day01.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.math.max import kotlin.test.assertEquals object Day01 : AbstractDay() { @Test fun tests() { assertEquals(24000, part1(testInput)) assertEquals(70374, part1(puzzleInput)) assertEquals(45000, part2(testInput)) assertEquals(204610, part2(puzzleInput)) } private fun part1(input: List<String>): Int { val (max, _) = input.fold( initial = 0 to 0, operation = { (max, cnt), s -> val calorie = s.toIntOrZero() val newCnt = if (s.isEmpty()) 0 else cnt + calorie val newMax = max(max, newCnt) newMax to newCnt } ) return max } private fun part2(input: List<String>): Int { val elfCalories = elfCalories(input = input) return elfCalories .sortedDescending() .take(3) .sum() } private fun elfCalories(offset: Int = 0, input: List<String>): List<Int> { val remainingElfCalories = input.sublistOrNull(offset, input.size) ?: return emptyList() val elfCalories = remainingElfCalories .takeWhile { it.isNotEmpty() } .map { it.toInt() } val newOffset = offset + elfCalories.size + 1 return elfCalories(newOffset, input) + elfCalories.sum() } private fun String.toIntOrZero() = this.ifEmpty { "0" }.toInt() }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
1,526
aoc
Apache License 2.0
src/main/kotlin/day10/Day10Second.kt
mdenburger
317,466,663
false
null
package day10 import java.io.File import kotlin.math.pow fun main() { val differences = File("src/main/kotlin/day10/day10-input.txt") .readLines() .map { it.toInt() } .sorted() .let { listOf(0) + it + listOf(it.last() + 3) } .windowed(2) .map { it[1] - it[0] } val permutationsOfOnes = listOf(0, 1, 2, 4, 7) val sublistCount = longArrayOf(0, 0, 0, 0, 0) var numberOfOnes = 0 differences.forEach { diff -> if (diff == 1) { numberOfOnes++ } else { sublistCount[numberOfOnes]++ numberOfOnes = 0 } } var answer = 1L for (i in 2 until sublistCount.size) { val permutations = permutationsOfOnes[i].pow(sublistCount[i]) if (permutations > 0) { answer *= permutations } } println(answer) } fun Int.pow(n: Long) = toDouble().pow(n.toDouble()).toLong()
0
Kotlin
0
0
b965f465cad30f949874aeeacd8631ca405d567e
935
aoc-2020
MIT License
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day16/Packet.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day16 sealed class Packet(open val version: Int, open val subPackets: List<Packet> = emptyList()) { companion object { const val LITERAL_VALUE = 4; } abstract fun evaluate(): Long data class LiteralValue(override val version: Int, val value: Long) : Packet(version) { override fun evaluate() = value } data class Sum(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = subPackets.sumOf { it.evaluate() } } data class Product(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = subPackets.map { it.evaluate() }.fold(1L, Long::times) } data class Minimum(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = subPackets.minOf { it.evaluate() } } data class Maximum(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = subPackets.maxOf { it.evaluate() } } data class GreaterThan(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = if (subPackets[0].evaluate() > subPackets[1].evaluate()) 1L else 0L } data class LessThan(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = if (subPackets[0].evaluate() < subPackets[1].evaluate()) 1L else 0L } data class EqualTo(override val version: Int, override val subPackets: List<Packet>) : Packet(version, subPackets) { override fun evaluate() = if (subPackets[0].evaluate() == subPackets[1].evaluate()) 1L else 0L } fun versionSum(): Int = version + subPackets.sumOf { it.versionSum() } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
1,991
AdventOfCode2021
Apache License 2.0
Kotlin/problems/0033_sort_linked_list.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem Statement /* Sort a linked list in O(n log n) time using constant space complexity. */ class ListNode(var `val`: Int = 0) { var next: ListNode? = null } class Solution { fun sortList(head: ListNode?): ListNode? { if(head == null ) return head; var helper:MutableList<ListNode?> = mutableListOf<ListNode?>(); var iterator: ListNode? = head; while(iterator!=null){ var prev: ListNode?; prev = iterator; iterator = iterator.next; prev.next = null; helper.add(prev); } while(helper.size>1){ var l1: ListNode? = helper[0]; helper.removeAt(0); var l2: ListNode? = helper[0]; helper.removeAt(0); var result: ListNode? = merge(l1,l2); helper.add(result); } return helper[0]; } fun merge(l1: ListNode?, l2: ListNode?): ListNode?{ var dummy: ListNode? = ListNode(-1); var iterator: ListNode? = dummy; var itl1: ListNode? = l1; var itl2: ListNode? = l2; while(itl1!=null && itl2!=null){ if(itl1.`val`<itl2.`val`){ iterator?.next = itl1; itl1 = itl1.next; }else{ iterator?.next = itl2; itl2 = itl2.next; } iterator = iterator?.next; } if(itl1==null) iterator?.next = itl2; else iterator?.next = itl1; return dummy?.next; } } fun vecToLinkedList(vec: IntArray) : ListNode?{ var dummy : ListNode? = ListNode(-1); var iterator : ListNode? = dummy; for(index in vec.indices){ iterator?.next = ListNode(vec[index]); iterator = iterator?.next; } return dummy?.next; } fun printListNode(list : ListNode?){ var iterator: ListNode? = list; while(iterator!=null){ print("${iterator.`val`} "); iterator = iterator.next; } println(); } fun main(args:Array<String>){ val vec : IntArray = intArrayOf(8,10,1,3,2,15); val list : ListNode? = vecToLinkedList(vec); printListNode(list); var merger : Solution = Solution(); printListNode(merger.sortList(list)); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
2,242
algorithms
MIT License
src/main/kotlin/days/aoc2022/Day2.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day class Day2 : Day(2022, 2) { override fun partOne(): Any { return calculateScoreOfGame1(inputList) } override fun partTwo(): Any { return calculateScoreOfGame2(inputList) } fun calculateScoreOfGame1(input: List<String>): Int { return input.sumOf { line -> when (line) { "A X" -> 1 + 3 "A Y" -> 2 + 6 "A Z" -> 3 + 0 "B X" -> 1 + 0 "B Y" -> 2 + 3 "B Z" -> 3 + 6 "C X" -> 1 + 6 "C Y" -> 2 + 0 "C Z" -> 3 + 3 else -> 0 }.toInt() } } fun calculateScoreOfGame2(input: List<String>): Int { return input.sumOf { line -> when (line) { "A X" -> 3 + 0 "A Y" -> 1 + 3 "A Z" -> 2 + 6 "B X" -> 1 + 0 "B Y" -> 2 + 3 "B Z" -> 3 + 6 "C X" -> 2 + 0 "C Y" -> 3 + 3 "C Z" -> 1 + 6 else -> 0 }.toInt() } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,175
Advent-Of-Code
Creative Commons Zero v1.0 Universal
js/js.translator/testData/webDemoExamples2/maze.kt
android
263,405,600
true
null
/** * Let's Walk Through a Maze. * * Imagine there is a maze whose walls are the big 'O' letters. * Now, I stand where a big 'I' stands and some cool prize lies * somewhere marked with a '$' sign. Like this: * * OOOOOOOOOOOOOOOOO * O O * O$ O O * OOOOO O * O O * O OOOOOOOOOOOOOO * O O I O * O O * OOOOOOOOOOOOOOOOO * * I want to get the prize, and this program helps me do so as soon * as I possibly can by finding a shortest path through the maze. */ /** * This function looks for a path from max.start to maze.end through * free space (a path does not go through walls). One can move only * straightly up, down, left or right, no diagonal moves allowed. */ fun findPath(maze: Maze): List<Pair<Int, Int>>? { val previous = HashMap<Pair<Int, Int>, Pair<Int, Int>> val queue = LinkedList<Pair<Int, Int>> val visited = HashSet<Pair<Int, Int>> queue.offer(maze.start) visited.add(maze.start) while (!queue.isEmpty()) { val cell = queue.poll() if (cell == maze.end) break for (newCell in maze.neighbors(cell._1, cell._2)) { if (newCell in visited) continue previous[newCell] = cell queue.offer(newCell) visited.add(cell) } } if (previous[maze.end] == null) return null val path = ArrayList<Pair<Int, Int>>() var current = previous[maze.end] while (current != maze.start) { path.add(0, current) current = previous[current] } return path } /** * Find neighbors of the (i, j) cell that are not walls */ fun Maze.neighbors(i: Int, j: Int): List<Pair<Int, Int>> { val result = ArrayList<Pair<Int, Int>> addIfFree(i - 1, j, result) addIfFree(i, j - 1, result) addIfFree(i + 1, j, result) addIfFree(i, j + 1, result) return result } fun Maze.addIfFree(i: Int, j: Int, result: List<Pair<Int, Int>>) { if (i !in 0..height - 1) return if (j !in 0..width - 1) return if (walls[i][j]) return result.add(Pair(i, j)) } /** * A data class that represents a maze */ class Maze( // Number or columns val width: Int, // Number of rows val height: Int, // true for a wall, false for free space val walls: Array<out Array<out Boolean>>, // The starting point (must not be a wall) val start: Pair<Int, Int>, // The target point (must not be a wall) val end: Pair<Int, Int> ) { } /** A few maze examples here */ fun main(args: Array<String>) { printMaze("I $") printMaze("I O $") printMaze(""" O $ O O O O I """) printMaze(""" OOOOOOOOOOO O $ O OOOOOOO OOO O O OOOOO OOOOO O O O OOOOOOOOO O OO OOOOOO IO """) printMaze(""" OOOOOOOOOOOOOOOOO O O O$ O O OOOOO O O O O OOOOOOOOOOOOOO O O I O O O OOOOOOOOOOOOOOOOO """) } // UTILITIES fun printMaze(str: String) { val maze = makeMaze(str) println("Maze:") val path = findPath(maze) for (i in 0..maze.height - 1) { for (j in 0..maze.width - 1) { val cell = Pair(i, j) print( if (maze.walls[i][j]) "O" else if (cell == maze.start) "I" else if (cell == maze.end) "$" else if (path != null && path.contains(cell)) "~" else " " ) } println("") } println("Result: " + if (path == null) "No path" else "Path found") println("") } /** * A maze is encoded in the string s: the big 'O' letters are walls. * I stand where a big 'I' stands and the prize is marked with * a '$' sign. * * Example: * * OOOOOOOOOOOOOOOOO * O O * O$ O O * OOOOO O * O O * O OOOOOOOOOOOOOO * O O I O * O O * OOOOOOOOOOOOOOOOO */ fun makeMaze(s: String): Maze { val lines = s.split("\n")!! val w = max<String?>(lines.toList(), comparator<String?> { o1, o2 -> val l1: Int = o1?.size ?: 0 val l2 = o2?.size ?: 0 l1 - l2 })!! val data = Array<Array<Boolean>>(lines.size) { Array<Boolean>(w.size) { false } } var start: Pair<Int, Int>? = null var end: Pair<Int, Int>? = null for (line in lines.indices) { for (x in lines[line].indices) { val c = lines[line]!![x] data[line][x] = c == 'O' when (c) { 'I' -> start = Pair(line, x) '$' -> end = Pair(line, x) else -> { } } } } if (start == null) { throw IllegalArgumentException("No starting point in the maze (should be indicated with 'I')") } if (end == null) { throw IllegalArgumentException("No goal point in the maze (should be indicated with a '$' sign)") } return Maze(w.size, lines.size, data, start!!, end!!) } // An excerpt from the Standard Library val String?.indices: IntRange get() = IntRange(0, this!!.size) fun <K, V> Map<K, V>.set(k: K, v: V) { put(k, v) } fun comparator<T> (f: (T, T) -> Int): Comparator<T> = object : Comparator<T> { override fun compare(o1: T, o2: T): Int = f(o1, o2) override fun equals(p: Any?): Boolean = false } fun <T, C : Collection<T>> Array<T>.to(result: C): C { for (elem in this) result.add(elem) return result }
34
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
5,698
kotlin
Apache License 2.0
kotlin/300.Longest Increasing Subsequence(最长上升子序列).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Given an unsorted array of integers, find the length of longest increasing subsequence.</p> <p><b>Example:</b></p> <pre> <b>Input:</b> <code>[10,9,2,5,3,7,101,18] </code><b>Output: </b>4 <strong>Explanation: </strong>The longest increasing subsequence is <code>[2,3,7,101]</code>, therefore the length is <code>4</code>. </pre> <p><strong>Note: </strong></p> <ul> <li>There may be more than one LIS combination, it is only necessary for you to return the length.</li> <li>Your algorithm should run in O(<i>n<sup>2</sup></i>) complexity.</li> </ul> <p><b>Follow up:</b> Could you improve it to O(<i>n</i> log <i>n</i>) time complexity?</p> <p>给定一个无序的整数数组,找到其中最长上升子序列的长度。</p> <p><strong>示例:</strong></p> <pre><strong>输入:</strong> <code>[10,9,2,5,3,7,101,18] </code><strong>输出: </strong>4 <strong>解释: </strong>最长的上升子序列是&nbsp;<code>[2,3,7,101],</code>它的长度是 <code>4</code>。</pre> <p><strong>说明:</strong></p> <ul> <li>可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。</li> <li>你算法的时间复杂度应该为&nbsp;O(<em>n<sup>2</sup></em>) 。</li> </ul> <p><strong>进阶:</strong> 你能将算法的时间复杂度降低到&nbsp;O(<em>n</em> log <em>n</em>) 吗?</p> <p>给定一个无序的整数数组,找到其中最长上升子序列的长度。</p> <p><strong>示例:</strong></p> <pre><strong>输入:</strong> <code>[10,9,2,5,3,7,101,18] </code><strong>输出: </strong>4 <strong>解释: </strong>最长的上升子序列是&nbsp;<code>[2,3,7,101],</code>它的长度是 <code>4</code>。</pre> <p><strong>说明:</strong></p> <ul> <li>可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。</li> <li>你算法的时间复杂度应该为&nbsp;O(<em>n<sup>2</sup></em>) 。</li> </ul> <p><strong>进阶:</strong> 你能将算法的时间复杂度降低到&nbsp;O(<em>n</em> log <em>n</em>) 吗?</p> **/ class Solution { fun lengthOfLIS(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,110
leetcode
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day22.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2017 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.plus fun main() = Day22.run() object Day22 : Day(2017, 22) { // Dirs UP, RIGHT, DOWN, LEFT private var dirs = arrayOf(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0)); override fun part1(): Int { val map = mutableMapOf<Pair<Int, Int>, Int>().withDefault { 0 } // Square input which is center of the total grid val lines = input.lines() val mid = lines.size / 2 for (row in lines.indices) { for (col in lines.indices) { map[Pair(-mid + col, mid - row)] = if (lines[row][col] == '#') 2 else 0 } } val bursts = 10000 var currPos = Pair(0, 0) var currDir = 0 var burstsOfInfection = 0 for (burst in 0 until bursts) { val state = map.getValue(currPos) == 2 currDir = if (state) (currDir + 1) % dirs.size else (currDir + 3) % dirs.size map[currPos] = if (state) 0 else 2 burstsOfInfection += if (!state) 1 else 0 currPos += dirs[currDir] } return burstsOfInfection } override fun part2(): Int { val bursts = 10000000 val map = mutableMapOf<Pair<Int, Int>, Int>().withDefault { 0 } // Square input which is center of the total grid val lines = input.lines() val mid = lines.size / 2 for (row in lines.indices) { for (col in lines.indices) { map[Pair(-mid + col, mid - row)] = if (lines[row][col] == '#') 2 else 0 } } var currPos = Pair(0, 0) var currDir = 0 var burstsOfInfection = 0 for (burst in 0 until bursts) { val state = map.getValue(currPos) currDir = when (state) { 0 -> (currDir + 3) % dirs.size 2 -> (currDir + 1) % dirs.size 3 -> (currDir + 2) % dirs.size else -> currDir } map[currPos] = (state + 1) % 4 burstsOfInfection += if (state == 1) 1 else 0 currPos += dirs[currDir] } return burstsOfInfection } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,223
adventofkotlin
MIT License
advent_of_code/2018/solutions/day_7_b.kt
migafgarcia
63,630,233
false
{"C++": 121354, "Kotlin": 38202, "C": 34840, "Java": 23043, "C#": 10596, "Python": 8343}
import java.io.File import java.util.* data class Task(val id: Char, val incoming: ArrayList<Task>, val outgoing: ArrayList<Task>, var discovered: Boolean = false, var finished: Boolean = false, var executed: Boolean = false) data class Worker(var currentTask: Task? = null, var timeLeft: Int = 0) fun main(args: Array<String>) { val regex = Regex("Step ([A-Z]) must be finished before step ([A-Z]) can begin\\.") val nodes = HashMap<Char, Task>() val taskList = LinkedList<Task>() val workers = arrayOf(Worker(), Worker(), Worker(), Worker(), Worker()) val sequence = generateSequence(0) { it + 1 } File(args[0]).forEachLine { line -> val results = regex.find(line)!!.groupValues val from = results[1][0] val to = results[2][0] nodes.computeIfAbsent(from, { t -> Task(t, ArrayList(), ArrayList()) }) nodes.computeIfAbsent(to, { t -> Task(t, ArrayList(), ArrayList()) }) nodes[to]?.let { nodes[from]!!.outgoing.add(it) } nodes[from]?.let { nodes[to]!!.incoming.add(it) } } nodes.values.sortedBy { it.id }.reversed().forEach { dfs(it, taskList) } for (time in sequence) { workers.filter { it.currentTask != null }.forEach { worker -> worker.timeLeft-- if (worker.timeLeft == 0) { worker.currentTask!!.executed = true worker.currentTask = null } } val freeWorkers = workers.filter { it.currentTask == null } val availableTasks = taskList.filter { task -> task.incoming.none { task -> !task.executed } } availableTasks.zip(freeWorkers).forEach { (first, second) -> taskList.remove(first) second.currentTask = first second.timeLeft = taskTime(first.id) } // print("$time ") // // workers.forEach { // if(it.currentTask == null) // print(". ") // else // print("${it.currentTask!!.id} ") // } // // println() if (taskList.isEmpty() && workers.none { it.currentTask != null }) { println(time) break } } } fun dfs(task: Task, list: LinkedList<Task>) { if (task.finished) return if (task.discovered) throw Exception("Task $task already visited") task.discovered = true task.outgoing.sortedBy { it.id }.reversed().forEach { dfs(it, list) } task.finished = true list.addFirst(task) } fun taskTime(id: Char): Int = 60 + (id - 'A' + 1)
0
C++
3
9
82f5e482c0c3c03fd39e46aa70cab79391ed2dc5
2,558
programming-challenges
MIT License
app/src/main/java/com/alexjlockwood/beesandbombs/demos/utils/MathUtils.kt
alexjlockwood
270,120,227
false
null
package com.alexjlockwood.beesandbombs.demos.utils import kotlin.math.pow import kotlin.math.sqrt const val PI = Math.PI.toFloat() const val TWO_PI = 2 * PI const val HALF_PI = PI / 2 /** * Calculates the cartesian distance between two points. */ fun dist(x1: Float, y1: Float, x2: Float, y2: Float): Float { return sqrt(((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))) } /** * Calculates a number between two numbers at a specific increment. */ fun lerp(a: Float, b: Float, t: Float): Float { return a + (b - a) * t } /** * Re-maps a number from one range to another. */ fun map(value: Float, start1: Float, stop1: Float, start2: Float, stop2: Float): Float { return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)) } /** * Converts the angle measured in radians to an approximately equivalent angle measured in degrees. */ fun Float.toDegrees(): Float { return Math.toDegrees(toDouble()).toFloat() } fun ease(p: Float): Float { return 3 * p * p - 2 * p * p * p } fun ease(p: Float, g: Float): Float { return if (p < 0.5f) { 0.5f * (2 * p).pow(g) } else { 1 - 0.5f * (2 * (1 - p)).pow(g) } }
0
Kotlin
23
374
0d7a86ba60c1734c7b4376d649b019e0c8241c4d
1,174
bees-and-bombs-compose
MIT License
src/main/kotlin/Day14.kt
N-Silbernagel
573,145,327
false
{"Kotlin": 118156}
import java.util.TreeMap fun main() { val input = readFileAsList("Day14") println(Day14.part1(input)) println(Day14.part2(input)) } object Day14 { fun part1(input: List<String>): Int { val field = Field.from(input) return simulateSand(field) } fun part2(input: List<String>): Int { val field = Field.from(input) val floorDescription = "${field.xStart - field.height},${field.yEnd + 2} -> ${field.xEnd + field.height},${field.yEnd + 2}" val fieldWithFloor = Field.from(input + floorDescription) return simulateSand(fieldWithFloor) } private fun simulateSand(field: Field): Int { field.getOrAddSand(Sand(500, 0)) while (true) { if (field.currentSand.y > field.yEnd) { return field.sand.size - 1 } if (field.currentSand.hasFallen) { if (field.currentSand.x == 500 && field.currentSand.y == 0) { return field.sand.size } field.getOrAddSand(Sand(500, 0)) continue } if (field.isAir(field.currentSand.x, field.currentSand.y + 1)) { field.moveCurrentSand(field.currentSand.x, field.currentSand.y + 1) continue } if (field.isAir(field.currentSand.x - 1, field.currentSand.y + 1)) { field.moveCurrentSand(field.currentSand.x - 1, field.currentSand.y + 1) continue } if (field.isAir(field.currentSand.x + 1, field.currentSand.y + 1)) { field.moveCurrentSand(field.currentSand.x + 1, field.currentSand.y + 1) continue } field.currentSand.hasFallen = true } } class Field { private val map: TreeMap<Int, TreeMap<Int, Thing>> = TreeMap() private var _yEnd = 0 private var _locked = false val sand = mutableListOf<Sand>() val currentSand: Sand get() = sand.last() val yEnd: Int get() = _yEnd val xStart: Int get() = map.firstKey() val xEnd: Int get() = map.lastKey() val height: Int get() = _yEnd companion object { fun from(input: List<String>): Field { val field = Field() for (line in input) { val splitLine = line.split(" -> ") val pathCoordinates = splitLine.map { splitLinePart -> splitLinePart.split(",").map { it.toInt() } } for ((pathIndex, coordinates) in pathCoordinates.withIndex()) { val (fromX, fromY) = coordinates val (toX, toY) = pathCoordinates.getOrNull(pathIndex + 1) ?: continue for (x in fromX..toX) { field.getOrAddThing(x, fromY, Rock()) } for (x in toX..fromX) { field.getOrAddThing(x, fromY, Rock()) } for (y in fromY..toY) { field.getOrAddThing(fromX, y, Rock()) } for (y in toY..fromY) { field.getOrAddThing(fromX, y, Rock()) } } } field.lock() return field } } fun getOrAddThing(x: Int, y: Int, thing: Thing): Thing { if (!_locked && y > _yEnd) { _yEnd = y } val row = map.getOrPut(x) { TreeMap() } return row.getOrPut(y) { thing } } fun getOrAddSand(sand: Sand): Thing { this.sand.add(sand) return getOrAddThing(sand.x, sand.y, sand) } fun isAir(x: Int, y: Int): Boolean { return map[x]?.get(y) == null } fun moveCurrentSand(newX: Int, newY: Int) { map[currentSand.x]!!.remove(currentSand.y) currentSand.x = newX currentSand.y = newY getOrAddThing(newX, newY, currentSand) } fun lock() { this._locked = true } } interface Thing private class Rock: Thing data class Sand(var x: Int, var y: Int, var hasFallen: Boolean = false): Thing }
0
Kotlin
0
0
b0d61ba950a4278a69ac1751d33bdc1263233d81
4,564
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day14/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day14 fun launchDay14(testCase: String) { launchPart1(testCase) launchPart2(testCase) } private fun launchPart1(testCase: String) { val input = readInput(testCase) tiltNorth(input) println("Day 14, part 1: ${calcSum(input)}") } private fun launchPart2(testCase: String) { val grid = readInput(testCase) var tilts = 0 val history = mutableListOf<Input>() while (search(grid, history) == -1) { tilts++ history.add(clone(grid)) tiltNorth(grid) tiltWest(grid) tiltSouth(grid) tiltEast(grid) } val goal = 1_000_000_000 val pos = search(grid, history) val diff = tilts - pos var todo = (goal - pos) % diff do { tiltNorth(grid) tiltWest(grid) tiltSouth(grid) tiltEast(grid) todo-- } while (todo > 0) println("Day 14, part 2: ${calcSum(grid)}") } private fun clone(input: Input): Input = input.map { it.toMutableList() }.toMutableList() private fun search(a: Input, bs: List<Input>): Int { bs.forEachIndexed { idx, b -> var res = true loop@ for (row in a.indices) for (col in a[row].indices) { if (a[row][col] != b[row][col]) { res = false break@loop } } if (res) return idx } return -1 } private fun printInput(grid: Input) { println("-----") grid.forEach { println(it.joinToString("")) } } private fun tiltNorth(grid: Input) { for (row in grid.indices) { for (col in grid[row].indices) { if (grid[row][col] == 'O') for (row2 in row - 1 downTo -1) { if (row2 == -1 || grid[row2][col] != '.') { val x = grid[row][col] grid[row][col] = grid[row2 + 1][col] grid[row2 + 1][col] = x break } } } } } private fun tiltWest(grid: Input) { for (col in grid[0].indices) { for (row in grid.indices) { if (grid[row][col] == 'O') for (col2 in col - 1 downTo -1) { if (col2 == -1 || grid[row][col2] != '.') { val x = grid[row][col] grid[row][col] = grid[row][col2 + 1] grid[row][col2 + 1] = x break } } } } } private fun tiltSouth(grid: Input) { for (row in grid.size - 1 downTo 0) { for (col in grid[row].indices) { if (grid[row][col] == 'O') for (row2 in row + 1..grid.size) { if (row2 == grid.size || grid[row2][col] != '.') { val x = grid[row][col] grid[row][col] = grid[row2 - 1][col] grid[row2 - 1][col] = x break } } } } } private fun tiltEast(grid: Input) { for (col in grid[0].size - 1 downTo 0) { for (row in grid.indices) { if (grid[row][col] == 'O') for (col2 in col + 1..grid[0].size) { if (col2 == grid[0].size || grid[row][col2] != '.') { val x = grid[row][col] grid[row][col] = grid[row][col2 - 1] grid[row][col2 - 1] = x break } } } } } private fun calcSum(grid: Input): Int { var result = 0 var counter = grid.size grid.forEach { it.forEach { x -> if (x == 'O') result += counter } counter-- } return result } private fun readInput(testCase: String): Input { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Invalid state, cannot read the input") val rows = mutableListOf<MutableList<Char>>() while (true) { val rawLine = (reader.readLine() ?: break).trim() rows.add(rawLine.toMutableList()) } return rows } private typealias Input = MutableList<MutableList<Char>>
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
4,056
advent-of-code-2023
MIT License