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
2022/src/day04/Day04.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day04 import java.io.File fun main() { val input = File("src/day04/day04input.txt").readLines() println(input.filter { isTotalOverlapping(parseSchedule(it)) }.size) println(input.filter { isAnyOverlapping(parseSchedule(it)) }.size) } val RANGE_REGEX: Regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex() fun parseSchedule(input: String): Pair<IntRange, IntRange> { val match = RANGE_REGEX.matchEntire(input)?.groupValues?.drop(1)?.map { it.toInt() } return if (match != null) { Pair(match[0]..match[1], match[2]..match[3]) } else { Pair(-1..-1, -1..-1) } } fun isTotalOverlapping(schedule: Pair<IntRange, IntRange>): Boolean { return schedule.first.contains(schedule.second.first) && schedule.first.contains(schedule.second.last) || schedule.second.contains(schedule.first.first) && schedule.second.contains(schedule.first.last) } fun isAnyOverlapping(schedule: Pair<IntRange, IntRange>): Boolean { return schedule.first.contains(schedule.second.first) || schedule.first.contains(schedule.second.last) || schedule.second.contains(schedule.first.first) || schedule.second.contains(schedule.first.last) }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
1,213
adventofcode
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day17.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2021 import com.dvdmunckhof.aoc.common.Point import com.dvdmunckhof.aoc.common.Rectangle class Day17(input: String) { private val rectangle: Rectangle init { val regex = Regex("target area: x=(\\d+)\\.\\.(\\d+), y=(-\\d+)\\.\\.(-\\d+)") val (leftX, rightX, bottomY, topY) = regex.matchEntire(input)!!.groupValues.drop(1).map(String::toInt) rectangle = Rectangle(leftX, rightX, bottomY, topY) } fun solvePart1(): Int { val velocityY = -rectangle.bottomY - 1 return velocityY * (velocityY + 1) / 2 // yMax = n*(n+1)/2 } fun solvePart2(): Int { val stepsY = mutableMapOf<Int, MutableList<Int>>() for (vy in rectangle.bottomY..-rectangle.bottomY) { for (step in calculateStepsY(1, vy, 0)) { stepsY.getOrPut(step, ::mutableListOf) += vy } } val maxSteps = stepsY.keys.maxOf { it } val result = mutableSetOf<Point>() for (vx in 1..rectangle.rightX) { calculateStepsX(vx).takeWhile { it <= maxSteps }.forEach { step -> result += stepsY[step]?.map { vy -> Point(vx, vy) } ?: emptyList() } } return result.size } private fun calculateStepsY(step: Int, velocity: Int, position: Int): Array<Int> { val pos = position + velocity if (pos < rectangle.bottomY) { return emptyArray() } val results = calculateStepsY(step + 1, velocity - 1, pos) return if (pos <= rectangle.topY) { results + step } else { results } } private fun calculateStepsX(initialVelocity: Int) = sequence { var step = 1 var position = 0 var velocity = initialVelocity while (true) { position += velocity if (position > rectangle.rightX) { break } if (position >= rectangle.leftX) { yield(step) } else if (velocity == 0) { break } step++ if (velocity > 0) { velocity-- } } } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
2,212
advent-of-code
Apache License 2.0
kotlin/combinatorics/PruferCode.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package combinatorics import java.util.stream.Stream // https://en.wikipedia.org/wiki/Pr%C3%BCfer_sequence object PruferCode { // O(n) complexity fun pruferCode2Tree(pruferCode: IntArray): Array<List<Integer>> { val n = pruferCode.size + 2 val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() } val degree = IntArray(n) Arrays.fill(degree, 1) for (v in pruferCode) ++degree[v] var ptr = 0 while (degree[ptr] != 1) ++ptr var leaf = ptr for (v in pruferCode) { tree[leaf].add(v) tree[v].add(leaf) --degree[leaf] --degree[v] leaf = if (degree[v] == 1 && v < ptr) { v } else { while (degree[++ptr] != 1); ptr } } for (v in 0 until n - 1) { if (degree[v] == 1) { tree[v].add(n - 1) tree[n - 1].add(v) } } return tree } // precondition: n >= 2 // O(n) complexity fun tree2PruferCode(tree: Array<List<Integer>>): IntArray { val n = tree.size val parent = IntArray(n) parent[n - 1] = -1 pruferDfs(tree, parent, n - 1) val degree = IntArray(n) var ptr = -1 for (i in 0 until n) { degree[i] = tree[i].size() if (degree[i] == 1 && ptr == -1) ptr = i } val res = IntArray(n - 2) var i = 0 var leaf = ptr while (i < n - 2) { val next = parent[leaf] res[i] = next --degree[next] leaf = if (degree[next] == 1 && next < ptr) { next } else { while (degree[++ptr] != 1); ptr } ++i } return res } fun pruferDfs(tree: Array<List<Integer>>, parent: IntArray, u: Int) { for (v in tree[u]) { if (v != parent[u]) { parent[v] = u pruferDfs(tree, parent, v) } } } // Usage example fun main(args: Array<String?>?) { val a = IntArray(5) do { val tree: Array<List<Integer>> = pruferCode2Tree(a) val b = tree2PruferCode(tree) if (!Arrays.equals(a, b)) throw RuntimeException() } while (Arrangements.nextArrangementWithRepeats(a, a.size + 2)) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,512
codelibrary
The Unlicense
2021/src/main/kotlin/aoc2021/day10/Day10.kt
dkhawk
433,915,140
false
{"Kotlin": 170350}
package aoc2021.day10 import java.util.LinkedList import utils.Input @OptIn(ExperimentalStdlibApi::class) class Day10 { companion object { fun run() { Day10().part1() Day10().part2() } } val sample = """ [({(<(())[]>[[{[]{<()<>> [(()[<>])]({[<{<<[]>>( {([(<{}[<>[]}>{[]{[(<()> (((({<>}<{<{<>}{[]{[]{} [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] {<[[]]>}<{[{[{[]{()[[[] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{ <{([{{}}[<[[[<>{}]]]>[]] """.trimIndent().split("\n").filter { it.isNotBlank() } val s2 = """ {([(<{}[<>[]}>{[]{[(<()> [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{""".trimIndent().split("\n").filter { it.isNotBlank() } private fun getInput(useRealInput: Boolean): List<String> { return if (useRealInput) { Input.readAsLines("10") // <====== TODO Set the day number!!!! } else { sample } } private val corruptionScore = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) private val completionScore = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4 ) private val bracketPairs = listOf( "()", "[]", "{}", "<>" ).map { it.toCharArray().let { it.first() to it.last() } } private val openToClose = bracketPairs.toMap() private val closeToOpen = bracketPairs.associate { it.second to it.first } private fun part1() { val real = true val inputs = getInput(useRealInput = real) val answer = inputs.sumOf { isCorrupt(it) } println(answer) if (!real) { println(answer == 26397) } } private fun isCorrupt(line: String): Int { val stack = LinkedList<Char>() return line.firstOrNull { c -> when (c) { in openToClose -> { stack.add(c) false } in closeToOpen -> { stack.removeLastOrNull() != closeToOpen[c] } else -> false } }?.let { corruptionScore[it] } ?: 0 } private fun part2() { val inputs = getInput(useRealInput = true) val scores = inputs.asSequence().filter { isCorrupt(it) == 0 }.map { completeMe(it) }.map { it.joinToString("") } .map { it to scoreMe(it) } .sortedBy { it.second }.toList() val median = scores[scores.size / 2] println(median) } private fun scoreMe(s: String): Long = s.fold(0L) { acc, c -> acc * 5 + completionScore[c]!! } private fun completeMe(line: String): List<Char> { val stack = LinkedList<Char>() line.forEach { c -> when (c) { in openToClose -> stack.add(c) in closeToOpen -> { if (stack.isEmpty()) return@forEach if (stack.removeLastOrNull() != closeToOpen[c]) throw Exception("bad character $c") } else -> throw Exception("bad character $c") } } return stack.map { c -> openToClose[c]!! }.asReversed() } }
0
Kotlin
0
0
64870a6a42038acc777bee375110d2374e35d567
2,999
advent-of-code
MIT License
src/main/kotlin/com/github/fantom/codeowners/search/CodeownersSearchFilter.kt
fan-tom
325,829,611
false
{"Kotlin": 257763, "Lex": 5866, "HTML": 966}
package com.github.fantom.codeowners.search import com.github.fantom.codeowners.CodeownersManager import com.github.fantom.codeowners.OwnersList import com.github.fantom.codeowners.indexing.CodeownersEntryOccurrence import com.github.fantom.codeowners.indexing.OwnerString import com.intellij.openapi.vfs.VirtualFile interface Predicate { // TODO change to OwnersSet, duplicates make no sense fun satisfies(fileOwners: OwnersList?): Boolean } sealed interface Filter: Predicate { fun displayName(): CharSequence // TODO rewrite using service + context /** * @return false, if this filter definitely cannot be satisfied by given codeowners file, true otherwise */ fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean sealed interface Condition: Filter { // files without assigned owners data object Unowned: Condition { override fun displayName() = "unowned" override fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean { return true // cannot easily calculate it precise: need to proof there is at least one unowned file } override fun satisfies(fileOwners: OwnersList?) = fileOwners == null } // explicitly unowned files data object OwnershipReset: Condition { override fun displayName() = "explicitly unowned" override fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean { return codeownersFile.items.any { it.second.owners.isEmpty() } } override fun satisfies(fileOwners: OwnersList?) = fileOwners?.isEmpty() ?: false } // files, owned by any (at least one) of the given owners data class OwnedByAnyOf(val owners: Set<OwnerString>): Condition { override fun displayName() = "owned by any of ${owners.joinToString(", ")}" override fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean { return true // because "owners" can be only from this file, so they own some files } override fun satisfies(fileOwners: OwnersList?) = fileOwners?.any { it in owners } ?: false } // files, owned by all the given owners, and maybe by some extra owners data class OwnedByAllOf(val owners: Set<OwnerString>): Condition { override fun displayName() = "owned by all of ${owners.joinToString(", ")}" override fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean { return codeownersFile.items.map { it.second }.any { satisfies(it.owners) } } override fun satisfies(fileOwners: OwnersList?) = fileOwners?.containsAll(owners) ?: false } // files, owned by only given owners, no extra owners allowed data class OwnedByExactly(val owners: Set<OwnerString>): Condition { override fun displayName() = "owned by exactly ${owners.joinToString(", ")}" override fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean { return codeownersFile.items.map { it.second }.any { satisfies(it.owners) } } override fun satisfies(fileOwners: OwnersList?) = fileOwners?.let { owners == it.toSet() } ?: false } } // negation of some Condition data class Not(val condition: Condition): Filter { override fun displayName() = "not ${condition.displayName()}" override fun satisfiable(codeownersFile: CodeownersEntryOccurrence): Boolean { // cannot calculate it in abstract: it depends on the nature of the "condition" return true } override fun satisfies(fileOwners: OwnersList?): Boolean { return !condition.satisfies(fileOwners) } } } // disjunction of conjunctions data class DNF(val filters: List<List<Filter>>): Predicate { override fun satisfies(fileOwners: OwnersList?) = filters.any { conj -> conj.all { n -> n.satisfies(fileOwners) } } fun displayName() = filters.joinToString(" or ") { conj -> "(${conj.joinToString(" and ") { n -> n.displayName() }})" } } data class CodeownersSearchFilter( val codeownersFile: CodeownersEntryOccurrence, // DNF: disjunction of conjunctions private val dnf: DNF ): Predicate by dnf { fun displayName() = "${codeownersFile.url}: ${dnf.displayName()}" context(CodeownersManager) fun satisfies(file: VirtualFile): Boolean { val ownersRef = getFileOwners(file, codeownersFile).getOrNull() ?: return false val ownersList = ownersRef.ref?.owners return satisfies(ownersList) } }
22
Kotlin
4
15
f898c1113f2f81b25aaeb6ba87f8e570da0ba08e
4,726
intellij-codeowners
MIT License
puzzles/kotlin/src/war/war.kt
charlesfranciscodev
179,561,845
false
{"Python": 141140, "Java": 34848, "Kotlin": 33981, "C++": 27526, "TypeScript": 22844, "C#": 22075, "Go": 12617, "JavaScript": 11282, "Ruby": 6255, "Swift": 3911, "Shell": 3090, "Haskell": 1375, "PHP": 1126, "Perl": 667, "C": 493}
import java.util.Scanner import kotlin.system.exitProcess fun main(args : Array<String>) { val game = Game() game.play() } /** * Represents the result of one game turn: * PLAYER1 if player 1 wins this round, * PLAYER2 if player 2 wins this round, * WAR if the two cards played are of equal value * */ enum class Result { PLAYER1, PLAYER2, WAR } class Card(val value: String, val suit: String) : Comparable<Card> { companion object { val intValues: HashMap<String, Int> = hashMapOf( "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9, "10" to 10, "J" to 11, "Q" to 12, "K" to 13, "A" to 14 ) } override fun compareTo(other: Card): Int { val value1 = intValues.getOrDefault(value, 0) val value2 = intValues.getOrDefault(other.value, 0) return value1 - value2 } } class Game { val input = Scanner(System.`in`) var deck1 = readGameInput() var deck2 = readGameInput() var nbRounds = 0 fun readGameInput(): List<Card> { val n = input.nextInt() // the number of cards for the player val cards = ArrayList<Card>(n) for (i in 0 until n) { val valueSuit = input.next() val value = valueSuit.substring(0, valueSuit.length - 1) val suit = valueSuit.substring(valueSuit.length - 1) cards.add(Card(value, suit)) } return cards } fun play() { var index = 0 while (true) { val result = playTurn(index) val rotateIndex = index + 1 if (result == Result.PLAYER1) { nbRounds++ deck1 = rotate(deck1, rotateIndex) deck1 += deck2.take(rotateIndex) // take other player's cards deck2 = deck2.drop(rotateIndex) // remove other player's cards index = 0 } else if (result == Result.PLAYER2) { nbRounds++ deck2 += deck1.take(rotateIndex) // take other player's cards deck1 = deck1.drop(rotateIndex) // remove other player's cards deck2 = rotate(deck2, rotateIndex) index = 0 } else { // WAR index += 4 } } } fun rotate(deck: List<Card>, index: Int): List<Card> { return deck.drop(index) + deck.take(index) } /** Returns the result of one game turn */ fun playTurn(index: Int): Result { if (index > deck1.size || index > deck2.size) { println("PAT") exitProcess(0) } checkGameOver() val card1 = deck1[index] val card2 = deck2[index] return when { card2 < card1 -> Result.PLAYER1 card1 < card2 -> Result.PLAYER2 else -> Result.WAR } } fun checkGameOver() { if (deck1.isEmpty()) { println("2 $nbRounds") exitProcess(0) } if (deck2.isEmpty()) { println("1 $nbRounds") exitProcess(0) } } }
0
Python
19
45
3ec80602e58572a0b7baf3a2829a97e24ca3460c
2,779
codingame
MIT License
src/main/kotlin/endredeak/aoc2023/Day05.kt
edeak
725,919,562
false
{"Kotlin": 26575}
package endredeak.aoc2023 // import endredeak.aoc2023.lib.utils.pMap data class SeedMap(val ranges: List<Triple<Long, Long, Long>>) { fun map(n: Long): Long = ranges .singleOrNull { (_, s, r) -> n in s..< (s + r) } ?.let { (d, s, _) -> n + d - s } ?: n } fun main() { solve("If You Give A Seed A Fertilizer") { val (seeds, seedMaps) = lines[0] .replace("seeds: ", "") .split(" ") .map { it.toLong() } to text .split("\n\n") .drop(1) .map { part -> part .split("\n") .drop(1) .map { map -> map.split(" ") .map { it.toLong() } .let { (s, d, r) -> Triple(s, d, r) } }.let { SeedMap(it) } } fun mapSeed(seed: Long): Long { var id = seed seedMaps.forEach { seedMap -> val newId = seedMap.map(id) id = newId } return id } part1(173706076) { seeds.minOfOrNull { seed -> mapSeed(seed) }!! } part2(11611182) { // brute force vv takes 10 minutes // seeds // .windowed(2, 2) // .map { (s, r) -> s..< (s + r) } // .pMap { seedRange -> seedRange.minOfOrNull { seed -> mapSeed(seed) }!! } // .min() 11611182 } } }
0
Kotlin
0
0
92c684c42c8934e83ded7881da340222ff11e338
1,753
AdventOfCode2023
Do What The F*ck You Want To Public License
src/leetcodeProblem/leetcode/editor/en/ContainsDuplicate.kt
faniabdullah
382,893,751
false
null
//Given an integer array nums, return true if any value appears at least twice //in the array, and return false if every element is distinct. // // // Example 1: // Input: nums = [1,2,3,1] //Output: true // Example 2: // Input: nums = [1,2,3,4] //Output: false // Example 3: // Input: nums = [1,1,1,3,3,4,3,2,4,2] //Output: true // // // Constraints: // // // 1 <= nums.length <= 10⁵ // -10⁹ <= nums[i] <= 10⁹ // // Related Topics Array Hash Table Sorting 👍 2676 👎 891 package leetcodeProblem.leetcode.editor.en class ContainsDuplicate { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun containsDuplicate(nums: IntArray): Boolean { val hashMap: HashMap<Int, Int> = HashMap() for (i in nums.indices) { if (hashMap.containsKey(nums[i])) return true else hashMap[nums[i]] = 1 } return false } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,148
dsa-kotlin
MIT License
classroom/src/main/kotlin/com/radix2/algorithms/week3/HalfSizedAuxArray.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week3 // Merging with smaller auxiliary array. // Suppose that the sub array 𝚊[𝟶] to 𝚊[𝚗−𝟷] is sorted and the subarray 𝚊[𝚗] to 𝚊[𝟸 ∗ 𝚗 − 𝟷] is sorted. // How can you merge the two sub arrays so that 𝚊[𝟶] to 𝚊[𝟸 ∗ 𝚗−𝟷] is sorted using an auxiliary array of length n (instead of 2n)? fun mergeWithSmallerAux(array: IntArray, aux: IntArray = IntArray(array.size / 2), lo: Int, mid: Int, hi: Int) { System.arraycopy(array, lo, aux, lo, aux.size) var i = lo var j = mid + 1 var k = 0 while(i <= mid && j <= hi) { if (aux[i] > array[j]) { array[k++] = array[j++] } else { array[k++] = aux[i++] } } while(i <= mid) array[k++] = aux[i++] while(j <= hi) array[k++] = array[j++] } fun main(args: Array<String>) { val array = intArrayOf(1, 3, 5, 7, 9, 11, 0, 2, 4, 6, 8, 10) mergeWithSmallerAux(array, lo = 0, mid = (array.size - 1) / 2, hi = array.size - 1) println(array.joinToString()) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
1,089
coursera-algorithms-part1
Apache License 2.0
src/main/kotlin/org/holo/kGrammar/Tree.kt
Holo314
343,512,707
false
null
package org.holo.kGrammar import java.util.* /** * A class that represent the set of all possible symbols, it is partitioned into 2 classes: * * [Terminal] - the class that represent all of the terminal symbols * * [NonTerminal] - the class that represent all non-terminal symbols */ sealed class Symbol { sealed class Terminal : Symbol() { companion object { fun from(symbol: Regex) = CustomTemplate(symbol) } data class CustomTemplate internal constructor(val symbol: Regex) : Terminal() { init { require(symbol.pattern.isNotEmpty()) { "Empty symbols are not allowed, use org.holo.kGrammar.Symbol.Terminal.Empty to represent empty sequence" } } } /** * A symbol that represent the end of sequence, it is used only internally and should not be added to a rule */ object EOS : Terminal() /** * A symbol that represent the empty sequence, if it appears in a rule it must appear alone and rules that it appears on represent "remove symbol" rules. * * For example: `A -> Empty` is the rule "when the non-terminal A appear, one can remove it" */ object Empty : Terminal() } sealed class NonTerminal : Symbol() { companion object { fun generate() = Custom(UUID.randomUUID().toString()) // This method is used for debugging, it helps following each symbol in the internal parts of the parsers internal fun generate(input: String) = Custom(input) } data class Custom internal constructor(val identifier: String) : NonTerminal() /** * A symbol that represent the starting point of the parsing, one should build his grammar starting from this symbol */ object Start : NonTerminal() } } /** * A class that represent a production rule for the grammar */ data class Rule private constructor(val head: Symbol.NonTerminal, val body: List<Symbol>) { init { require(body.isNotEmpty()) { "The rule must not be empty, use org.holo.kGrammar.Symbol.Terminal.Empty to represent empty sequence" } require(Symbol.Terminal.EOS !in body) { "EOS should not be used inside of a rule, it is a terminating token used internally." + "It is exposed for those who wish to deal with Parse Tables" } if (body[0] is Symbol.NonTerminal) { require(body[0] != head) { "Left recursion is not allowed" } } if (body.filterNot { it is Symbol.Terminal.EOS }.size > 1) { require(Symbol.Terminal.Empty !in body) { "The empty terminal cannot appear with other rules" } } } companion object { fun from(definition: Pair<Symbol.NonTerminal, List<Symbol>>) = Rule(definition.first, definition.second) fun rulesSet(generator: RuleResource.() -> Unit) = RuleResource(mutableSetOf()).apply(generator).mutableSet.toSet() data class RuleResource(val mutableSet: MutableSet<Rule>) { operator fun Pair<Symbol.NonTerminal, List<Symbol>>.unaryPlus() = mutableSet.add(Rule(first, second)) } } } data class Token(val symbol: Symbol.Terminal, val value: String, val position: IntRange) /** * A class that represent CST */ sealed class ParseTree { data class TerminalNode internal constructor(val symbol: Symbol.Terminal, val value: Token) : ParseTree() object EmptyNode: ParseTree() data class NonTerminalNode internal constructor(val symbol: Symbol.NonTerminal, val children: List<ParseTree>) : ParseTree() companion object { /** * This function remove nodes whose direct child is an empty node * ``` * S * / \ S * A C | * / \ | ==> A * a B ε | * | a * ε * ``` */ fun removeEmpty(node: NonTerminalNode): ParseTreeNonEmpty.NonTerminalNode { require(node.children.first() !is EmptyNode) { "the node cannot have direct empty children" } val newChildren = node.children.filter { when(it) { is TerminalNode -> true is NonTerminalNode -> it.children.first() !is EmptyNode is EmptyNode -> error("something went horribly wrong") } }.map { when(it) { is TerminalNode -> ParseTreeNonEmpty.TerminalNode(it) is NonTerminalNode -> removeEmpty(it) is EmptyNode -> error("something went horribly wrong") } } return ParseTreeNonEmpty.NonTerminalNode(node.symbol, newChildren) } } } fun ParseTree.NonTerminalNode.removeEmpty(): ParseTreeNonEmpty.NonTerminalNode = ParseTree.removeEmpty(this) /** * This sealed hierarchy exist because Kotlin does not support sum types, nor(at the time of writing this line) have sealed interfaces as stable feature, * so we need a separate hierarchy when we exclude the [ParseTree.EmptyNode] (otherwise one won't be able use pattern matching in a normal and natural way) */ sealed class ParseTreeNonEmpty { data class TerminalNode internal constructor(val symbol: Symbol.Terminal, val token: Token) : ParseTreeNonEmpty() { constructor(node: ParseTree.TerminalNode) : this(node.symbol, node.value) } data class NonTerminalNode internal constructor(val symbol: Symbol.NonTerminal, val children: List<ParseTreeNonEmpty>) : ParseTreeNonEmpty() }
0
Kotlin
0
0
af5568fc4d1a56d98a93a645ca0ffbbf966a450b
5,650
KGrammar
MIT License
day22/src/main/kotlin/Day22.kt
bzabor
160,240,195
false
null
import kotlin.math.pow import kotlin.math.sqrt typealias CellTool = Pair<Cell, Tool> class Day22(private val input: List<String>) { // sample // val depth = 510 // val targetRow = 10 // val targetCol = 10 //actual val depth = 11817 val targetCol = 9 val targetRow = 751 val gridExtendRight = 30 val gridExtendDown = 30 val MAX_SCORE = Integer.MAX_VALUE var grid = Array(targetRow + 1 + gridExtendDown) { Array(targetCol + 1 + gridExtendRight) { Cell() } } // https://rosettacode.org/wiki/A*_search_algorithm // https://www.geeksforgeeks.org/a-search-algorithm/ // guess 7436 too high, 7433 too high, (2146 too high,2143 too high with gridextend 10) with grideExtend20: 2146 // 0,0 got it down to less than 1070, cant recall exact - 1064? 1039 was not correct // for 30, 30 try 1027 - not correct.. 1025 is! // val start = Triple(0,0, Tool.TORCH) val start = Pair(Cell(0, 0), Tool.TORCH) val finish = Pair(Cell(targetRow, targetCol), Tool.TORCH) val openVertices = mutableSetOf(start) val closedVertices = mutableSetOf<CellTool>() val costFromStart = mutableMapOf(start to 0) val estimatedTotalCost = mutableMapOf(start to distanceToTarget(start.first)) val cameFrom = mutableMapOf<CellTool, CellTool>() // Used to generate path by back tracking // neighbors are the four compass points, plus a tool switch at current position fun getNeighbors(cellTool: CellTool): List<CellTool> { val neighbors = mutableListOf<CellTool>() if (cellTool.first.row + 1 in 0..grid.lastIndex) { neighbors.add(CellTool(grid[cellTool.first.row + 1][cellTool.first.col], cellTool.second)) } if (cellTool.first.col + 1 in 0..grid[0].lastIndex) { neighbors.add(CellTool(grid[cellTool.first.row][cellTool.first.col + 1], cellTool.second)) } if (cellTool.first.col - 1 in 0..grid[0].lastIndex) { neighbors.add(CellTool(grid[cellTool.first.row][cellTool.first.col - 1], cellTool.second)) } if (cellTool.first.row - 1 in 0..grid.lastIndex) { neighbors.add(CellTool(grid[cellTool.first.row - 1][cellTool.first.col], cellTool.second)) } // filter out neighbors that don't actually have torch as a tool val eligible = neighbors.filter { it.first.cellType.tools.contains(cellTool.second) }.toMutableList() val otherTool = cellTool.first.cellType.tools.filterNot { it == cellTool.second }[0] eligible.add(Pair(cellTool.first, otherTool)) println("for cell: ${cellTool.first} eligible neighbors are: $eligible") val finalEligible = eligible.filterNot { closedVertices.contains(it) } // println("for cell: ${cellTool.first} filtered final eligible neighbors are: $finalEligible") return finalEligible } fun starSearch() { /** * Use the cameFrom values to Backtrack to the start position to generate the path */ fun generatePath(currentPos: CellTool, cameFrom: Map<CellTool, CellTool>): List<CellTool> { val path = mutableListOf(currentPos) var current = currentPos while (cameFrom.containsKey(current)) { current = cameFrom.getValue(current) path.add(0, current) } return path.toList() } while (openVertices.size > 0) { val currentPos = openVertices.minBy { estimatedTotalCost.getValue(it) }!! // Check if we have reached the finish if (currentPos == finish) { val path = generatePath(currentPos, cameFrom) println("currentPos == finish with TOTAL COST ${estimatedTotalCost.getValue(finish)}") println("Final path is: $path") println("==".repeat(50)) return } // Mark the current vertex as closed openVertices.remove(currentPos) closedVertices.add(currentPos) val neighbors = getNeighbors(currentPos) neighbors .filterNot { closedVertices.contains(it) } // Exclude previous visited vertices .forEach { neighbor -> val moveCost = moveCost(currentPos, neighbor) val score = costFromStart.getValue(currentPos) + moveCost if (score < costFromStart.getOrDefault(neighbor, MAX_SCORE)) { if (!openVertices.contains(neighbor)) { openVertices.add(neighbor) } cameFrom.put(neighbor, currentPos) // sets parent costFromStart.put(neighbor, score) estimatedTotalCost.put(neighbor, score + distanceToTarget(neighbor.first)) } } } throw IllegalArgumentException("No Path from Start $start to Finish $finish") } fun moveCost(currentPos: CellTool, neighbor: CellTool): Int { val cost = if (currentPos.second == neighbor.second) 1 else 7 println("cost to move from ${currentPos.first},${currentPos.second} to ${neighbor.first},${neighbor.second} ------> $cost") return cost } fun init() { for (row in 0..targetRow + gridExtendDown) { for (col in 0..targetCol + gridExtendRight) { val cell = grid[row][col] cell.row = row cell.col = col setGeoLogicIndex(cell) setCellErosionLevel(cell) setCellType(cell) } } } fun part1(): Int { init() printGrid() starSearch() return 0 } // Before you go in, you should determine the risk level of the area. For the the rectangle that has a top-left corner // of region 0,0 and a bottom-right corner of the region containing the target, add up the risk level of each individual // region: 0 for rocky regions, 1 for wet regions, and 2 for narrow regions. // In the cave system above, because the mouth is at 0,0 and the target is at 10,10, adding up the risk level of all // regions with an X coordinate from 0 to 10 and a Y coordinate from 0 to 10, this total is 114. private fun riskLevel(): Int { val riskList = grid.flatMap { it.filter { it.row <= targetRow && it.col <= targetCol } }.sumBy { it.cellType.risk } return riskList } private fun setGeoLogicIndex(cell: Cell) { cell.geologicIndex = when { (cell.row == 0 && cell.col == 0) || (cell.row == targetRow && cell.col == targetCol) -> 0 cell.row == 0 -> cell.col * 16807 cell.col == 0 -> cell.row * 48271 else -> grid[cell.row][cell.col - 1].erosionLevel * grid[cell.row - 1][cell.col].erosionLevel } } private fun setCellErosionLevel(cell: Cell) { cell.erosionLevel = (cell.geologicIndex + depth) % 20183 } private fun setCellType(cell: Cell) { cell.cellType = when (cell.erosionLevel % 3) { 0 -> CellType.ROCKY 1 -> CellType.WET 2 -> CellType.NARROW else -> throw Exception("unknown cell type") } } var count = 0 fun distanceToTarget(cell: Cell): Double { return sqrt((targetRow - cell.row).toDouble().pow(2) + (targetCol - cell.col).toDouble().pow(2)) } private fun printGrid() { println("") println("-".repeat(50)) for (cellRow in grid) { for (cell in cellRow) { val symbol = when { cell.row == 0 && cell.col == 0 -> "M" cell.row == targetRow && cell.col == targetCol -> "T" else -> cell.cellType.symbol } print("$symbol ") } println("") } println("-".repeat(50)) println("") } } enum class Tool(val symbol: Char) { CLIMBING_GEAR('C'), TORCH('T'), NEITHER('N') } enum class CellType(val symbol: Char, val risk: Int, val tools: List<Tool>) { ROCKY('.', 0, listOf(Tool.CLIMBING_GEAR, Tool.TORCH)), WET('=', 1, listOf(Tool.CLIMBING_GEAR, Tool.NEITHER)), NARROW('|', 2, listOf(Tool.TORCH, Tool.NEITHER)) } data class Cell( var row: Int = 0, var col: Int = 0 ) { var geologicIndex: Int = 0 var erosionLevel: Int = 0 var cellType: CellType = CellType.ROCKY var pathSum: Int = 0 override fun toString() = "$row:$col" fun distanceToNeighbor(cell: Cell, currentTool: Tool) = if (cell.cellType.tools.contains(currentTool)) 1 else 7 }
0
Kotlin
0
0
14382957d43a250886e264a01dd199c5b3e60edb
8,857
AdventOfCode2018
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/StrobogrammaticNumber.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 /** * 246. Strobogrammatic Number */ fun interface StrobogrammaticNumber { operator fun invoke(num: String): Boolean } /** * Approach 1: Make a Rotated Copy * Time complexity : O(N). * Space complexity : O(N). */ class StrobogrammaticRotated : StrobogrammaticNumber { override operator fun invoke(num: String): Boolean { val rotatedDigits = charArrayOf('0', '1', '\u0000', '\u0000', '\u0000', '\u0000', '9', '\u0000', '8', '6') val rotatedStringBuilder = StringBuilder() for (i in num.length - 1 downTo 0) { val c: Char = num[i] val charIndex = Character.getNumericValue(c) rotatedStringBuilder.append(rotatedDigits[charIndex]) } val rotatedString = rotatedStringBuilder.toString() return num == rotatedString } } /** * Approach 2: Two Pointers * Time complexity : O(N). * Space complexity : O(1). */ class StrobogrammaticTwoPointers : StrobogrammaticNumber { override operator fun invoke(num: String): Boolean { val rotatedDigits: Map<Char, Char> = hashMapOf('0' to '0', '1' to '1', '6' to '9', '8' to '8', '9' to '6') var left = 0 var right: Int = num.length - 1 while (left <= right) { val leftChar: Char = num[left] val rightChar: Char = num[right] if (!rotatedDigits.containsKey(leftChar) || rotatedDigits[leftChar] != rightChar) { return false } left++ right-- } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,182
kotlab
Apache License 2.0
src/main/kotlin/days/aoc2020/Day7.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2020 import days.Day class Day7: Day(2020, 7) { fun createBagList(list: List<String>): Map<String,Bag> { val bags: MutableMap<String,Bag> = mutableMapOf() list.forEach { Regex("(\\w+ \\w+)").find(it)?.destructured?.let { (bagDescriptor) -> bags.putIfAbsent(bagDescriptor, Bag(bagDescriptor)) val bag = bags[bagDescriptor]!! Regex("(\\d+) (\\w+ \\w+) bag").findAll(it)?.forEach { it.destructured?.let { (count, descriptor) -> bags.putIfAbsent(descriptor, Bag(descriptor)) bag.descendants.add(Pair(bags[descriptor]!!, count.toInt())) bags[descriptor]!!.ancestors.add(bag) } } } } return bags } fun countDescendents(bag: Bag): Int { val result = bag.descendants.map { (containedBag, number) -> val descendants = countDescendents(containedBag) + 1 number * if (descendants > 0) descendants else 1 }.sum() return result } override fun partTwo(): Any { val bags = createBagList(inputList) return countDescendents(bags["shiny gold"]!!) } override fun partOne(): Any { val bags = createBagList(inputList) return countAncestors(bags["shiny gold"]!!) } class Bag(val descriptor: String) { val descendants: MutableList<Pair<Bag, Int>> = mutableListOf() val ancestors: MutableSet<Bag> = mutableSetOf() } fun countAncestors(bag: Bag): Int { return traverseAncestors(bag, mutableSetOf()).count() } fun traverseAncestors(bag: Bag, bags: MutableSet<Bag>): MutableSet<Bag> { bags.addAll(bag.ancestors) bag.ancestors.forEach { traverseAncestors(it, bags) } return bags } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,936
Advent-Of-Code
Creative Commons Zero v1.0 Universal
Kotlin for Java Developers. Week 2/Mastermind/Task/src/mastermind/playMastermind.kt
binout
159,054,839
false
null
package mastermind import java.util.* val ALPHABET = 'A'..'F' val CODE_LENGTH = 4 fun main(args: Array<String>) { playBullsAndCows() } fun playBullsAndCows( secret: String = generateSecret() ) { val scanner = Scanner(System.`in`) var evaluation: Evaluation do { print("Your guess: ") var guess = scanner.next() while (hasErrorsInInput(guess)) { println("Incorrect input: $guess. " + "It should consist of ${CODE_LENGTH} digits. " + "Try again.") guess = scanner.next() } evaluation = evaluateGuess(secret, guess) if (evaluation.isComplete()) { println("You are correct!") } else { println("Positions: ${evaluation.rightPosition}; letters: ${evaluation.wrongPosition}.") } } while (!evaluation.isComplete()) } fun Evaluation.isComplete(): Boolean = rightPosition == CODE_LENGTH fun hasErrorsInInput(guess: String): Boolean { val possibleLetters = ALPHABET.toSet() return guess.length != CODE_LENGTH || guess.any { it !in possibleLetters } } fun generateSecret(differentLetters: Boolean = false): String { val chars = ALPHABET.toMutableList() val random = Random() return buildString { for (i in 1..CODE_LENGTH) { val letter = chars[random.nextInt(chars.size)] append(letter) if (differentLetters) { chars.remove(letter) } } } }
0
Kotlin
1
5
40ff182f63d29443fa3c29730560d37e2325501a
1,520
coursera-kotlin
Apache License 2.0
src/main/kotlin/day6.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* fun main() { val input = Input.day(6) println(day6A(input)) println(day6B(input)) } fun day6A(input: Input): Int { val times = input.lines[0].toLongs() val records = input.lines[1].toLongs() val winOptions = times.mapIndexed { index, time -> raceWinOptions(time, records[index]) } return winOptions.reduce { acc, i -> acc * i } } fun day6B(input: Input): Int { val time = input.lines[0].replace(" ", "").split(':')[1].toLong() val record = input.lines[1].replace(" ", "").split(':')[1].toLong() return raceWinOptions(time, record) } private fun raceWinOptions(time: Long, record: Long): Int { var count = 0 for(charge in 1 .. time) { val moved = (time - charge) * charge if(moved > record) count++ } return count }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
819
AdventOfCode2023
MIT License
year2022/src/cz/veleto/aoc/year2022/Day09.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import cz.veleto.aoc.core.Pos import cz.veleto.aoc.core.minus import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.sign class Day09(config: Config) : AocDay(config) { override fun part1(): String = countTailPositions(ropeLength = 2).toString() override fun part2(): String = countTailPositions(ropeLength = 10).toString() private fun countTailPositions(ropeLength: Int): Int { val rope = MutableList(ropeLength) { 0 to 0 } val tailPoses = mutableSetOf(rope.last()) for (s in input) { val (direction, steps) = parseMotion(s) repeat(steps) { rope[0] = moveHead(rope[0], direction) rope.indices.drop(1).forEach { rope[it] = moveTail(rope[it - 1], rope[it]) } tailPoses += rope.last() } } return tailPoses.size } private fun parseMotion(line: String): Pair<Char, Int> { val (directionChars, stepsChars) = line.split(' ') val direction = directionChars.single() val steps = stepsChars.toInt() return direction to steps } private fun moveHead(head: Pos, direction: Char): Pos { val (hx, hy) = head return when (direction) { 'U' -> hx to hy + 1 'R' -> hx + 1 to hy 'D' -> hx to hy - 1 'L' -> hx - 1 to hy else -> error("wut direction $direction") } } private fun moveTail(head: Pos, tail: Pos): Pos { val (tx, ty) = tail val (dx, dy) = head - tail return when { max(dx.absoluteValue, dy.absoluteValue) <= 1 -> tail dx != 0 && dy != 0 -> tx + dx.sign to ty + dy.sign dx != 0 -> tx + dx.sign to ty dy != 0 -> tx to ty + dy.sign else -> error("wut ds") } } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
1,915
advent-of-pavel
Apache License 2.0
2022/src/main/kotlin/de/skyrising/aoc2022/day3/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day3 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.chars.CharOpenHashSet @PuzzleName("Rucksack Reorganization") fun PuzzleInput.part1(): Any { var sum = 0 for (line in lines) { val comp1 = line.slice(0 until line.length / 2) val comp2 = line.slice(line.length / 2 until line.length) val items1 = CharOpenHashSet(comp1.toCharArray()) val items2 = CharOpenHashSet(comp2.toCharArray()) items1.retainAll(items2) val same = items1.single() sum += when (same) { in 'a'..'z' -> same.code - 'a'.code + 1 in 'A'..'Z' -> same.code - 'A'.code + 27 else -> 0 } } return sum } fun PuzzleInput.part2(): Any { var sum = 0 for (i in lines.indices step 3) { val items1 = CharOpenHashSet(lines[i].toCharArray()) val items2 = CharOpenHashSet(lines[i + 1].toCharArray()) val items3 = CharOpenHashSet(lines[i + 2].toCharArray()) items1.retainAll(items2) items1.retainAll(items3) val same = items1.single() sum += when (same) { in 'a'..'z' -> same.code - 'a'.code + 1 in 'A'..'Z' -> same.code - 'A'.code + 27 else -> 0 } } return sum }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,287
aoc
MIT License
calendar/day01/Day1.kt
rscuddertnow
726,288,081
false
{"Kotlin": 9759}
package day01 import Day import Lines class Day1 : Day() { val digits:List<String> = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") override fun part1(input: Lines): Any { return input.fold(0) { total, line: String -> val firstDigit = line.first { it.isDigit() } val lastDigit = line.findLast { it.isDigit() } "$firstDigit$lastDigit".toInt() + total } } override fun part2(input: Lines): Any { return input.fold(0) { total, line: String -> val firstDigit = line.findAnyOf(digits).let(::getDigit) val lastDigit = line.findLastAnyOf(digits).let(::getDigit) "$firstDigit$lastDigit".toInt() + total } } private fun getDigit(stringDigit:Pair<Int, String>?) : String { return when(stringDigit!!.second) { "zero" -> "0" "one" -> "1" "two" -> "2" "three" -> "3" "four" -> "4" "five" -> "5" "six" -> "6" "seven" -> "7" "eight" -> "8" "nine" -> "9" else -> stringDigit.second } } }
0
Kotlin
0
0
30bc609fa9fda383de74d267a86d6ecf2e782402
1,257
aoc2023-kotlin
Apache License 2.0
y2019/src/main/kotlin/adventofcode/y2019/Day08.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution fun main() = Day08.solve() object Day08 : AdventSolution(2019, 8, "Space Image Format") { override fun solvePartOne(input: String) = input .chunked(6 * 25) .map { layer -> layer.groupingBy { it }.eachCount() } .minByOrNull { it['0'] ?: 0 } ?.let { (it['1'] ?: 0) * (it['2'] ?: 0) } override fun solvePartTwo(input: String) = input .chunked(6 * 25) .reduce(this::mergeLayers) .map { if (it == '1') "██" else " " } .chunked(25) .joinToString(separator = "\n", prefix = "\n") { it.joinToString("") } private fun mergeLayers(foreground: String, background: String): String = foreground.zip(background, this::mergePixels).joinToString("") private fun mergePixels(foreground: Char, background: Char): Char = if (foreground != '2') foreground else background }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
964
advent-of-code
MIT License
kotlin/154.Find Minimum in Rotated Sorted Array II(寻找旋转排序数组中的最小值 II).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.</p> <p>(i.e., &nbsp;<code>[0,1,2,4,5,6,7]</code>&nbsp;might become &nbsp;<code>[4,5,6,7,0,1,2]</code>).</p> <p>Find the minimum element.</p> <p>The array may contain duplicates.</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> [1,3,5] <strong>Output:</strong> 1</pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> [2,2,2,0,1] <strong>Output:</strong> 0</pre> <p><strong>Note:</strong></p> <ul> <li>This is a follow up problem to&nbsp;<a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/">Find Minimum in Rotated Sorted Array</a>.</li> <li>Would allow duplicates affect the run-time complexity? How and why?</li> </ul> <p>假设按照升序排序的数组在预先未知的某个点上进行了旋转。</p> <p>( 例如,数组&nbsp;<code>[0,1,2,4,5,6,7]</code> <strong> </strong>可能变为&nbsp;<code>[4,5,6,7,0,1,2]</code>&nbsp;)。</p> <p>请找出其中最小的元素。</p> <p>注意数组中可能存在重复的元素。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> [1,3,5] <strong>输出:</strong> 1</pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> [2,2,2,0,1] <strong>输出:</strong> 0</pre> <p><strong>说明:</strong></p> <ul> <li>这道题是&nbsp;<a href="https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/description/">寻找旋转排序数组中的最小值</a>&nbsp;的延伸题目。</li> <li>允许重复会影响算法的时间复杂度吗?会如何影响,为什么?</li> </ul> <p>假设按照升序排序的数组在预先未知的某个点上进行了旋转。</p> <p>( 例如,数组&nbsp;<code>[0,1,2,4,5,6,7]</code> <strong> </strong>可能变为&nbsp;<code>[4,5,6,7,0,1,2]</code>&nbsp;)。</p> <p>请找出其中最小的元素。</p> <p>注意数组中可能存在重复的元素。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> [1,3,5] <strong>输出:</strong> 1</pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> [2,2,2,0,1] <strong>输出:</strong> 0</pre> <p><strong>说明:</strong></p> <ul> <li>这道题是&nbsp;<a href="https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/description/">寻找旋转排序数组中的最小值</a>&nbsp;的延伸题目。</li> <li>允许重复会影响算法的时间复杂度吗?会如何影响,为什么?</li> </ul> **/ class Solution { fun findMin(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,634
leetcode
MIT License
src/main/kotlin/Day08R.kt
rileynull
437,153,864
false
null
package rileynull.aoc // This code is heinous. See the note in Day08.kt. object Day08R { data class Line(val inputs: List<Set<Segment>>, val outputs: List<Set<Segment>>) enum class Segment { A, B, C, D, E, F, G } object SevenSegmentDisplay { val digits = mapOf( Pair(0, setOf(Segment.A, Segment.B, Segment.C, Segment.E, Segment.F, Segment.G)), Pair(1, setOf(Segment.C, Segment.F)), Pair(2, setOf(Segment.A, Segment.C, Segment.D, Segment.E, Segment.G)), Pair(3, setOf(Segment.A, Segment.C, Segment.D, Segment.F, Segment.G)), Pair(4, setOf(Segment.B, Segment.C, Segment.D, Segment.F)), Pair(5, setOf(Segment.A, Segment.B, Segment.D, Segment.F, Segment.G)), Pair(6, setOf(Segment.A, Segment.B, Segment.D, Segment.E, Segment.F, Segment.G)), Pair(7, setOf(Segment.A, Segment.C, Segment.F)), Pair(8, setOf(Segment.A, Segment.B, Segment.C, Segment.D, Segment.E, Segment.F, Segment.G)), Pair(9, setOf(Segment.A, Segment.B, Segment.C, Segment.D, Segment.F, Segment.G)) ) fun decodeSegments(segments: Set<Segment>): Int { for (result in digits.filterValues { it == segments }) return result.key error("No decoding for ${segments.joinToString("")}.") } } /** * Implements an undirected bipartite graph. The firsts and seconds of `edges` should be disjoint. */ @ExperimentalStdlibApi class BipartiteGraph<T>(val edges: List<Pair<T, T>>) { // Adjacency lists from each U to its adjacent vertices in V in the input graph. private val forwardMapping = edges.groupBy({ it.first }, { it.second }) /** * Finds a matching using a vaguely Ford–Fulkerson type algorithm. * * We have two disjoint sets of vertices, U and V, with edges only going between the two sets. The idea of the * algorithm is that at each step we augment our existing matching by using an alternating path. This is a * path that starts at an unmatched U and ends at an unmatched V, with 2n+1 edges alternating between being * in and out of the existing matching. If we can find such a path, we can improve our matching by removing the * n edges that are already part of the matching and adding the n+1 other edges. */ fun matching(): List<Pair<T, T>> { // These hold our current matching at any given time, in both the forward and reverse directions. val uMatching = mutableMapOf<T, T>() val vMatching = mutableMapOf<T, T>() fun findAlternatingPath(): List<T> { val vPredecessors = mutableMapOf<T, T>() /** * Use vPredecessors to reconstruct the path that the BFS took to arrive at the unmatched V. */ fun reconstructPath(endV: T): List<T> { val path = mutableListOf<T>() var v: T? = endV while (v != null) { val u = vPredecessors[v]!! path.add(v) path.add(u) v = uMatching[u] } path.reverse() return path } // Do a BFS to find the shortest alternating path from an unmatched U to an unmatched V. // At each step we start at a U, then check its V neighbors to see if they're matched. If no, we're // done. If yes, we enqueue the U that each one is matched to. This guarantees that we take an // alternating path. val uQueue = ArrayDeque<T>(forwardMapping.keys.filter { it !in uMatching }.shuffled()) while (uQueue.isNotEmpty()) { val u = uQueue.removeFirst() for (v in forwardMapping[u]!!.shuffled()) { if (v in vPredecessors) continue vPredecessors[v] = u val nextU = vMatching[v] if (nextU != null) uQueue.addLast(nextU) else return reconstructPath(v) } } return listOf() } // Use alternating paths to repeatedly augment our current best matching. var alternatingPath = findAlternatingPath() while (alternatingPath.isNotEmpty()) { for (segment in alternatingPath.windowed(2, 2)) { uMatching[segment[0]] = segment[1] vMatching[segment[1]] = segment[0] } alternatingPath = findAlternatingPath() } return uMatching.toList() } } } @ExperimentalStdlibApi fun main() { fun splitToSegments(str: String) = str.split(' ').map { it.map { Day08R.Segment.valueOf(it.toUpperCase().toString()) }.toSet()} val lines = {}.javaClass.getResource("/day08.txt").openStream().reader().buffered().lineSequence() .map { it.split(" | ") } .map { halves -> Day08R.Line(splitToSegments(halves[0]), splitToSegments(halves[1])) } .toList() val partA = lines.flatMap { it.outputs }.count { it.size == 2 || it.size == 4 || it.size == 3 || it.size == 7 } println("The answer to part A is $partA.") val partB = lines.sumBy { val possibleMappingsPerWord = it.inputs.map { segments -> val possibleMappings = Day08R.SevenSegmentDisplay.digits.values .filter { it.size == segments.size } .reduce { acc, cur -> acc.union(cur) } segments.map { Pair(it, possibleMappings) }.toMap().toMutableMap() } val possibleMappings = possibleMappingsPerWord.reduce { acc, cur -> for (item in cur) { acc.merge(item.key, item.value) { old, new -> old.intersect(new) } } acc } val edges = possibleMappings.flatMap { kv -> kv.value.map { Pair(kv.key, it) } } var matching: Map<Day08R.Segment, Day08R.Segment> while (true) { matching = Day08R.BipartiteGraph(edges).matching().toMap() try { // check our answer :) it.inputs.map { it.map { matching[it]!! }.toSet() }.map(Day08R.SevenSegmentDisplay::decodeSegments) it.outputs.map { it.map { matching[it]!! }.toSet() }.map(Day08R.SevenSegmentDisplay::decodeSegments) break; } catch (_: IllegalStateException) { } } val unscrambled = it.outputs.map { it.map { matching[it]!! }.toSet() } unscrambled.map(Day08R.SevenSegmentDisplay::decodeSegments).joinToString("").toInt() } println("The answer to part B is $partB.") }
0
Kotlin
0
0
2ac42faa192767f00be5db18f4f1aade756c772b
7,134
adventofcode
Apache License 2.0
src/Day08_part1.kt
lowielow
578,058,273
false
{"Kotlin": 29322}
class Tree { val list = mutableListOf<MutableList<String>>() var visibleCount: Int= 0 private fun checkAll(i: Int, j: Int): Boolean = checkLeft(i, j) || checkRight(i, j) || checkTop(i, j) || checkBottom(i, j) private fun checkLeft(i: Int, j: Int): Boolean { for (n in 0 until j) { if (list[i][n] < list[i][j]) { continue } else { return false } } return true } private fun checkRight(i: Int, j: Int): Boolean { for (n in j + 1 until list[0].size) { if (list[i][n] < list[i][j]) { continue } else { return false } } return true } private fun checkTop(i: Int, j: Int): Boolean { for (n in 0 until i) { if (list[n][j] < list[i][j]) { continue } else { return false } } return true } private fun checkBottom(i: Int, j: Int): Boolean { for (n in i + 1 until list.size) { if (list[n][j] < list[i][j]) { continue } else { return false } } return true } fun handleVisibleCount(): Int { for (i in list.indices) { for (j in list[i].indices) { if (i >= 1 && i <= list.size - 2 && j >= 1 && j <= list[0].size - 2) { if (checkAll(i, j)) { visibleCount++ } } } } return visibleCount } } fun main() { val tree = Tree() val input: List<String> = readInput("Day08") for (str in input) { tree.list.add(str.map{ it.toString() }.toMutableList()) } tree.visibleCount = (tree.list.size - 1) * 4 tree.handleVisibleCount().println() }
0
Kotlin
0
0
acc270cd70a8b7f55dba07bf83d3a7e72256a63f
1,917
aoc2022
Apache License 2.0
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day06/Day06.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day06 import eu.janvdb.aocutil.kotlin.readCommaSeparatedNumbers const val FILENAME = "input06.txt" const val SPAWN_DELAY = 7 const val INITIAL_DELAY = 2 fun main() { val state = State.readFromInput() // Part 1 runDays(state, 80) // Part 2 runDays(state, 256) } private fun runDays(initialState: State, numberOfDays: Int) { var state = initialState println("0\t${state.totalFish()}\t${state.fishPerDay}") for (i in 1..numberOfDays) { state = state.next() println("$i\t${state.totalFish()}\t${state.fishPerDay}") } } data class State(val fishPerDay: Map<Int, Long>) { fun totalFish() = fishPerDay.values.sum() fun next(): State { val newFishPerDay = mutableMapOf<Int, Long>() fun addFishPerDay(day: Int, fish: Long) { newFishPerDay[day] = newFishPerDay.getOrDefault(day, 0) + fish } fishPerDay.forEach { entry -> if (entry.key == 0) { addFishPerDay(SPAWN_DELAY - 1, entry.value) addFishPerDay(SPAWN_DELAY + INITIAL_DELAY - 1, entry.value) } else { addFishPerDay(entry.key - 1, entry.value) } } return State(newFishPerDay) } companion object { fun readFromInput(): State { val input = readCommaSeparatedNumbers(2021, FILENAME) .groupBy { it } .map { Pair(it.key, it.value.size.toLong()) } .toMap() return State(input) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,336
advent-of-code
Apache License 2.0
src/main/kotlin/com/sk/topicWise/tree/easy/637. Average of Levels in Binary Tree.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.tree.easy import com.sk.topicWise.tree.TreeNode class Solution637 { fun averageOfLevels(root: TreeNode?): DoubleArray { val list = arrayListOf<Pair<Int, Double>>() dfs(root, 0, list) return list.map { it.second / it.first }.toDoubleArray() } fun dfs(root: TreeNode?, level: Int, list: ArrayList<Pair<Int, Double>>) { if (root == null) { return } if (list.size <= level) { val p = Pair(1, root.`val`.toDouble()) list.add(p) } else { val first = list[level].first + 1 val second = list[level].second + root.`val`.toDouble() list[level] = Pair(first, second) } dfs(root.left, level + 1, list) dfs(root.right, level + 1, list) } fun averageOfLevels2(root: TreeNode?): DoubleArray { val list = arrayListOf<Double>() if (root == null) { return list.toDoubleArray() } val queue = ArrayDeque<TreeNode>() queue.add(root) while (!queue.isEmpty()) { val count = queue.size var size = count var sum = 0.0 while (size > 0) { val cur = queue.removeFirst() sum += cur.`val` cur.left?.let { queue.add(it) } cur.right?.let { queue.add(it) } size-- } list.add(sum / count) } return list.toDoubleArray() } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,524
leetcode-kotlin
Apache License 2.0
src/main/kotlin/day2/Day2.kt
erolsvik
573,456,869
false
{"Kotlin": 2081}
package day2 import java.io.File val values = mapOf("A" to 1, "B" to 2, "C" to 3) val values2 = mapOf("X" to 1, "Y" to 2, "Z" to 3) val winValues = mapOf("X" to "C", "Y" to "A", "Z" to "B") val lossValues = mapOf("X" to "B", "Y" to "C", "Z" to "A") val drawValues = mapOf("X" to "A", "Y" to "B", "Z" to "C") var totalScore = 0 fun main() { task2() println(totalScore) } fun task1() { loadFile().useLines { it.iterator().forEachRemaining { line -> val hand = line.split(" ") if (hand[0] == drawValues[hand[1]]) { totalScore += 3 } else if(hand[0] == winValues[hand[1]]) { totalScore += 6 } totalScore += values[drawValues[hand[1]]]!!.toInt() } } } fun task2() { loadFile().useLines { it.iterator().forEachRemaining { line -> val hand = line.split(" ") when(hand[1]) { "Y" -> totalScore += 3 + values2[invertMap(drawValues)[hand[0]]!!]!!.toInt() "Z" -> totalScore += 6 + values2[invertMap(winValues)[hand[0]]!!]!!.toInt() else -> totalScore += values2[invertMap(lossValues)[hand[0]]!!]!!.toInt() } } } } private fun loadFile(): File { return File("C:\\dev\\Advent_of_code_2022\\src\\main\\kotlin\\day2\\input.txt") } private fun invertMap(ogMap: Map<String, String>): Map<String, String> = ogMap.entries.associateBy({ it.value }) { it.key }
0
Kotlin
0
0
82f1bbbdfb3c1a6c74be88fc48107e8d4e0c43eb
1,493
advent-of-code-2022
Apache License 2.0
src/main/kotlin/solutions/Day05.kt
chutchinson
573,586,343
false
{"Kotlin": 21958}
typealias Action = Triple<Int, Int, Int> typealias Stack = ArrayDeque<Char> class Day05 : Solver { data class Puzzle( val stacks: List<Stack>, val actions: List<Action>) fun Puzzle.move (multiple: Boolean): Puzzle { for (action in this.actions) { val (count, from, to) = action val crates = ArrayDeque<Char>() for (x in 0..count-1) { val crate = this.stacks[from - 1].removeFirst() if (multiple) crates.addFirst(crate) else crates.addLast(crate) } while (crates.size > 0) { val crate = crates.removeFirst() this.stacks[to - 1].addFirst(crate) } } return this } fun Puzzle.display (): String { return this.stacks.map { it.first() }.joinToString("") } fun parse (input: List<String>): Puzzle { val stacks = mutableListOf<Stack>() val actions = mutableListOf<Action>() var state = 0 for (line in input) { if (line.isEmpty()) { state = 1 continue } if (state == 0) { val pattern = Regex("\\[(.)\\]+") val matches = pattern.findAll(line).map { it.groups[1] }.toList() for (group in matches) { val index = (group!!.range.first - 1) / 4 while (stacks.size <= index) stacks.add(ArrayDeque()) stacks[index].add(group.value[0]) } } if (state == 1) { val pattern = Regex("move (\\d+) from (\\d+) to (\\d+)") val rmatch = pattern.find(line) val (a, b, c) = rmatch!!.destructured actions.add(Action(a.toInt(), b.toInt(), c.toInt())) } } return Puzzle(stacks, actions) } override fun solve (input: Sequence<String>) { val lines = input.toList() println(first(parse(lines))) println(second(parse(lines))) } fun first (input: Puzzle): String = input.move(false).display() fun second (input: Puzzle): String = input.move(true).display() }
0
Kotlin
0
0
5076dcb5aab4adced40adbc64ab26b9b5fdd2a67
2,244
advent-of-code-2022
MIT License
common/src/commonMain/kotlin/ticketToRide/PlayerScore.kt
Kiryushin-Andrey
253,543,902
false
{"Kotlin": 278687, "Dockerfile": 845, "JavaScript": 191}
package ticketToRide import graph.* const val InitialStationsCount = 3 const val PointsPerStation = 4 class PlayerScore( override val name: PlayerName, override val color: PlayerColor, val occupiedSegments: List<Segment>, val placedStations: List<CityId>, tickets: List<Ticket>, segmentsOccupiedByOtherPlayers: List<Segment>, private val map: GameMap ): PlayerId { private val fulfilledTicketsPoints get() = fulfilledTickets.sumOf { it.points } private val unfulfilledTicketPoints get() = unfulfilledTickets.sumOf { it.points } val stationsLeft get() = InitialStationsCount - placedStations.size val stationPoints = stationsLeft * PointsPerStation val segmentsPoints get() = occupiedSegments.groupingBy { it.length }.eachCount().entries .sumOf { (length, count) -> map.getPointsForSegments(length) * count } private fun getLongestPathPoints(longestPathOfAll: Int) = if (longestPathOfAll > 0 && longestRoute == longestPathOfAll) map.pointsForLongestRoute else 0 fun getTotalPoints(longestPathOfAll: Int, gameInProgress: Boolean): Int { val result = fulfilledTicketsPoints + segmentsPoints + stationPoints + getLongestPathPoints(longestPathOfAll) return if (gameInProgress) result else result - unfulfilledTicketPoints } val longestRoute: Int val fulfilledTickets: List<Ticket> val unfulfilledTickets: List<Ticket> init { val graph = buildSegmentsGraph(occupiedSegments) val subgraphs = graph.splitIntoConnectedSubgraphs().toList() fulfilledTickets = getFulfilledTickets( tickets, occupiedSegments, placedStations, segmentsOccupiedByOtherPlayers, graph, subgraphs ) unfulfilledTickets = tickets - fulfilledTickets longestRoute = subgraphs .map { it.getMaxEulerianSubgraph().getTotalWeight() } .maxOrNull() ?: 0 } }
1
Kotlin
3
11
0ad7aa0b79f7d97cbac6bc4cd1b13b6a1d81e442
1,989
TicketToRide
MIT License
src/main/java/challenges/educative_grokking_coding_interview/two_heaps/_4/ScheduleTask.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.two_heaps._4 import challenges.util.PrintHyphens import java.util.* /** Given a set of n number of tasks, implement a task scheduler method, tasks(), to run in O(n logn) time that finds the minimum number of machines required to complete these n tasks. https://www.educative.io/courses/grokking-coding-interview-patterns-java/YQoGA7Wz5zM */ object ScheduleTask { private fun tasks(tasksList: ArrayList<ArrayList<Int?>>): Int { // to count the total number of machines for "optimalMachines" tasks var optimalMachines = 0 val machinesAvailable = PriorityQueue(Comparator.comparingInt { a: IntArray -> a[0] }) val tasksQueue = PriorityQueue(Comparator.comparingInt { a: IntArray -> a[0] }) for (task in tasksList) { tasksQueue.offer( intArrayOf( task[0]!!, task[1]!! ) ) } while (!tasksQueue.isEmpty()) { // looping through the tasks list // remove from "tasksQueue" the task i with earliest start time val task = tasksQueue.poll() var machineInUse: IntArray if (!machinesAvailable.isEmpty() && task[0] >= machinesAvailable.peek()[0]) { // top element is deleted from "machinesAvailable" machineInUse = machinesAvailable.poll() // schedule task on the current machine machineInUse = intArrayOf( task[1], machineInUse[1] ) } else { // if there's a conflicting task, increment the // counter for machines and store this task's // end time on heap "machinesAvailable" optimalMachines += 1 machineInUse = intArrayOf( task[1], optimalMachines ) } machinesAvailable.offer(machineInUse) } // return the total number of machines return optimalMachines } @JvmStatic fun main(args: Array<String>) { // Input: A set "tasks_list" of "n" tasks, such that // each taskList has a start time and a finish time val inputs = listOf( listOf( listOf(1, 1), listOf(5, 5), listOf(8, 8), listOf(4, 4), listOf(6, 6), listOf(10, 10), listOf(7, 7) ), listOf( listOf(1, 7), listOf(1, 7), listOf(1, 7), listOf(1, 7), listOf(1, 7), listOf(1, 7) ), listOf( listOf(1, 7), listOf(8, 13), listOf(5, 6), listOf(10, 14), listOf(6, 7) ), listOf( listOf(1, 3), listOf(3, 5), listOf(5, 9), listOf(9, 12), listOf(12, 13), listOf(13, 16), listOf(16, 17) ), listOf( listOf(12, 13), listOf(13, 15), listOf(17, 20), listOf(13, 14), listOf(19, 21), listOf(18, 20) ) ) // loop to execute till the length of tasks val inputTaskList = ArrayList<ArrayList<ArrayList<Int?>>>() for (j in inputs.indices) { inputTaskList.add(ArrayList()) for (k in inputs[j].indices) { inputTaskList[j].add(ArrayList()) for (g in inputs[j][k].indices) { inputTaskList[j][k].add(inputs[j][k][g]) } } } for (i in inputTaskList.indices) { println("${i + 1}.\tTask = " + inputTaskList[i].toString()) // Output: A non-conflicting schedule of tasks in // "tasks_list" using the minimum number of machines println("\tOptimal number of machines = " + tasks(inputTaskList[i])) println(PrintHyphens.repeat("-", 100)) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
4,258
CodingChallenges
Apache License 2.0
kotlin/graphs/lca/LcaSchieberVishkin.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.lca import java.util.stream.Stream // Answering LCA queries in O(1) with O(n) preprocessing class LcaSchieberVishkin(tree: Array<List<Integer>>, root: Int) { var parent: IntArray var preOrder: IntArray var I: IntArray var head: IntArray var A: IntArray var time = 0 fun dfs1(tree: Array<List<Integer>>, u: Int, p: Int) { parent[u] = p preOrder[u] = time++ I[u] = preOrder[u] for (v in tree[u]) { if (v == p) continue dfs1(tree, v, u) if (Integer.lowestOneBit(I[u]) < Integer.lowestOneBit(I[v])) { I[u] = I[v] } } head[I[u]] = u } fun dfs2(tree: Array<List<Integer>>, u: Int, p: Int, up: Int) { A[u] = up or Integer.lowestOneBit(I[u]) for (v in tree[u]) { if (v == p) continue dfs2(tree, v, u, A[u]) } } fun enterIntoStrip(x: Int, hz: Int): Int { if (Integer.lowestOneBit(I[x]) === hz) return x val hw: Int = Integer.highestOneBit(A[x] and hz - 1) return parent[head[I[x] and -hw or hw]] } fun lca(x: Int, y: Int): Int { val hb: Int = if (I[x] == I[y]) Integer.lowestOneBit(I[x]) else Integer.highestOneBit(I[x] xor I[y]) val hz: Int = Integer.lowestOneBit(A[x] and A[y] and -hb) val ex = enterIntoStrip(x, hz) val ey = enterIntoStrip(y, hz) return if (preOrder[ex] < preOrder[ey]) ex else ey } companion object { // Usage example fun main(args: Array<String?>?) { val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(5).toArray { _Dummy_.__Array__() } tree[0].add(1) tree[0].add(2) tree[1].add(3) tree[1].add(4) val lca = LcaSchieberVishkin(tree, 0) System.out.println(0 == lca.lca(1, 2)) System.out.println(1 == lca.lca(3, 4)) System.out.println(0 == lca.lca(4, 2)) } } init { val n = tree.size preOrder = IntArray(n) I = IntArray(n) head = IntArray(n) A = IntArray(n) parent = IntArray(n) dfs1(tree, root, -1) dfs2(tree, root, -1, 0) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,272
codelibrary
The Unlicense
src/main/kotlin/com/cbrew/unify/Unifiable.kt
cbrew
248,690,438
false
{"Kotlin": 147469, "ANTLR": 8870, "Vue": 8502, "HTML": 303, "Dockerfile": 123}
package com.cbrew.unify sealed class Unifiable { fun label(): String = when (this) { is AtomicValue -> value is FeatureMap -> "${get("cat")?.label()}[${get("f")?.label()}]" else -> "??" } fun key(): String = when (this) { is AtomicValue -> value is FeatureMap -> get("cat")?.label() ?: "??" else -> "??" } } sealed class FeatureStructure : Unifiable() data class AtomicValue(val value: String) : FeatureStructure() { override fun toString(): String { return value } } data class SemanticValue(val value: Lambda) : FeatureStructure() { override fun toString(): String { return "<${value}>" } } data class QueryVariable(val name: String) : FeatureStructure() { override fun toString(): String { return name } } data class FeatureList(val elements: List<Unifiable>) : FeatureStructure() { override fun toString(): String = "[${elements.joinToString()}]" } data class FeatureListExpression(val elements: List<Unifiable>) : FeatureStructure() { override fun toString(): String = "[${elements.joinToString()}]" fun simplify(): FeatureStructure { // maybe we can simplify by collapsing adjacent elements // result might then be an aggregate or remain an expression val acc = mutableListOf<Unifiable>() var copyIsExpression = false for (element in elements) { when (element) { is FeatureTuple -> acc.addAll(element.elements) is FeatureList -> acc.addAll(element.elements) is QueryVariable -> { copyIsExpression = true; acc.add(element) } else -> acc.add(element) } } if (copyIsExpression) { return FeatureListExpression(acc) } else { return FeatureList(acc) } } } data class FeatureTuple(val elements: List<Unifiable>) : FeatureStructure() { override fun toString(): String = "[${elements.joinToString()}]" } data class FeatureTupleExpression(val elements: List<Unifiable>) : FeatureStructure() { override fun toString(): String = "[${elements.joinToString()}]" fun simplify(): FeatureStructure { // maybe we can simplify by collapsing adjacent elements // result might then be an aggregate or remain an expression val acc = mutableListOf<Unifiable>() var copyIsExpression = false for (element in elements) { when (element) { is FeatureTuple -> acc.addAll(element.elements) is FeatureList -> acc.addAll(element.elements) is QueryVariable -> { copyIsExpression = true; acc.add(element) } else -> acc.add(element) } } if (copyIsExpression) { return FeatureTupleExpression(acc) } else { return FeatureTuple(acc) } } } fun emptyFeatureList(): FeatureList = FeatureList(listOf()) data class FeatureMap(private val delegate: Map<String, Unifiable>) : FeatureStructure(), Map<String, Unifiable> by delegate { override fun toString(): String { return if ("cat" in this) "${this["cat"]}${(this - "cat").asIterable()}" else "${this}" } } data class Grammar(val rules: Set<Rule>, val lexicon: Map<String, Set<FeatureMap>>) : FeatureStructure() { override fun toString(): String = "rules\n${rules.joinToString(separator = "\n")}\nlexicon\n${lexicon.asIterable() .joinToString(separator = "\n")}" } fun emptyGrammar(): Grammar = Grammar(setOf(), mapOf()) interface Rule data class CfgRule(val lhs: FeatureMap, val rhs: List<FeatureMap>, val words: List<Unifiable>) : Rule, FeatureStructure() { override fun toString(): String { return "${lhs} -> ${rhs.joinToString(separator = " ")}" } } data class McfgRule(val lhs: FeatureMap, val rhs: List<FeatureMap>, val linseq: FeatureList) : FeatureStructure(), Rule { override fun toString(): String { return "${lhs} => ${rhs.joinToString(separator = " ")}: <${linseq.elements.joinToString()}>" } } sealed class Lambda : Unifiable() data class Constant(val name: String) : Lambda() { override fun toString(): String { return name } } data class Var(val index: Int) : Lambda() { override fun toString(): String { return "v:${index}" } } data class QVar(val index: Int) : Lambda() { override fun toString(): String { return "q:${index}" } } data class Lam(val body: Lambda) : Lambda() { override fun toString(): String { return "\u03BB.($body)" } } data class Forall(val body: Lambda) : Lambda() { override fun toString(): String = "\u2200.(${body})" // TODO hide DeBruijn notation } data class Exists(val body: Lambda) : Lambda() { override fun toString(): String = "\u2203.(${body})" // TODO hide DeBruijn notation } data class App(val e1: Lambda, val e2: Lambda) : Lambda() { override fun toString(): String { val acc = uncurry() return "${acc.get(0)}(${acc.subList(1,acc.size).joinToString(", ")})" } private fun uncurry() :List<Lambda>{ val acc = mutableListOf<Lambda>() // currried verstion is a left-branching tree when (e1) { is App -> acc.addAll(e1.uncurry()) else -> acc.add(e1) } acc.add(e2) return acc } } data class Not(val body: Lambda) : Lambda() data class And(val conjuncts: Set<Lambda>) : Lambda() { override fun toString(): String { return "(${conjuncts.joinToString(separator = " \u2227 ")})" } } data class Or(val disjuncts: Set<Lambda>) : Lambda() { override fun toString(): String { return "(${disjuncts.joinToString(separator = " \u2228 ")})" } } data class Implies(val e1: Lambda, val e2: Lambda) : Lambda() data class Equiv(val e1: Lambda, val e2: Lambda) : Lambda() data class FstructVar(val name: String) : Lambda() { override fun toString(): String { return name } } object Box : Lambda() object Empty : Lambda() data class Integer(val value: Int) : FeatureStructure() { override fun toString(): String { return "${value}" } } fun atomicMap(atom: String): FeatureMap = FeatureMap(mapOf(Pair("cat", AtomicValue(atom))))
1
Kotlin
0
0
16c4e42911782595e419f38c23796ce34b65f384
6,608
quadruplet
Apache License 2.0
src/main/kotlin/arr/MaxPop.kt
yx-z
106,589,674
false
null
package arr fun main(args: Array<String>) { // given a list of [birth year, death year] // find the year that the most people are alive val testArr = arrayOf( 1961 to 2000, 1978 to 2015, 1858 to 1912, 1900 to 1950, 1992 to 2025, 1990 to 1991 ) println(testArr.getMostPopulationYear()) println(testArr.getMostPopulationYearOptimize()) } fun Array<Pair<Int, Int>>.getMostPopulationYear(): Int { val minBirthYear = this.minBy { it.first }!!.first val maxDeathYear = this.maxBy { it.second }!!.second val year = IntArray(maxDeathYear - minBirthYear + 1) forEach { (birthYear, deathYear) -> (birthYear..deathYear).forEach { year[it - minBirthYear]++ } } return year.withIndex().maxBy { it.value }!!.index + minBirthYear } fun Array<Pair<Int, Int>>.getMostPopulationYearOptimize(): Int { val minBirthYear = this.minBy { it.first }!!.first val maxDeathYear = this.maxBy { it.second }!!.second val year = IntArray(maxDeathYear - minBirthYear + 1) forEach { (birthYear, deathYear) -> year[birthYear - minBirthYear]++ year[deathYear - minBirthYear]-- } year.indices .filter { it > 0 } .forEach { year[it] += year[it - 1] } return year.withIndex().maxBy { it.value }!!.index + minBirthYear }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,243
AlgoKt
MIT License
2022/programming/AtCoder/220312_ABC243/src/main/kotlin/MainE.kt
kyoya-p
253,926,918
false
{"Kotlin": 797744, "JavaScript": 82500, "HTML": 54815, "TypeScript": 51200, "Java": 30096, "C++": 28982, "CMake": 20831, "Dart": 14886, "Shell": 7841, "Batchfile": 6182, "CSS": 5729, "Dockerfile": 3451, "Swift": 1622, "C": 1489, "PowerShell": 234, "Objective-C": 78}
package main.e import testenv.stdioEmulatior import testenv.testEnv val ex = testEnv { debug = true intake.println( """ 5 6 1 2 4 1 4 1 1 5 9 2 5 1 2 3 1 3 4 1 """.trimIndent() ) outlet.readLine() == "2" } val envs = listOf( testEnv { intake.println(""" 3 3 1 2 2 2 3 3 1 3 6 """.trimIndent() ) outlet.readLine() == "1" }, testEnv { intake.println( """ 5 4 1 3 3 2 3 9 3 5 3 4 5 3 """.trimIndent() ) outlet.readLine() == "0" }, testEnv { debug = true intake.println( """ 5 10 1 2 71 1 3 9 1 4 82 1 5 64 2 3 22 2 4 99 2 5 1 3 4 24 3 5 18 4 5 10 """.trimIndent() ) outlet.readLine() == "5" } ) fun main() { open class Edge<NODE>(val a: NODE, val b: NODE) data class EdgeND<NODE>(val a1: NODE, val b1: NODE) : Edge<NODE>(a1, b1) { // 無方向グラフ override fun hashCode(): Int = a.hashCode() + b.hashCode() override fun equals(other: Any?): Boolean = (other is Edge<*>) && (a == other.a && b == other.b || a == other.b && b == other.a) } data class EdgeWeight<EDGE>(val e: EDGE, val w: Int) fun <NODE> graphLibFloydWarshall(edgeList: List<EdgeWeight<EdgeND<NODE>>>): Map<Edge<NODE>, Int> { val edgeMap: MutableMap<Edge<NODE>, Int> = edgeList.associate { it.e to it.w }.toMutableMap() val nodeList = edgeList.asSequence().flatMap { sequenceOf(it.e.a, it.e.b) }.distinct() nodeList.flatMap { i -> nodeList.flatMap { j -> nodeList.map { k -> listOf(EdgeND(i, j), EdgeND(i, k), EdgeND(k, j)) } } }.distinct().forEach { ij_ik_kj -> val (eij, _, _) = ij_ik_kj val (ij, ik, kj) = ij_ik_kj.map { edgeMap[it] } //System.err.print("$eij=$ij $eik=$ik $ekj=$kj") when { ik != null && kj != null && ij != null -> if (ij > ik + kj) edgeMap[eij] = ik + kj ik != null && kj != null && ij == null -> edgeMap[eij] = ik + kj } //System.err.print(" / ${ij_ik_kj[0]}=$eik $eik=$ik $ekj=$kj") //System.err.println() } return edgeMap } fun MutableList<MutableList<Int>>.floydWarshall() { val e = this asSequence().withIndex().flatMap { (i, n1) -> n1.asSequence().withIndex().flatMap { (j, wij) -> (0 until e.size).asSequence().map { k -> val (wik, wkj) = listOf(e[i][k], e[k][j]) if (wij > wik + wkj) e[i][j] = wik + wkj } } } } class MutableMatrix2<T : Number>(val n: Int, val init: (Int, Int) -> T) : Iterable<Triple<Int, Int, T>> { val m = MutableList(n * n) { init(it % n, it / n) } fun ad(i: Int, j: Int) = if (i > j) i * n + j else j * n + i operator fun get(n1: Int, n2: Int) = m[ad(n1, n2)] //operator fun get(node: Pair<Int, Int>) = this[node.first, node.second] operator fun set(n1: Int, n2: Int, w: T) = { m[ad(n1, n2)] = w }() //operator fun set(node: Pair<Int, Int>, w: T) = { m[ad(node.first, node.second)] = w }() fun clone() = MutableMatrix2(n) { i, j -> m[ad(i, j)] } fun replace(op: (Pair<Int, Int>, T) -> T) = apply { m.mapIndexed { i, e -> m[i] = op(i % n to i / n, e) } } fun <R> mapIndexed(op: (Pair<Int, Int>, T) -> R) = m.mapIndexed { i, e -> op(i % n to i / n, e) } fun <R> forEachIndexed(op: (Pair<Int, Int>, T) -> R) = entries.map { op(it.i to it.j, it.w) } val entries get() = (0 until n).flatMap { i -> (0 until i).map { j -> Entry(i, j, m[ad(i, j)]) } } inner class Entry(val i: Int, val j: Int, val w: T) { override fun toString() = "(${i + 1},${j + 1})=$w" } override fun iterator(): Iterator<Triple<Int, Int, T>> { TODO("Not yet implemented") } } @Suppress("LocalVariableName") fun main() { val (N, M) = readLine()!!.split(" ").map { it.toInt() } val MaxValue = 1000000000 val W = MutableMatrix2(N) { i, j -> MaxValue } repeat(M) { val (a, b, w) = readLine()!!.split(" ").map { it.toInt() } W[a - 1, b - 1] = w } val Wmin = W.clone().apply { forEachIndexed { (i, j), wij -> (0 until N).map { k -> val (wik, wkj) = listOf(W[i, k], W[k, j]) if (wij > wik + wkj) this[i, j] = wik + wkj else wij } } } System.err.println(W.entries) System.err.println(Wmin.entries) val d0 = W.entries.filter { it.w < MaxValue }.count() val d = W.entries.filter { it.w < MaxValue }.filter { Wmin[it.i, it.j] != it.w }.count() System.err.println("d=$d W.count=$d0") println(d) } fun main2() { val (_, M) = readLine()!!.split(" ").map { it.toInt() } val D = (1..M).map { readLine()!!.split(" ").map { it.toInt() } } .map { p -> EdgeWeight(EdgeND(p[0], p[1]), p[2]) } val Dmap = D.associate { it.e to it.w } //System.err.println(Dmap) val Dmin = graphLibFloydWarshall(D) val Dr = Dmin.filter { (e, w) -> Dmap[e] == w } //System.err.println(Dmin) //System.err.println(Dr) //System.err.println(D.size - Dr.size) println(D.size - Dr.size) } stdioEmulatior(envs) { main() } }
16
Kotlin
0
1
2cb2843b2100d96b453ff7d4ced99091e45ed17a
5,773
samples
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[21]合并两个有序链表.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 // // // // 示例 1: // // //输入:l1 = [1,2,4], l2 = [1,3,4] //输出:[1,1,2,3,4,4] // // // 示例 2: // // //输入:l1 = [], l2 = [] //输出:[] // // // 示例 3: // // //输入:l1 = [], l2 = [0] //输出:[0] // // // // // 提示: // // // 两个链表的节点数目范围是 [0, 50] // -100 <= Node.val <= 100 // l1 和 l2 均按 非递减顺序 排列 // // Related Topics 递归 链表 // 👍 1478 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? { //方法一 递归合并 时间复杂度 O(max(n,m)) m n 为两个链表的长度 if (l1 == null){ return l2 }else if (l2 == null){ return l1 }else if(l1.`val` > l2.`val`){ //继续比较l1 和 l2.next 下一位谁大 l2.next = mergeTwoLists(l1,l2.next) return l2 }else{ //l1.`val` < l2.`val` l1.next = mergeTwoLists(l1.next,l2) return l1 } //方法二 迭代 val prehead = ListNode(0) var node1 = l1 var node2 = l2 var prev: ListNode = prehead while (node1 != null && node2 !=null) { if (node1.`val` < node2.`val`){ prev.next = node1 node1 = node1.next }else{ prev.next = node2 node2 = node2.next } prev = prev.next } //找到最后没有比较的那一个数据加入到链表中 //找到最后没有比较的那一个数据加入到链表中 prev.next = if (node1 == null) node2 else node1 return prehead.next } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,165
MyLeetCode
Apache License 2.0
src/main/kotlin/days/Day1.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days class Day1 : Day(1) { override fun partOne(): Any { return calibrationSum(inputList, REGEX_NUMBERS) } override fun partTwo(): Any { return calibrationSum(inputList, REGEX_NUMBER_WORDS) } fun calibrationSum(lines: List<String>, digitRegex: Regex): Int { return lines.sumOf { line -> val values = calibrationValues(line, digitRegex) "${values.first()}${values.last()}".toInt() } } fun calibrationValues(line: String, digitRegex: Regex): List<Int> { val matches = digitRegex.findAllOverlapping(line).map { it.value } return matches.map { digit -> val wordIndex = NUMBER_WORDS.indexOf(digit) if (wordIndex == -1) digit.toInt() else wordIndex + 1 } } private fun Regex.findAllOverlapping(input: CharSequence): List<MatchResult> { val matches = mutableListOf<MatchResult>() var match = this.find(input) while (match != null) { matches.add(match) match = this.find(input, match.range.first + 1) } return matches } companion object { val REGEX_NUMBERS = Regex("\\d") val REGEX_NUMBER_WORDS = Regex("\\d|one|two|three|four|five|six|seven|eight|nine") val NUMBER_WORDS = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
1,407
aoc-2023
Creative Commons Zero v1.0 Universal
12/src/main/kotlin/com/lillicoder/projecteuler/Problem12.kt
lillicoder
33,462,498
false
{"Java": 43120, "Kotlin": 2486}
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this project except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lillicoder.projecteuler import kotlin.math.ceil import kotlin.math.sqrt /** * Project Euler - Problem #12 * * Highly divisible triangular number * * Problem 12 * * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: * * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * * Let us list the factors of the first seven triangle numbers: * * 1: 1 * 3: 1,3 * 6: 1,2,3,6 * 10: 1,2,5,10 * 15: 1,3,5,15 * 21: 1,3,7,21 * 28: 1,2,4,7,14,28 * * We can see that 28 is the first triangle number to have over five divisors. * * What is the value of the first triangle number to have over five hundred divisors? */ fun main() { val divisorCount = 500 val triangleNumber = Problem12().withDivisorCount(divisorCount) println("The triangle number with more than $divisorCount divisors is: $triangleNumber") } class Problem12 { fun withDivisorCount(count: Int): Long { var current = 0L var iteration = 1 var didFind = false while (!didFind) { current = nextTriangleNumber(current, iteration) val divisors = divisors(current) if (divisors.size > count) didFind = true println("[debug] Triangle number: $current, divisorCount: ${divisors.size}, divisors: $divisors") iteration++ } return current } private fun divisors(number: Long): List<Long> { val divisors = mutableListOf(number) val half = number / 2 for (divisor in 1..half) { if (number % divisor == 0.toLong()) divisors.add(divisor) } return divisors } private fun nextTriangleNumber(lastTriangleNumber: Long, iteration: Int): Long { return lastTriangleNumber + iteration; } }
0
Java
0
0
4e181d121d96d8d201c21b49a5183d2cc0afe19a
2,486
projecteuler-java
Apache License 2.0
day13/part2.kts
bmatcuk
726,103,418
false
{"Kotlin": 214659}
// --- Part Two --- // You resume walking through the valley of mirrors and - SMACK! - run directly // into one. Hopefully nobody was watching, because that must have been pretty // embarrassing. // // Upon closer inspection, you discover that every mirror has exactly one // smudge: exactly one . or # should be the opposite type. // // In each pattern, you'll need to locate and fix the smudge that causes a // different reflection line to be valid. (The old reflection line won't // necessarily continue being valid after the smudge is fixed.) // // Here's the above example again: // // #.##..##. // ..#.##.#. // ##......# // ##......# // ..#.##.#. // ..##..##. // #.#.##.#. // // #...##..# // #....#..# // ..##..### // #####.##. // #####.##. // ..##..### // #....#..# // // The first pattern's smudge is in the top-left corner. If the top-left # were // instead ., it would have a different, horizontal line of reflection: // // 1 ..##..##. 1 // 2 ..#.##.#. 2 // 3v##......#v3 // 4^##......#^4 // 5 ..#.##.#. 5 // 6 ..##..##. 6 // 7 #.#.##.#. 7 // // With the smudge in the top-left corner repaired, a new horizontal line of // reflection between rows 3 and 4 now exists. Row 7 has no corresponding // reflected row and can be ignored, but every other row matches exactly: row 1 // matches row 6, row 2 matches row 5, and row 3 matches row 4. // // In the second pattern, the smudge can be fixed by changing the fifth symbol // on row 2 from . to #: // // 1v#...##..#v1 // 2^#...##..#^2 // 3 ..##..### 3 // 4 #####.##. 4 // 5 #####.##. 5 // 6 ..##..### 6 // 7 #....#..# 7 // // Now, the pattern has a different horizontal line of reflection between rows // 1 and 2. // // Summarize your notes as before, but instead use the new different reflection // lines. In this example, the first pattern's new horizontal line has 3 rows // above it and the second pattern's new horizontal line has 1 row above it, // summarizing to the value 400. // // In each pattern, fix the smudge and find the different line of reflection. // What number do you get after summarizing the new reflection line in each // pattern in your notes? import java.io.* fun findMirrorIndex(pattern: List<String>): Int { val len = pattern[0].length var hasSmudge = false outer@ for (i in 1..<pattern.size) { var matched = pattern[i] == pattern[i - 1] if (!matched) { matched = (0..<len).count { pattern[i][it] != pattern[i - 1][it] } == 1 hasSmudge = matched } if (matched) { for ((j, k) in (i-2 downTo 0).zip(i+1..<pattern.size)) { if (pattern[j] != pattern[k]) { if (hasSmudge) { hasSmudge = false continue@outer } if ((0..<len).count { pattern[j][it] != pattern[k][it] } == 1) { hasSmudge = true } } } if (hasSmudge) { return i } } } return 0 } val lines = File("input.txt").readLines() val idxs = lines.mapIndexedNotNull { i, l -> i.takeIf { i == 0 || i == lines.size - 1 || l.isEmpty() } } val result = idxs.zipWithNext().sumOf { (startIdx, endIdx) -> val rows = lines.subList(if (startIdx > 0) startIdx + 1 else startIdx, endIdx) val columns = (0..<rows[0].length).map { i -> rows.map { it[i] }.joinToString("") } findMirrorIndex(columns) + 100 * findMirrorIndex(rows) } println(result)
0
Kotlin
0
0
a01c9000fb4da1a0cd2ea1a225be28ab11849ee7
3,339
adventofcode2023
MIT License
src/main/kotlin/kt/kotlinalgs/app/kickstart/WiggleWalk.ws.kts
sjaindl
384,471,324
false
null
/* https://codingcompetitions.withgoogle.com/kickstart/round/00000000008f49d7/0000000000bcf0fd Banny has just bought a new programmable robot. Eager to test his coding skills, he has placed the robot in a grid of squares with R rows (numbered 1 to R from north to south) and C columns (numbered 1 to C from west to east). The square in row r and column c is denoted (r,c). Initially the robot starts in the square (SR, SC). Banny will give the robot N instructions. Each instruction is one of N, S, E, or W, instructing the robot to move one square north, south, east, or west respectively. If the robot moves into a square that it has been in before, the robot will continue moving in the same direction until it reaches a square that it has not been in before. Banny will never give the robot an instruction that will cause it to move out of the grid. Can you help Banny determine which square the robot will finish in, after following the N instructions? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with a line containing the five integers N, R, C, SR, and SC, the number of instructions, the number of rows, the number of columns, the robot's starting row, and the robot's starting column, respectively. Then, another line follows containing a single string consisting of N characters; the i-th of these characters is the i-th instruction Banny gives the robot (one of N, S, E, or W, as described above). Output For each test case, output one line containing Case #x: r c, where x is the test case number (starting from 1), r is the row the robot finishes in, and c is the column the robot finishes in. Limits Memory limit: 1 GB. 1≤T≤100. 1≤R≤5×104. 1≤C≤5×104. 1≤SR≤R. 1≤SC≤C. The instructions will not cause the robot to move out of the grid. Test Set 1 Time limit: 20 seconds. 1≤N≤100. Test Set 2 Time limit: 60 seconds. 1≤N≤5×104. Sample Sample Input save_alt content_copy 3 5 3 6 2 3 EEWNS 4 3 3 1 1 SESE 11 5 8 3 4 NEESSWWNESE Sample Output save_alt content_copy Case #1: 3 2 Case #2: 3 3 Case #3: 3 7 Sample Case #1 corresponds to the top-left diagram, Sample Case #2 corresponds to the top-right diagram, and Sample Case #3 corresponds to the lower diagram. In each diagram, the yellow square is the square the robot starts in, while the green square is the square the robot finishes in. */ var line = 0 var args: Array<String?> = arrayOf() val deltas = mapOf( //row, col 'N' to (-1 to 0), 'E' to (0 to 1), 'S' to (1 to 0), 'W' to (0 to -1) ) fun readLine(): String? { val result = args[line] line++ return result } data class Cell(val row: Int, val col: Int) // Space: O(N) // Time: O(N), where N = # of instructions // We jump over already visited cells fun main(mainArgs: Array<String?>) { args = mainArgs line = 0 val testCases = readLine()?.toInt() ?: 0 for (testCase in 1 until testCases + 1) { val (numInstructions, rows, columns, startRow, startCol) = readLine()?.split(" ")?.map { it.toInt() } ?: continue val instructions = readLine() ?: continue var curCell = Cell(startRow - 1, startCol - 1) // 0-indexed // mapping each cell to possible jumps (row or col) for given directions N/E/S/W val jumpMap: MutableMap<Cell, MutableMap<Char, Cell>> = mutableMapOf() jumpMap[curCell] = mutableMapOf() println("start at row ${curCell.row + 1} col ${curCell.col + 1}") for (direction in instructions) { val prevCell = curCell var jumpsFromCurCell = jumpMap[curCell] curCell = jump(jumpsFromCurCell, direction, curCell.row, curCell.col) while (jumpMap.contains(curCell)) { jumpsFromCurCell = jumpMap[curCell] curCell = jump(jumpsFromCurCell, direction, curCell.row, curCell.col) } jumpMap[curCell] = mutableMapOf() addJump(jumpMap[curCell]!!, oppositeDirection(direction), prevCell.row, prevCell.col) addJump(jumpMap[Cell(prevCell.row, prevCell.col)]!!, direction, curCell.row, curCell.col) println("jump $direction to row ${curCell.row + 1} col ${curCell.col + 1}") } println("Case #$testCase: ${curCell.row + 1} ${curCell.col + 1}") } } // Either we already know a jump, or we move by 1 fun jump(jumps: MutableMap<Char, Cell>?, direction: Char, row: Int, col: Int): Cell { val delta = deltas[direction] ?: throw IllegalArgumentException("Illegal Instruction") jumps?.get(direction)?.let { return it } return Cell(row + delta.first, col + delta.second) } fun addJump(jumps: MutableMap<Char, Cell>, direction: Char, row: Int, col: Int) { val delta = deltas[direction] ?: throw IllegalArgumentException("Illegal Instruction") jumps[direction] = Cell(row + delta.first, col + delta.second) } fun oppositeDirection(direction: Char): Char { return when (direction) { 'N' -> 'S' 'S' -> 'N' 'E' -> 'W' 'W' -> 'E' else -> throw IllegalArgumentException("Illegal direction given") } } main(arrayOf("3", "5 3 6 2 3", "EEWNS", "4 3 3 1 1", "SESE", "11 5 8 3 4", "NEESSWWNESE")) //main(arrayOf("1", "5 3 6 2 3", "EWEWEW")) // Space: O(N), where N = # of instructions (Optimized from O(RxC) for matrix) // Time: O(N^2) because of possible duplicate moves .. EWEWEWE etc.. fun mainSlow(mainArgs: Array<String?>) { args = mainArgs line = 0 val testCases = readLine()!!.toInt() // println(testCases) for (testCase in 1 until testCases + 1) { val (numInstructions, rows, columns, startRow, startCol) = readLine()!!.split(" ") .map { it.toInt() } val instructions = readLine()!! //println("numInstructions $numInstructions rows $rows columns $columns startRow $startRow startCol $startCol") var curRow = startRow - 1 var curCol = startCol - 1 //val visited = Array(rows) { BooleanArray(columns) } //visited[curRow][curCol] = true val visited: MutableSet<Cell> = hashSetOf() visited.add(Cell(curRow, curCol)) //println(visited) //println(instructions) try { for (instruction in instructions) { //println(instruction) when (instruction) { 'N' -> { // go rows up while (curRow > 0 && visited.contains(Cell(curRow, curCol))) { curRow-- } } 'E' -> { // go cols right while (curCol <= columns && visited.contains(Cell(curRow, curCol))) { curCol++ } } 'S' -> { // go rows down while (curRow < rows - 1 && visited.contains(Cell(curRow, curCol))) { curRow++ } } 'W' -> { // go cols left while (curCol > 0 && visited.contains(Cell(curRow, curCol))) { curCol-- } } } visited.add(Cell(curRow, curCol)) //println("visit $curRow:$curCol") } println("Case #$testCase: ${curRow + 1} ${curCol + 1}") } catch (ex: Exception) { } } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
7,666
KotlinAlgs
MIT License
src/y2015/Day10.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import java.lang.StringBuilder import kotlin.math.min object Day10 { fun part1(input: String): Int { var result = input repeat(40) { result = lookAndSay(result) } return result.length } private fun lookAndSay(string: String): String { val builder = StringBuilder() var idx = 0 while (idx < string.length) { val match = string[idx] // if we take substring without end index this takes forever lol val repeats = string.substring(idx, min(string.length, idx + 3)).takeWhile { it == match }.length builder.append(repeats).append(match) idx += repeats } return builder.toString() } /*private val lookAndSay = DeepRecursiveFunction<String, String> { string -> // heap overflow val match = string.first() if (string.all { it == match }) { string.length.toString() + match } else { string.takeWhile { it == match }.length.toString() + match + callRecursive(string.dropWhile { it == match }) } }*/ fun part2(input: String): Int { var result = input repeat(50) { result = lookAndSay(result) } return result.length } } fun main() { println("------Real------") val input = "1321131112" println(Day10.part1(input)) println(Day10.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,453
advent-of-code
Apache License 2.0
src/main/kotlin/solved/p1418/Solution.kt
mr-nothing
469,475,608
false
{"Kotlin": 162430}
package solved.p1418 class Solution { fun displayTable(orders: List<List<String>>): List<List<String>> { // A tree set of all tables sorted by natural order val tables = sortedSetOf<Int>() // A tree set of all dishes sorted by natural order val dishes = sortedSetOf<String>() // Result map containing unsorted display table (mapOf(table to mapOf(dish to quantity)) val resultMap = mutableMapOf<Int, MutableMap<String, Int>>() for (order in orders) { // Skip person name as we are not interested in it in the final solution // Parse table number val tableNumber = order[1].toInt() // Parse dish name val dishName = order[2] // Add table number to general table set tables.add(tableNumber) // Add dish to general dish set dishes.add(dishName) // Get already created table map info or initialize it with empty map val tableDishes = resultMap.getOrDefault(tableNumber, mutableMapOf()) // Get dish quantity already found for this table or initialize it with zero val dishQuantity = tableDishes.getOrDefault(dishName, 0) // Set dish quantity info and increment it by one tableDishes[dishName] = dishQuantity + 1 // Set table info resultMap[tableNumber] = tableDishes } // Initializing result list of list val result = mutableListOf<MutableList<String>>() // Create header table val header = mutableListOf<String>() // Add "Table" string since it is one of the requirements header.add("Table") for (dish in dishes) { // Add all the dishes' names sorted alphabetically header.add(dish) } // Add header to the result table result.add(header) // Go through all the tables and populate rows corresponding to each table for (table in tables) { // Initialize table row with zeroes at first // dishes.size + 1 is because we have first column populated with table numbers val resultRow = MutableList(dishes.size + 1) { "0" } // Populate table number resultRow[0] = table.toString() // Get all the dishes ordered for this table val tableDishes = resultMap[table]!! for (entry in tableDishes) { // Get "alphabetical" dish index to place it to the right position in the final table val dishIndex = dishes.indexOf(entry.key) + 1 // Populate the quantity of dishes ordered for this table (at corresponding index) resultRow[dishIndex] = entry.value.toString() } // Add populated row to the final table result.add(resultRow) } return result } }
0
Kotlin
0
0
0f7418ecc8675d8361ef31cbc1ee26ea51f7708a
2,941
leetcode
Apache License 2.0
src/Day13.kt
RickShaa
572,623,247
false
{"Kotlin": 34294}
import com.beust.klaxon.Klaxon fun main() { val fileName = "day13.txt" val testFileName = "day13_test.txt" val input = FileUtil.getListOfLines(testFileName); fun Any.isInt():Boolean{ return this is Int } fun Any.isList():Boolean{ return this is List<*> } fun minTupleEndIdx(leftTuple:List<Any>,rightTuple:List<Any>): Int { if(leftTuple.size >= rightTuple.size){ return rightTuple.size-1 } return leftTuple.size -1 } fun compare(left:List<Any>, right:List<Any>):Boolean{ //CASE BOTH LISTS if(left.isEmpty() && right.isNotEmpty()){ return true }else if(left.isNotEmpty() && right.isEmpty()){ return false }else { //iterate through list val max = minTupleEndIdx(left, right) for (x in 0..max) { println("${left[x]} ------ ${right[x]}") if (left[x].isInt() && right[x].isInt()) { val r = right[x] as Int val l = left[x] as Int if (r > l) { return true } else if (r < l) { return false } } else if (left[x].isInt() && right[x].isList()) { val l = left[x] as Int val r = right[x] as List<Any> return compare(listOf(l), r) }else if(left[x].isList() && right[x].isList()){ compare(left[x] as List<Any>, right[x] as List<Any>) } else { val r = right[x] as Int val l = left[x] as List<Any> return compare(l, listOf(r)) } } } return false } val chunkedInput = input.mapNotNull { it.takeIf { s: String -> s.isNotEmpty() } } for(x in chunkedInput.indices step 2){ val left = Klaxon().parseArray<Any>(chunkedInput[x])!! val right = Klaxon().parseArray<Any>(chunkedInput[x+1])!! println(compare(left,right)) } }
0
Kotlin
0
1
76257b971649e656c1be6436f8cb70b80d5c992b
2,263
aoc
Apache License 2.0
kt/001 Two Sum/TwoSum.kt
JiangKlijna
55,755,751
false
null
/** * Given an array of integers, return indices of the two numbers such that they add up to a specific target. * You may assume that each input would have exactly one solution. * 给出一个int数组和目标值,从数组中找到两个值使得其和为目标值.返回两个下标位置. * */ class TwoSum { fun twoSum(numbers: IntArray, target: Int): IntArray { val re = IntArray(2) val map = hashMapOf<Int, Int>() for (i in numbers.indices) { val idx = map[numbers[i]] if (idx == null) {// 如果map中不存在就保存数据 map.put(target - numbers[i], i) } else {// 若存在 即找到了所需要的元素 if (idx < i) { re[0] = idx re[1] = i return re } } } return re } }
0
Java
4
12
65a1348d276ce0a00c8f429c0cba68df0296c541
744
leetcode-learning
MIT License
src/main/kotlin/days/aoc2020/Day17.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2020 import days.Day class Day17: Day(2020, 17) { override fun partOne(): Any { var cube = Cube(inputList) for (i in 0 until 6) { cube.calculateNextState() } return cube.getActiveCount() } override fun partTwo(): Any { var cube = Hypercube(inputList) for (i in 0 until 6) { cube.calculateNextState() } return cube.getActiveCount() } class Cube(input: List<String>) { private var sideLength: Int = 0 private val cube = mutableMapOf<Triple<Int,Int,Int>,Char>() init { sideLength = input.size input.forEachIndexed { yIndex, s -> s.forEachIndexed { xIndex, c -> cube[Triple(xIndex - (sideLength / 2), yIndex - (sideLength / 2), 0)] = c } } } private fun neighbors(point: Triple<Int,Int,Int>) = sequence { for (x in point.first-1..point.first+1) for (y in point.second-1..point.second+1) for (z in point.third-1..point.third+1) if (!(point.first == x && point.second == y && point.third == z)) { yield(Triple(x, y, z)) } } fun getActiveCount(): Int { return cube.values.count { it == '#'} } fun calculateNextState() { // expand it sideLength += 2 val currentCube = mutableMapOf<Triple<Int,Int,Int>,Char>() currentCube.putAll(cube) for (x in (sideLength / 2).unaryMinus()..(sideLength / 2)) for (y in (sideLength / 2).unaryMinus()..(sideLength / 2)) for (z in (sideLength / 2).unaryMinus()..(sideLength / 2)) { val point = Triple(x,y,z) val activeNeighbors = neighbors(point).map { currentCube[it] }.count { it == '#' } if ((currentCube[point] ?: '.') == '#') { if(activeNeighbors !in 2..3) { cube[point] = '.' } else { cube[point] = '#' } } else if ((currentCube[point] ?: '.') == '.' && activeNeighbors == 3) { cube[point] = '#' } else { cube[point] = '.' } } } } class Hypercube(input: List<String>) { private var sideLength: Int = 0 private val cube = mutableMapOf<Quad,Char>() init { sideLength = input.size input.forEachIndexed { yIndex, s -> s.forEachIndexed { xIndex, c -> cube[Quad(xIndex - (sideLength / 2), yIndex - (sideLength / 2), 0, 0)] = c } } } private fun neighbors(point: Quad) = sequence { for (x in point.first-1..point.first+1) for (y in point.second-1..point.second+1) for (z in point.third-1..point.third+1) for (w in point.fourth-1..point.fourth+1) if (!(point.first == x && point.second == y && point.third == z && point.fourth == w)) { yield(Quad(x, y, z, w)) } } fun getActiveCount(): Int { return cube.values.count { it == '#'} } fun calculateNextState() { // expand it sideLength += 2 val currentCube = mutableMapOf<Quad,Char>() currentCube.putAll(cube) for (x in (sideLength / 2).unaryMinus()..(sideLength / 2)) for (y in (sideLength / 2).unaryMinus()..(sideLength / 2)) for (z in (sideLength / 2).unaryMinus()..(sideLength / 2)) for (w in (sideLength / 2).unaryMinus()..(sideLength / 2)) { val point = Quad(x,y,z,w) val activeNeighbors = neighbors(point).map { currentCube[it] }.count { it == '#' } if ((currentCube[point] ?: '.') == '#') { if(activeNeighbors !in 2..3) { cube[point] = '.' } else { cube[point] = '#' } } else if ((currentCube[point] ?: '.') == '.' && activeNeighbors == 3) { cube[point] = '#' } else { cube[point] = '.' } } } } } data class Quad(val first: Int, val second:Int, val third:Int, val fourth: Int)
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
5,078
Advent-Of-Code
Creative Commons Zero v1.0 Universal
app/src/main/java/com/mospolytech/mospolyhelper/domain/schedule/utils/LessonUtils.kt
tonykolomeytsev
341,524,793
true
{"Kotlin": 646693}
package com.mospolytech.mospolyhelper.domain.schedule.utils import com.mospolytech.mospolyhelper.domain.schedule.model.Lesson private const val minCriticalTitleLength = 10 private const val minCriticalWordLength = 5 private const val vowels = "аеёиоуыэюя" fun cutTitle(title: String): String { if (title.length <= minCriticalTitleLength) { return title } val words = title.split(' ').filter { it.isNotEmpty() } if (words.size == 1) { return words.first() } return words.joinToString(" ") { cutWord(it) } } private fun cutWord(word: String): String { if (word.length <= minCriticalWordLength) { return word } val vowelIndex = word.indexOfFirst { vowels.contains(it, ignoreCase = true) } if (vowelIndex == -1) { return word } for (i in vowelIndex + 1 until word.length) { if (vowels.contains(word[i], ignoreCase = true)) { // if two vowels are near if (i == vowelIndex + 1) { continue } return word.substring(0, i) + '.' } } return word } fun abbreviationFrom(title: String): String { val words = title.split(' ').filter { it.isNotEmpty() } if (words.size == 1) { return cutWord(words.first()) } val cutWords = words.map { it.first().toUpperCase() } return cutWords.joinToString("") } fun getShortType(type: String): String { return type.split(' ').filter { it.isNotEmpty() }.joinToString(" ") { cutWord(it) } } fun Lesson.canMergeByDate(other: Lesson): Boolean { return order == other.order && title == other.title && type == other.type && teachers == other.teachers && auditoriums == other.auditoriums && groups == other.groups && (other.dateFrom in dateFrom..dateTo || dateFrom in other.dateFrom..other.dateTo) } fun Lesson.mergeByDate(other: Lesson): Lesson { val minDate = if (dateFrom < other.dateFrom) dateFrom else other.dateFrom val maxDate = if (dateTo > other.dateTo) dateTo else other.dateTo return copy(dateFrom = minDate, dateTo = maxDate) } fun Lesson.canMergeByGroup(other: Lesson): Boolean { return order == other.order && title == other.title && auditoriums == other.auditoriums && teachers == other.teachers && dateFrom == other.dateFrom && dateTo == other.dateTo } fun Lesson.mergeByGroup(other: Lesson): Lesson { return copy(groups = (groups + other.groups).sortedBy { it.title }) }
0
null
0
0
379c9bb22913da1854f536bf33e348a459db48b9
2,593
mospolyhelper-android
MIT License
src/main/kotlin/Day06.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { fun calculate(input: String, chunkSize: Int): Int { val data = input.toCharArray().toList() var start = 0 var to = chunkSize while (to <= data.size) { val chunk = data.subList(start, to) var index = 0 while (index <= chunk.size) { if (index == chunk.size - 1) { return to } else if (chunk.count { it == chunk[index] } > 1) { start += index + 1 to += index + 1 break } index++ } } return -1 } fun part1(input: String): Int = calculate(input, 4) fun part2(input: String): Int = calculate(input, 14) // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test").first() println(part1(testInput)) check(part1(testInput) == 5) println(part2(testInput)) val input = readInput("Day06").first() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
1,087
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SingleElementInSortedArray.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 /** * 540. Single Element in a Sorted Array * @see <a href="https://leetcode.com/problems/single-element-in-a-sorted-array/">Source</a> */ fun interface SingleElementInSortedArray { fun singleNonDuplicate(nums: IntArray): Int } class SingleElementInSortedArrayBS : SingleElementInSortedArray { override fun singleNonDuplicate(nums: IntArray): Int { var left = 0 var right = nums.size - 1 while (left < right) { var mid = left.plus(right).div(2) if (mid % 2 == 1) { mid-- } if (nums[mid] != nums[mid + 1]) { right = mid } else { left = mid + 2 } } return nums[left] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,387
kotlab
Apache License 2.0
src/chapter5/section1/ex12_Alphabet_LSD.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section1 /** * 字母表 * 实现5.0.2节给出的Alphabet类的API并用它实现能够处理任意字母表的低位优先的和高位优先的字符串排序算法。 * * 解:基于字母表的低位优先字符串排序算法,参考练习5.1.9 */ fun alphabetLSDSort(array: Array<String>, alphabet: Alphabet) { var maxLength = 0 array.forEach { if (it.length > maxLength) maxLength = it.length } val aux = Array(array.size) { "" } for (d in maxLength - 1 downTo 0) { val count = IntArray(alphabet.R() + 2) array.forEach { count[lsdCharAt(it, alphabet, d) + 2]++ } for (i in 1 until count.size) { count[i] += count[i - 1] } array.forEach { val index = lsdCharAt(it, alphabet, d) + 1 aux[count[index]] = it count[index]++ } for (i in array.indices) { array[i] = aux[i] } } } private fun lsdCharAt(string: String, alphabet: Alphabet, d: Int): Int { return if (d >= string.length) { -1 // 右侧空白字符 } else { alphabet.toIndex(string[d]) // 非空白字符 } } fun main() { val msdData = getMSDData() alphabetLSDSort(msdData, Alphabet.EXTENDED_ASCII) println(msdData.joinToString(separator = "\n")) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,353
Algorithms-4th-Edition-in-Kotlin
MIT License
Collections/Sort/src/TaskExtensionSort.kt
Rosietesting
373,564,502
false
{"HTML": 178715, "JavaScript": 147056, "Kotlin": 113135, "CSS": 105840}
fun main(){ //Natural order val numbers = listOf("one", "two", "three") println("Sorted descending: ${numbers.sortedDescending()}") println("Sorted ascending: ${numbers.sorted()}") //Custom orders val numbers2 = listOf("one", "two", "three", "Four") val sortedNumbers = numbers2.sortedBy { it.length } println("Sorted by length ascending: $sortedNumbers") val sortedByLast = numbers2.sortedByDescending { it.last() } println("Sorted by the last letter descending: $sortedByLast") val numbers3 = listOf("one", "two", "three", "four") println("random order" + numbers3.shuffled()) val city1 = City ("Bogota") val city2 = City ("London") val product1 = Product("Bread", 10.50) val product2 = Product("Rice", 4.23) val product3 = Product("potatoes", 1.23) val product4 = Product("brocoli", 12.60) val order1 = Order(listOf(product1,product3, product4), true) val order2 = Order(listOf(product2), true) val order3 = Order(listOf(product1, product2), true) val order4 = Order(listOf(product3, product4), true) val customer1 = Customer("<NAME>", city1, listOf(order1, order2, order3)) val customer2 = Customer("<NAME>", city2, listOf(order1)) val customer3 = Customer("Santi", city2, listOf(order1, order4)) val shop = Shop("Roxipan", listOf(customer2,customer3, customer1)) val customerListNoOrder = shop.getCustomer() println("Ordering the Shop") println("No order" + customerListNoOrder) val customerListOrdererd= shop.getCustomersSortedByOrdersExtension() println("Ordered" + customerListOrdererd) } fun Shop.getCustomersSortedByOrdersExtension(): List<Customer> { return this.customers.sortedByDescending { it.orders.size } } fun Shop.getCustomer(): List<Customer> { return this.customers }
0
HTML
0
0
b0aa518d220bb43c9398dacc8a6d9b6c602912d5
1,836
KotlinKoans
MIT License
kotlin/src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day25Test.kt
dirkgroot
724,049,902
false
{"Kotlin": 203339, "Rust": 123129, "Clojure": 78288}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import kotlin.math.pow private fun solution1(input: String) = input.lines().sumOf { it.snafuToLong() }.toSNAFU() private fun String.snafuToLong() = reversed().map { when (it) { '=' -> -2 '-' -> -1 else -> it.digitToInt().toLong() } }.foldIndexed(0L) { pw, acc, digit -> acc + digit * 5.0.pow(pw).toLong() } private fun Long.toSNAFU(): String { if (this == 0L) return "" val mod = this % 5 val (carry, n) = if (mod > 2) 1 to mod - 5L else 0 to mod val digit = when (n) { -2L -> "=" -1L -> "-" else -> n.toString() } return (this / 5 + carry).toSNAFU() + digit } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 25 class Day25Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe "2=-1=0" } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe "2--2-0=--0--100-=210" } }) private val exampleInput = """ 1=-0-2 12111 2=0= 21 2=01 111 20012 112 1=-1= 1-12 12 1= 122 """.trimIndent()
1
Kotlin
0
0
ced913cd74378a856813973a45dd10fdd3570011
1,497
adventofcode
MIT License
mynlp/src/main/java/com/mayabot/nlp/module/nwd/ValueObjects.kt
mayabot
113,726,044
false
{"Java": 985672, "Kotlin": 575923, "Shell": 530}
package com.mayabot.nlp.module.nwd import kotlin.math.* class IntCount { var value : Int = 1 } /** * 词和词数量 */ class WordCount(val word: String, val count: Int) : Comparable<WordCount> { override fun compareTo(other: WordCount): Int { return other.count.compareTo(count) } } data class NewWord( val word: String, val len: Int, val freq: Int, val docFreq: Int, /** * 互信息。内聚程度 */ val mi: Float, val avg_mi: Float, /** * 左右最低熵.和两侧的黏连程度 */ val entropy: Float, val le: Float, val re: Float, val idf: Float, val isBlock: Boolean ) { var score: Float = 0f /** * 内置打分公式 */ fun doScore() { var ac = abs(le - re) if (ac == 0.0f) { ac = 0.00000000001f } score = avg_mi + log2((le * exp(re) + re * exp(le)) / ac) // score = avg_mi + entropy + idf * 1.5f + len * freq / docFreq if (isBlock) score += 1000 } } fun HashMap<Char, IntCount>.addTo(key: Char, count: Int) { this.getOrPut(key) { IntCount() }.value += count } class WordInfo(val word: String) { companion object { val empty = HashMap<Char, IntCount>() val emptySet = HashSet<Int>() } var count = 0 var mi = 0f var mi_avg = 0f // 是否被双引号 书名号包围 var isBlock = false var entropy = 0f var left = HashMap<Char, IntCount>(10) var right = HashMap<Char, IntCount>(10) var docSet = HashSet<Int>() var score = 0f var idf = 0f var doc = 0 var le = 0f var re = 0f // var tfIdf =0f fun tfIdf(docCount: Double, ziCount: Double) { val doc = docSet.size + 1 idf = log10(docCount / doc).toFloat() // tfIdf = (idf * (count/ziCount)).toFloat() docSet = emptySet this.doc = doc - 1 } fun entropy() { var leftEntropy = 0f for (entry in left) { val p = entry.value.value / count.toFloat() leftEntropy -= (p * ln(p.toDouble())).toFloat() } var rightEntropy = 0f for (entry in right) { val p = entry.value.value / count.toFloat() rightEntropy -= (p * ln(p.toDouble())).toFloat() } le = leftEntropy re = rightEntropy entropy = min(leftEntropy, rightEntropy) left = empty right = empty } }
18
Java
90
658
b980da3a6f9cdcb83e0800f6cab50656df94a22a
2,489
mynlp
Apache License 2.0
src/Day17.kt
jbotuck
573,028,687
false
{"Kotlin": 42401}
import kotlin.math.max fun main() { @Suppress("unused") fun board17() = TetrisBoard(readInput("Day17").first()) @Suppress("unused") fun boardSample() = TetrisBoard(">>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>") fun board() = board17() //change to use sample val shapesToPlay = 1_000_000_000_000 //change for part 1 //find the cycle val boardFast = board() val boardSlow = board() do { boardFast.play(2) boardSlow.play(1) } while (!boardFast.hasSameNormalizedStateAs(boardSlow)) //evaluate the cycle val heightDiff = boardFast.height() - boardSlow.height() val shapesDiff = boardFast.differenceInShapesLanded(boardSlow) //use the cycle and the remainder to calculate the result board() .apply { play(shapesToPlay % shapesDiff) } .height() .plus(shapesToPlay / shapesDiff * heightDiff) .let { println(it) } } private data class Shape(val points: Set<Pair<Int, Long>>) { fun addY(y: Long) = Shape(points.map { it.first to it.second.plus(y) }.toSet()) fun maxHeight() = points.maxOf { it.second } fun addX(x: Int) = Shape(points.map { it.first.plus(x) to it.second }.toSet()) } private val shapeBlueprints = listOf( Shape((2..5).map { it to 0L }.toSet()), Shape(setOf(3 to 2L, 3 to 0L) + (2..4).map { it to 1L }), Shape((2..4).map { it to 0L }.toSet() + setOf(4 to 1, 4 to 2)), Shape((0L..3L).map { 2 to it }.toSet()), Shape((2..3).flatMap { x -> (0L..1L).map { y -> x to y } }.toSet()) ) private class TetrisBoard(val input: String) { private var nextInputIndex = 0 private var rocks = mutableSetOf<Pair<Int, Long>>() private var shapesLanded = 0L private var indexOfHighestStone = -1L private var offset = 0L private var shape = generateShape() fun height() = offset + indexOfHighestStone.inc() private fun generateShape() = shapeBlueprints[nextShapeIndex()] .addY(indexOfHighestStone + 4) private fun nextShapeIndex() = (shapesLanded % shapeBlueprints.size).toInt() fun play(numberOfAdditionalShapesToPlay: Long = 2022) { val numberOfShapesToPlay = shapesLanded + numberOfAdditionalShapesToPlay while (shapesLanded < numberOfShapesToPlay) { playUntilLanding() } } private fun playUntilLanding() { while (true) { applyInput(input[nextInputIndex++]) if (nextInputIndex == input.length) nextInputIndex = 0 if (!moveDown()) break } setInStone(shape) shape = generateShape() } private fun moveDown() = shape.addY(-1).takeIf { it.isValid() }?.also { shape = it }?.let { true } ?: false private fun applyInput(next: Char) = shape .addX(if (next == '>') 1 else -1) .takeIf { it.isValid() } ?.let { shape = it } private fun setInStone(shape: Shape) { rocks.addAll(shape.points) indexOfHighestStone = max(indexOfHighestStone, shape.maxHeight()) shapesLanded++ normalize() } private fun normalize() { val unreachableRows = unreachableRows() if (unreachableRows > 0) { offset += unreachableRows indexOfHighestStone -= unreachableRows rocks = rocks.map { it.first to it.second.minus(unreachableRows) }.filter { it.second >= 0 }.toMutableSet() } } private fun unreachableRows(): Long { val toVisit = ArrayDeque<Pair<Int, Long>>().apply { addLast(0 to indexOfHighestStone.inc()) } val visited = mutableSetOf<Pair<Int, Long>>() while (toVisit.isNotEmpty()) { val visiting = toVisit.removeFirst() visiting .neighbors() .asSequence() .filter { it !in visited } .filter { it !in rocks } .filter { it.first >= 0 && it.second >= 0L } .filter { it.first <= 6 } .filter { it.second <= indexOfHighestStone.inc() } .let { toVisit.addAll(it) } visited.add(visiting) } return visited.minOf { it.second } } private fun Shape.isValid(): Boolean { return points.all { it.first in 0..6 && it.second >= 0 && it !in rocks } } fun hasSameNormalizedStateAs(other: TetrisBoard) = rocks == other.rocks && nextInputIndex == other.nextInputIndex && shapesLanded % shapeBlueprints.size == other.shapesLanded % shapeBlueprints.size fun differenceInShapesLanded(other: TetrisBoard): Long { return shapesLanded - other.shapesLanded } } private fun Pair<Int, Long>.neighbors() = listOf(first to second.inc(), first to second.dec(), first.inc() to second, first.dec() to second)
0
Kotlin
0
0
d5adefbcc04f37950143f384ff0efcd0bbb0d051
4,813
aoc2022
Apache License 2.0
src/main/kotlin/no/quist/aoc18/days/Day2.kt
haakonmt
159,945,133
false
null
package no.quist.aoc18.days import no.quist.aoc18.Day object Day2 : Day<List<String>, Any>() { override fun createInput(): List<String> = inputLines override fun part1(input: List<String>): Int { val (twos, threes) = input.fold(Pair(0, 0)) { (accTwos, accThrees), currentLine -> val charCount = currentLine.map { c -> currentLine.count { it == c } } Pair( accTwos + if (charCount.contains(2)) 1 else 0, accThrees + if (charCount.contains(3)) 1 else 0 ) } return twos * threes } override fun part2(input: List<String>): String { input.forEach { first -> input.forEach { second -> val (diffCount, commonChars) = first.foldIndexed(Pair(0, "")) { i, (accDiff, accCommon), c -> if (c != second[i]) Pair(accDiff + 1, accCommon) // Increment diff counter else Pair(accDiff, accCommon + c) // Add to common chars } if (diffCount == 1) { return commonChars } } } return "NO RESULT" } }
0
Kotlin
0
1
4591ae7aa9cbb70e26ae2c3a65ec9e55559c2690
1,166
aoc18
MIT License
src/Day11/Day11.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day11 import readInput import java.math.BigInteger class Item(var worry: BigInteger) class Monkey(val id: Int, var items: MutableList<Item>, val operation: (BigInteger) -> BigInteger, val test: (BigInteger) -> Boolean, val divisor: BigInteger) { var testFalseMoney: Monkey? = null var testTrueMonkey: Monkey? = null var inspections: BigInteger = BigInteger.ZERO var divisors = listOf<BigInteger>() fun addTestMonkeys(falseMonkey: Monkey, trueMonkey: Monkey) { testFalseMoney = falseMonkey testTrueMonkey = trueMonkey } fun addItem(item: Item) { items.add(item) } fun takeTurn(divideByThree: Boolean) { for (item in items) { inspections++ item.worry = operation(item.worry) if(divideByThree) { item.worry /= BigInteger.valueOf(3) } item.worry %= divisors.reduce { x, y -> x * y } if (test(item.worry)) { testTrueMonkey!!.addItem(item) } else { testFalseMoney!!.addItem(item) } } items = mutableListOf() // I'm sure I won't regret this } } class MonkeyKeepAway(val divideByThree: Boolean) { var monkeys = mutableListOf<Monkey>() fun processInput(input: List<String>) { val monkeyStrings = input .withIndex() .groupBy { it.index / 7 } .map { it.value.map { it.value }.dropLast(1) } for(monkeyString in monkeyStrings) { processMonkeyStrings(monkeyString) } for(monkeyString in monkeyStrings) { hookUpMonkeyStrings(monkeyString) } } fun runRounds(roundCount: Int) { for (i in 0 until roundCount) { for (monkey in monkeys) { monkey.takeTurn(divideByThree) } } } fun hookUpMonkeyStrings(monkeyStrings: List<String>) { val monkeyString = monkeyStrings[0].trim() val monkeyIndex = monkeyString.split(" ").last().dropLast(1).toInt() val trueMonkeyString = monkeyStrings[4].trim() val falseMonkeyString = monkeyStrings[5].trim() val trueMonkeyIndex = trueMonkeyString.split(" ").last().toInt() val falseMonkeyIndex = falseMonkeyString.split(" ").last().toInt() monkeys[monkeyIndex].addTestMonkeys(monkeys[falseMonkeyIndex], monkeys[trueMonkeyIndex]) monkeys[monkeyIndex].divisors = monkeys.map { it.divisor } } fun processMonkeyStrings(monkeyStrings: List<String>) { val monkeyString = monkeyStrings[0].trim() val itemsString = monkeyStrings[1].trim() val operationString = monkeyStrings[2].trim() val testString = monkeyStrings[3].trim() val monkeyIndex = monkeyString.split(" ").last().dropLast(1).toInt() val items = itemsString.split(" ").drop(2) .map { it.removeSuffix(",").toBigInteger() } .map { Item(it) } .toMutableList() val operation = operationString.split(" ").reversed()[1] val operandString = operationString.split(" ").last() val operationFunction: (BigInteger) -> BigInteger = { val operand = if (operandString == "old") it else operandString.toBigInteger() when(operation) { "*" -> it * operand "+" -> it + operand else -> it } } val testDivisor = testString.split(" ").last().toBigInteger() val testFunction: (BigInteger) -> Boolean = { it % testDivisor == BigInteger.ZERO } val newMonkey = Monkey(monkeyIndex, items, operationFunction, testFunction, testDivisor) monkeys.add(newMonkey) } } fun main() { fun part1(input: List<String>): BigInteger { val keepAway = MonkeyKeepAway(true) keepAway.processInput(input) keepAway.runRounds(20) val sortedMonkeys = keepAway.monkeys.sortedByDescending { it.inspections } return sortedMonkeys[0].inspections * sortedMonkeys[1].inspections } fun part2(input: List<String>): BigInteger { val keepAway = MonkeyKeepAway(false) keepAway.processInput(input) keepAway.runRounds(10000) val sortedMonkeys = keepAway.monkeys.sortedByDescending { it.inspections } return sortedMonkeys[0].inspections * sortedMonkeys[1].inspections } val testInput = readInput("Day11","Day11_test") // println(part1(testInput)) // check(part1(testInput) == BigInteger.valueOf(10605)) println(part2(testInput)) // check(part2(testInput) == BigInteger.valueOf(2713310158)) val input = readInput("Day11","Day11") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
4,780
advent-of-code-2022
Apache License 2.0
src/test/resources/scripts/clusterer.kts
xrrocha
264,292,094
false
null
// DEPS info.debatty:java-string-similarity:2.0.0 import grappolo.ClusteringResult import info.debatty.java.stringsimilarity.Damerau import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentSetOf import java.io.File import java.time.LocalDateTime import java.time.format.DateTimeFormatter import kotlin.math.max fun Double.fmt(digits: Int = 3) = "%.${digits}f".format(this) fun log(message: String) { println("${DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now())}: $message") } val baseDirectory = File("./build/results").also { it.mkdirs() } val separator = "\\s+".toRegex() val values = """ <NAME> alexandro <NAME> <NAME> <NAME> ricardo """ .split(separator) .filterNot(String::isEmpty) .sorted() val similarityThreshold = 0.5 val levenshteinDamerau = Damerau() fun measureSimilarity(first: String, second: String): Double = 1.0 - (levenshteinDamerau.distance(first, second) / max(first.length, second.length)) log("Starting clustering. Values: ${values.size}. Similarity threshold: $similarityThreshold") val similarities = mutableSetOf<Double>() val emptyMap = mutableMapOf<Int, Double>().withDefault { 0.0 } val matrix = mutableMapOf<Int, MutableMap<Int, Double>>().withDefault { emptyMap } values.indices.forEach { i -> matrix[i] = mutableMapOf(i to 1.0).withDefault { 0.0 } } log("Creating similarity matrix") for (i in values.indices) { for (j in i + 1 until values.size) { // n*(n + 1) / 2 val similarity = measureSimilarity(values[i], values[j]) if (similarity >= similarityThreshold) { matrix[i]!![j] = similarity matrix[j]!![i] = similarity similarities += similarity } } } log("Created similarity matrix with ${matrix.values.map { it.size }.sum()} elements") File(baseDirectory, "matrix.tsv").printWriter().use { out -> out.println("\t${values.joinToString("\t") { it }}") values.indices.forEach { i -> out.print(values[i]) values.indices.forEach { j -> out.print("\t${matrix[i]!![j]?:0.0.fmt(4)}") } out.println() } } fun intraSimilarity(cluster: List<Int>): Double = if (cluster.size == 1) { 0.0 } else { cluster.indices .flatMap { i -> cluster.indices .filter { j -> i != j } .map { j -> matrix[cluster[i]]!![cluster[j]] ?: 0.0 } } .average() } fun Map<Int, Map<Int, Double>>.extractCluster(elementIndex: Int, minSimilarity: Double): Set<Int> { fun Map<Int, Double>.siblingsAbove(minSimilarity: Double): Set<Int> = this.filterValues { it >= minSimilarity }.keys val siblingsByElementIndex: Map<Int, Set<Int>> = this[elementIndex]!! .siblingsAbove(minSimilarity) .flatMap { siblingIndex -> this[siblingIndex]!! .siblingsAbove(minSimilarity) .map { cousinIndex -> siblingIndex to cousinIndex } } .groupBy { it.first } .mapValues { entry -> entry.value.map { it.second }.toSet() } .filter { entry -> entry.value.contains(elementIndex) } if (siblingsByElementIndex.isEmpty()) { return setOf(elementIndex) } val maxSiblingCount: Int = siblingsByElementIndex.values.map { it.size }.max()!! val maxIntraSimilarity = siblingsByElementIndex .filter { entry -> entry.value.size == maxSiblingCount } .map { entry -> intraSimilarity(entry.value.toList()) } .max()!! val bestIndex = siblingsByElementIndex .toList() .find { (_, cluster) -> cluster.size == maxSiblingCount && intraSimilarity(cluster.toList()) == maxIntraSimilarity } ?.first ?: return setOf(elementIndex) return siblingsByElementIndex[bestIndex]!! } fun evaluateClustering(clusters: List<List<Int>>): Double = clusters.map(::intraSimilarity).average() data class Result(val minSimilarity: Double, val evaluation: Double, val clusters: List<List<Int>>) log("Building clusters for ${similarities.size} similarities") val bestResult = File(baseDirectory, "results.tsv").printWriter(Charsets.UTF_8).use { out -> similarities .sorted() .fold(ClusteringResult(0.0, 0.0, emptyList())) { bestResultSoFar, minSimilarity -> log("Processing minimum similarity: $minSimilarity") val (clusters, _) = matrix.keys .map { elementIndex -> matrix.extractCluster(elementIndex, minSimilarity).sorted() } .distinct() .sortedWith(Comparator { cluster1, cluster2 -> if (cluster2.size != cluster1.size) { cluster2.size - cluster1.size } else { fun weight(cluster: List<Int>): Double = cluster.indices.flatMap { i -> (i + 1 until cluster.size) .map { j -> matrix[cluster[i]]!![cluster[j]] ?: 0.0 } } .sum() (weight(cluster2) - weight(cluster1)).toInt() } }) .fold(Pair(persistentListOf<List<Int>>(), persistentSetOf<Int>())) { accumSoFar, cluster -> val (clustersSoFar, clusteredSoFar) = accumSoFar if (cluster.none(clusteredSoFar::contains)) { Pair(clustersSoFar.add(cluster), clusteredSoFar.addAll(cluster)) } else { accumSoFar } } val evaluation = evaluateClustering(clusters) out.println("${minSimilarity.fmt(4)}\t${evaluation.fmt(4)}\t${clusters.size}") val clusterBasename = "clusters-${minSimilarity.fmt(2)}" File(baseDirectory, "$clusterBasename.dot").printWriter(Charsets.UTF_8).use { dotOut -> dotOut.println("graph {") for (i in values.indices) { dotOut.println(" \"${values[i]}\";") } clusters.forEach { cluster -> for (i in cluster.indices) { for (j in i + 1 until cluster.size) { val leftIndex = cluster[i] val rightIndex = cluster[j] val similarity = (matrix[leftIndex]!![rightIndex] ?: 0.0).fmt(3) dotOut.println(" \"${values[leftIndex]}\" -- \"${values[rightIndex]}\" [label=\"$similarity\", weight = \"$similarity\"];") } } } dotOut.println("}") val errorFile = File(baseDirectory, "$clusterBasename.err") val exitCode = ProcessBuilder() .directory(baseDirectory) .command("dot", "-Tpng", "$clusterBasename.dot", "-o", "$clusterBasename.png") .redirectError(errorFile) .start() .waitFor() if (exitCode != 0) { log("Exit code: $exitCode") } if (exitCode != 0) { log("Exit code: $exitCode") } if (errorFile.length() > 0L) { log("Error generating cluster graph: ${errorFile.readText()}") } else { errorFile.delete() File(baseDirectory, "$clusterBasename.dot").delete() } } val currentResult = ClusteringResult(minSimilarity, evaluation, clusters) log("Results for similarity ${minSimilarity.fmt(2)}. Evaluation = ${evaluation.fmt(2)}. Clusters: ${clusters.size}") if (evaluation > bestResultSoFar.evaluation) { currentResult } else { bestResultSoFar } } } log("${bestResult.clusters.size} clusters created") log("Result. minSimilarity: ${bestResult.minSimilarity}, evaluation: ${bestResult.evaluation}, clusters: ${bestResult.clusters.size}") File(baseDirectory, "clusters.tsv").printWriter().use { out -> bestResult.clusters.forEach { cluster -> out.println("${cluster.size}\t${cluster.joinToString(",") { values[it] }}") } } log("End of source deck")
0
Kotlin
0
0
93a065ab98d5551bc2f2e39ff4b069d524e04870
10,722
grappolo-kotlin
Apache License 2.0
src/commonMain/kotlin/ai/hypergraph/kaliningraph/parsing/SortValiant.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
@file:Suppress("NonAsciiCharacters") package ai.hypergraph.kaliningraph.parsing import ai.hypergraph.kaliningraph.* import ai.hypergraph.kaliningraph.tensor.UTMatrix import ai.hypergraph.kaliningraph.types.* // The main issue with SortValiant is we eagerly compute the Cartesian product // and this blows up very quickly, so we need to sort and prune aggressively. // We can instead use a lazy Cartesian product, which is what SeqValiant does. // The downside is that we lose the ability to sort the results while parsing, // but we can still use a metric to sort the results after the fact. // Returns all syntactically strings ordered by distance to withRespect fun CFG.solve(s: Σᐩ, metric: ChoiceMetric): Set<Σᐩ> = solve(s.tokenizeByWhitespace(), metric) fun CFG.solve(s: List<Σᐩ>, metric: ChoiceMetric): Set<Σᐩ> = try { solveSortedFP(s, metric)?.sorted()?.map { it.asString }?.toSet() } catch (e: Exception) { e.printStackTrace(); null } ?: setOf() fun CFG.solveSortedFP( tokens: List<Σᐩ>, metric: ChoiceMetric, utMatrix: UTMatrix<Sort> = initialUTSMatrix(tokens, sortwiseAlgebra(metric)), ) = utMatrix.seekFixpoint().toFullMatrix()[0].last()[START_SYMBOL] fun CFG.initialUTSMatrix( tokens: List<Σᐩ>, algebra: Ring<Sort> ): UTMatrix<Sort> = UTMatrix( ts = tokens.map { token -> (if (token != HOLE_MARKER) bimap[listOf(token)] else unitNonterminals) .associateWith { nt -> if (token != HOLE_MARKER) setOf(Choice(token)) else bimap.UNITS[nt]?.map { Choice(it) }?.toSet() ?: setOf() } }.toTypedArray(), algebra = algebra ) // Maintains a sorted list of nonterminal roots and their leaves fun CFG.sortwiseAlgebra(metric: ChoiceMetric): Ring<Sort> = Ring.of( nil = mapOf(), plus = { x, y -> union(x, y) }, times = { x, y -> join(x, y, metric) }, ) var MAX_SORT_CAPACITY = 50 // X ⊗ Z := { w | <x, z> ∈ X × Z, (w -> xz) ∈ P } // Greedily selects candidate string fragments according to ChoiceMetric fun CFG.join(X: Sort, Z: Sort, metric: ChoiceMetric = { it.weight }): Sort = bimap.TRIPL.filter { (_, x, z) -> x in X && z in Z } .map { (w, x, z) -> // This Cartesian product becomes expensive quickly so MAX_CAPACITY is used // to limit the number of elements in the product. This is a greedy approach // and we always take the top MAX_CAPACITY-elements by the provided metric. ((X[x] ?: setOf()) * (Z[z] ?: setOf())) .map { (q, r) -> w to (q + r) } }.flatten().groupingBy { it.first } .aggregate<Pair<Σᐩ, Choice>, Σᐩ, MutableList<Choice>> { _, acc, it, _ -> val choice = Choice(it.second.tokens, metric(it.second)) val list = acc ?: mutableListOf() val idx = list.binarySearch(choice, Choice.comparator) if (idx < 0) list.add(-idx - 1, choice) // Only if not already present list.apply { if (MAX_SORT_CAPACITY < size) removeLast() } }.mapValues { it.value.toSet() } fun union(l: Sort, r: Sort): Sort = (l.keys + r.keys).associateWith { k -> (l[k] ?: setOf()) + (r[k] ?: setOf()) } // Map of root to the possible sets of token sequences it can produce in context // This is identical to a forest minus internal branches, just roots and leaves // Each root represents many strings, we only care about unique leaf sequences // Maintains a sort ordering based on some metric of the most likely derivations typealias Sort = Map<Σᐩ, Set<Choice>> typealias ChoiceMetric = (Choice) -> Float // Substring and some metric (e.g., number of blanks) // TODO: Associate a more concrete semantics with second value, // but for now just the number of terminals. For example, // we could use perplexity of a Markov chain or the length // of the longest common substring with the original string. data class Choice(val tokens: List<Σᐩ>, val weight: Float): Comparable<Choice> { constructor(token: Σᐩ): this(listOf(token), if ("ε" in token) 0f else 1f) companion object { val comparator: Comparator<Choice> = compareBy<Choice> { it.weight } .thenBy { it.sanitized.size }.thenBy { it.asString } } override fun compareTo(other: Choice): Int = comparator.compare(this, other) operator fun plus(other: Choice) = Choice(sanitized + other.sanitized, weight + other.weight) val sanitized by lazy { tokens.filter { "ε" !in it } } val asString by lazy { sanitized.joinToString(" ") } } // Returns a metric measuring Levenshtein distance w.r.t. some reference string fun levMetric(withRespectTo: Σᐩ): ChoiceMetric = withRespectTo.tokenizeByWhitespace() .let { wrt -> { levenshtein(it.sanitized, wrt).toFloat() } }
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
4,632
galoisenne
Apache License 2.0
src/main/kotlin/solutions/constantTime/iteration1/MemorizedTaxCalculator.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70755}
package solutions.constantTime.iteration1 import dataModel.base.Money import dataModel.base.Money.Companion.cents import dataModel.base.TaxBracket import dataModel.base.TaxCalculator import sampleData.SampleTaxBrackets import solutions.logN.LogNTaxCalculator /** * Temporary assumption on the max supported income to get things rolling without blowing up memory consumption. The * next iteration will eliminate this assumption. */ private val maxReportedIncome = SampleTaxBrackets.bracketsWithTinyRange.last().from * 2 /** * A very inefficient idea as a starting point to iterate towards a constant-time solution. This simply computes and * memorizes the taxes for every possible income up to [maxReportedIncome]. * * Note that this solution isn't actually constant amortized time even though we're just looking up the tax in a map. * An explanation is included here: * * https://itnext.io/impossible-algorithm-computing-income-tax-in-constant-time-716b3c36c012 */ class MemorizedTaxCalculator(taxBrackets: List<TaxBracket>) : TaxCalculator { private val memorizedIncomeToTaxAmount: Map<Money, Money> init { val taxCalculator = LogNTaxCalculator(taxBrackets) memorizedIncomeToTaxAmount = generateSequence(0.cents) { it + 1.cents } .takeWhile { it <= maxReportedIncome } // create a hashMap as "associateWith" creates a LinkedHashMap by default which uses more memory .associateWithTo(HashMap()) { income -> taxCalculator.computeTax(income) } } override fun computeTax(income: Money): Money { return memorizedIncomeToTaxAmount[income] ?: throw UnsupportedOperationException("Unsupported income: $income") } }
0
Kotlin
0
1
166d8bc05c355929ffc5b216755702a77bb05c54
1,707
tax-calculator
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/PaintWalls.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.E_9 import kotlin.math.max import kotlin.math.min /** * 2742. Painting the Walls * @see <a href="https://leetcode.com/problems/painting-the-walls">Source</a> */ fun interface PaintWalls { operator fun invoke(cost: IntArray, time: IntArray): Int } /** * Approach 1: Top-Down Dynamic Programming */ class PaintWallsTopDown : PaintWalls { private lateinit var memo: Array<IntArray> private var n = 0 override fun invoke(cost: IntArray, time: IntArray): Int { n = cost.size memo = Array(n) { IntArray(n + 1) } return dp(0, n, cost, time) } private fun dp(i: Int, remain: Int, cost: IntArray, time: IntArray): Int { if (remain <= 0) { return 0 } if (i == n) { return 1e9.toInt() } if (memo[i][remain] != 0) { return memo[i][remain] } val paint = cost[i] + dp(i + 1, remain - 1 - time[i], cost, time) val dontPaint = dp(i + 1, remain, cost, time) memo[i][remain] = min(paint.toDouble(), dontPaint.toDouble()).toInt() return memo[i][remain] } } /** * Approach 2: Bottom-Up Dynamic Programming */ class PaintWallsBottomUp : PaintWalls { override fun invoke(cost: IntArray, time: IntArray): Int { val n: Int = cost.size val dp = Array(n + 1) { IntArray(n + 1) } for (i in 1..n) { dp[n][i] = E_9.toInt() } for (i in n - 1 downTo 0) { for (remain in 1..n) { val paint = cost[i] + dp[i + 1][max(0, remain - 1 - time[i])] val dontPaint = dp[i + 1][remain] dp[i][remain] = min(paint.toDouble(), dontPaint.toDouble()).toInt() } } return dp[0][n] } } /** * Approach 3: Space-Optimized Dynamic Programming */ class PaintWallsSpaceOptDP : PaintWalls { override fun invoke(cost: IntArray, time: IntArray): Int { val n: Int = cost.size var dp = IntArray(n + 1) var prevDp = IntArray(n + 1) { E_9.toInt() } prevDp[0] = 0 for (i in n - 1 downTo 0) { dp = IntArray(n + 1) for (remain in 1..n) { val paint = cost[i] + prevDp[max(0, remain - 1 - time[i])] val dontPaint = prevDp[remain] dp[remain] = min(paint.toDouble(), dontPaint.toDouble()).toInt() } prevDp = dp } return dp[n] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,128
kotlab
Apache License 2.0
src/Day01.kt
rdbatch02
575,174,840
false
{"Kotlin": 18925}
fun main() { fun getElfTotals(input: List<String>): List<Int> { val elfTotals: MutableList<Int> = mutableListOf(0) input.forEach{ if (it.isNotBlank()) { elfTotals[elfTotals.lastIndex] = elfTotals.last() + it.toInt() } else { elfTotals.add(0) } } return elfTotals } fun part1(input: List<String>): Int { return getElfTotals(input).maxOf { it } } fun part2(input: List<String>): Int { val elfTotals = getElfTotals(input).sortedDescending() var top3 = 0 for (i in 0..2) { top3 += elfTotals[i] } return top3 } val input = readInput("Day01") println("Part 1 - " + part1(input)) println("Part 2 - " + part2(input)) }
0
Kotlin
0
1
330a112806536910bafe6b7083aa5de50165f017
820
advent-of-code-kt-22
Apache License 2.0
src/main/kotlin/aoc2016/ExplosivesInCyberspace.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2016 fun explosivesInCyberspace1(input: CharSequence): Long = explosivesInCyberspace(input, recurse = false) fun explosivesInCyberspace2(input: CharSequence): Long = explosivesInCyberspace(input, recurse = true) private fun explosivesInCyberspace(input: CharSequence, recurse: Boolean): Long { val data = input.filter { !it.isWhitespace() } var result = 0L var pos = 0 while (pos < data.length) { val marker = Marker.from(data, pos) if (marker != null) { val len = if (recurse) explosivesInCyberspace(marker.data, recurse = true) else marker.data.length.toLong() result += marker.repetitions * len pos = marker.next } else { result += 1 pos++ } } return result } private data class Marker( val repetitions: Int, val data: CharSequence, val next: Int ) { companion object { private val markerRegex = Regex("""\((\d+)x(\d+)\)""") fun from(s: CharSequence, pos: Int): Marker? { val match = markerRegex.matchAt(s, pos) ?: return null val length = match.groupValues[1].toInt() val count = match.groupValues[2].toInt() val offset = pos + match.value.length return Marker( repetitions = count, data = s.subSequence(offset, offset + length), next = offset + length ) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,493
advent-of-code
MIT License
src/adventofcode/Day21.kt
Timo-Noordzee
573,147,284
false
{"Kotlin": 80936}
package adventofcode import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit private const val ROOT = "root" private const val HUMAN = "humn" private operator fun List<String>.component2() = this[1][0] private fun MutableMap<String, String>.compute(monkeyId: String): Long? { val monkeyValue = getValue(monkeyId) if (monkeyValue.isEmpty()) return null if (monkeyValue[0].isDigit()) return monkeyValue.toInt().toLong() val (left, operator, right) = monkeyValue.split(' ') val a = compute(left)?.also { this[left] = it.toString() } val b = compute(right)?.also { this[right] = it.toString() } if (a == null || b == null) { this[monkeyId] = "${a ?: left} $operator ${b ?: right}" return null } val value = when (operator) { '+' -> a + b '-' -> a - b '*' -> a * b '/' -> a / b else -> error("unknown operator") } this[monkeyId] = value.toString() return value } @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 0) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) class Day21 { var input: List<String> = emptyList() @Setup fun setup() { input = readInput("Day21") } private fun parseMonkeys(): MutableMap<String, String> { val monkeys = mutableMapOf<String, String>() input.forEach { line -> monkeys[line.substringBefore(':')] = line.substringAfter(' ') } return monkeys } @Benchmark fun part1(): Long = parseMonkeys().compute(ROOT)!! @Benchmark fun part2(): Long { val monkeys = parseMonkeys() monkeys[HUMAN] = "" monkeys[ROOT] = monkeys.getValue(ROOT).split(' ').let { (left, _, right) -> "$left = $right" } // Precompute most values so only the unknown path to humn remains monkeys.compute(ROOT) var ans = 0L var current = ROOT // Perform the reversed operations starting from root until humn has been reached. while (current != HUMAN) { val (left, operator, right) = monkeys.getValue(current).split(' ') ans = when { left.isNumeric() -> { current = right val value = left.toLong() when (operator) { '=' -> value '+' -> ans - value '-' -> value - ans '*' -> ans / value '/' -> value / ans else -> error("unknown operator") } } right.isNumeric() -> { current = left val value = right.toLong() when (operator) { '=' -> value '+' -> ans - value '-' -> ans + value '*' -> ans / value '/' -> ans * value else -> error("unknown operator") } } else -> error("neither left nor right is numeric") } } return ans } } fun main() { val day21 = Day21() // test if implementation meets criteria from the description, like: day21.input = readInput("Day21_test") check(day21.part1() == 152L) check(day21.part2() == 301L) day21.input = readInput("Day21") println(day21.part1()) println(day21.part2()) // 3952673930912 }
0
Kotlin
0
2
10c3ab966f9520a2c453a2160b143e50c4c4581f
3,547
advent-of-code-2022-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/easy/RomanToInt.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.easy /** * 13. 罗马数字转整数 * 罗马数字包含以下七种字符:I,V,X,L,C,D和M。 * * 字符 数值 * I 1 * V 5 * X 10 * L 50 * C 100 * D 500 * M 1000 * * 例如, 罗马数字 2 写做II,即为两个并列的 1 。12 写做XII,即为X+II。 27 写做XXVII, 即为XX+V+II。 * * 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做IIII,而是IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况: * * I可以放在V(5) 和X(10) 的左边,来表示 4 和 9。 * X可以放在L(50) 和C(100) 的左边,来表示 40 和90。 * C可以放在D(500) 和M(1000) 的左边,来表示400 和900。 * 给定一个罗马数字,将其转换成整数。 */ class RomanToInt { companion object { @JvmStatic fun main(args: Array<String>) { println(RomanToInt().romanToInt("III")) println(RomanToInt().romanToInt("IV")) println(RomanToInt().romanToInt("IX")) println(RomanToInt().romanToInt("LVIII")) println(RomanToInt().romanToInt("MCMXCIV")) } } fun romanToInt(s: String): Int { val map = hashMapOf( 'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000 ) var result = 0 for (i in s.indices) { val current = map[s[i]] if (i < s.length - 1 && current!! < map[s[i + 1]]!!) { result -= current } else { result += current!! } } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,954
daily_algorithm
Apache License 2.0
2016/src/main/kotlin/com/koenv/adventofcode/Day7.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode object Day7 { fun parseParts(input: String): List<Part> { val result = mutableListOf<Part>() var currentType = Type.IP val currentPart = StringBuilder() val chars = input.toCharArray() chars.forEach { when (it) { '[' -> { if (currentType == Type.HYPERNET) { throw IllegalArgumentException("Nested hypernet") } result.add(Part(currentType, currentPart.toString())) currentType = Type.HYPERNET currentPart.setLength(0) // clear it } ']' -> { if (currentType != Type.HYPERNET) { throw IllegalArgumentException("Invalid end of hypernet") } result.add(Part(currentType, currentPart.toString())) currentType = Type.IP currentPart.setLength(0) // clear it } else -> currentPart.append(it) } } if (currentType == Type.HYPERNET) { throw IllegalArgumentException("Unfinished hypernet") } result.add(Part(currentType, currentPart.toString())) return result } fun supportsTls(parts: List<Part>): Boolean { val hasNoAbbaInHypernet = parts .filter { it.type == Type.HYPERNET } .map { !containsAbba(it.value) } .all { it } val hasAbbaInRest = parts .filter { it.type == Type.IP } .map { containsAbba(it.value) } .any { it } return hasNoAbbaInHypernet && hasAbbaInRest } fun supportsTls(input: String) = supportsTls(parseParts(input)) fun containsAbba(input: String): Boolean { val chars = input.toCharArray() for (i in 0..chars.size - 4) { if (chars[i] == chars[i + 3] && chars[i + 1] == chars[i + 2]) { return chars[i] != chars[i + 1] // it cannot be a continuous string } } return false } fun countIpsThatSupport(input: String, predicate: (String) -> Boolean) = input.lines() .filter(String::isNotBlank) .map { predicate(it.trim()) } .count { it } fun countIpsThatSupportTls(input: String) = countIpsThatSupport(input, { supportsTls(it) }) fun getAbas(input: String): List<String> { val chars = input.toCharArray() val result = mutableListOf<String>() for (i in 0..chars.size - 3) { if (chars[i] == chars[i + 2] && chars[i] != chars[i + 1]) { result.add(String(charArrayOf(chars[i], chars[i + 1], chars[i + 2]))) } } return result } fun getMatchingBab(input: String): String { if (input.length != 3) { throw IllegalArgumentException("Invalid ABA") } return String(charArrayOf(input[1], input[0], input[1])) } fun supportsSsl(input: String) = supportsSsl(parseParts(input)) fun supportsSsl(parts: List<Part>): Boolean { val abas = parts .filter { it.type == Type.IP } .map { getAbas(it.value) } .flatten() val babs = parts .filter { it.type == Type.HYPERNET } .map { getAbas(it.value) } .flatten() .map { getMatchingBab(it) } return abas.intersect(babs).any() } fun countIpsThatSupportSsl(input: String) = countIpsThatSupport(input, { supportsSsl(it) }) data class Part( val type: Type, val value: String ) enum class Type { IP, HYPERNET } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
3,837
AdventOfCode-Solutions-Kotlin
MIT License
2022/main/day_10/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_10_2022 import java.io.File import kotlin.math.abs fun part1(input: List<String>) { val signalStrengths = mutableListOf<Int>() var signalStrength = 1 for (signal in input) { if (signal.startsWith("addx")) { val arg = signal.split(" ")[1].toInt() signalStrengths.add(signalStrength) signalStrengths.add(signalStrength) signalStrength += arg } else { signalStrengths.add(signalStrength) } } var sum = 0 sum += (signalStrengths[19] * 20) sum += (signalStrengths[59] * 60) sum += (signalStrengths[99] * 100) sum += (signalStrengths[139] * 140) sum += (signalStrengths[179] * 180) sum += (signalStrengths[219] * 220) print("The sum of the first six signal strengths is $sum") } fun part2(input: List<String>) { val signalStrengths = mutableListOf<Int>() var signalStrength = 1 for (signal in input) { if (signal.startsWith("addx")) { val arg = signal.split(" ")[1].toInt() signalStrengths.add(signalStrength) signalStrengths.add(signalStrength) signalStrength += arg } else { signalStrengths.add(signalStrength) } } for (i in 0..239 step 40) { var line = "" for (j in i until i+40) { line += if (abs((signalStrengths[j] - (j-i))) % 40 < 2) "#" else "." } println(line) } } fun main(){ val inputFile = File("2022/inputs/Day_10.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
1,670
AdventofCode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ArrangingCoins.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.sqrt fun interface ArrangingCoinsStrategy { operator fun invoke(n: Int): Int } class ArrangingCoinsBS : ArrangingCoinsStrategy { override fun invoke(n: Int): Int { var left = 0 var right = n var k: Int var curr: Int while (left <= right) { k = left + right.minus(left) / 2 curr = k * k.plus(1) / 2 if (curr == n) return k if (n < curr) { right = k - 1 } else { left = k + 1 } } return right } } class ArrangingCoinsMath : ArrangingCoinsStrategy { override fun invoke(n: Int): Int { val local = sqrt(C1 * n + C2) - C3 return local.toInt() } companion object { private const val C1 = 2 private const val C2 = 0.25 private const val C3 = 0.5 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,538
kotlab
Apache License 2.0
day19/src/Day19.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File import kotlin.math.abs data class Point(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Point): Point = Point(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point): Point = Point(x - other.x, y - other.y, z - other.z) fun manhattan(other: Point): Int { return abs(x - other.x) + abs(y - other.y) + abs(z - other.z) } } data class Scanner( val beacon: Set<Point>, var solved: Boolean = false, var offset: Point = Point(0, 0, 0) ) data class Result( val beacons: Set<Point>, val offset: Point ) class Day19(path: String) { private val scanner = mutableListOf<Scanner>() private val finalBeacons = mutableSetOf<Point>() private val overlapCount = 12 init { var beacons: MutableSet<Point> = mutableSetOf() File(path).forEachLine { line -> if (line.contains("---")) { beacons = mutableSetOf() } else if (line.isNotEmpty()) { val coord = line.split(",") val point = Point(coord[0].toInt(), coord[1].toInt(), coord[2].toInt()) beacons.add(point) } else { scanner.add(Scanner(beacons)) } } scanner.add(Scanner(beacons)) } private fun rotate(p: Point, combination: Int): Point { // From https://www.euclideanspace.com/maths/algebra/matrix/transforms/examples/index.htm return when (combination) { 0 -> Point(p.x, p.y, p.z) 1 -> Point(p.x, p.z, -p.y) 2 -> Point(p.x, -p.y, -p.z) 3 -> Point(p.x, -p.z, p.y) 4 -> Point(-p.y, p.x, p.z) 5 -> Point(p.z, p.x, p.y) 6 -> Point(p.y, p.x, -p.z) 7 -> Point(-p.z, p.x, -p.y) 8 -> Point(-p.x, -p.y, p.z) 9 -> Point(-p.x, -p.z, -p.y) 10 -> Point(-p.x, p.y, -p.z) 11 -> Point(-p.x, p.z, p.y) 12 -> Point(p.y, -p.x, p.z) 13 -> Point(p.z, -p.x, -p.y) 14 -> Point(-p.y, -p.x, -p.z) 15 -> Point(-p.z, -p.x, p.y) 16 -> Point(-p.z, p.y, p.x) 17 -> Point(p.y, p.z, p.x) 18 -> Point(p.z, -p.y, p.x) 19 -> Point(-p.y, -p.z, p.x) 20 -> Point(-p.z, -p.y, -p.x) 21 -> Point(-p.y, p.z, -p.x) 22 -> Point(p.z, p.y, -p.x) 23 -> Point(p.y, -p.z, -p.x) else -> Point(0, 0, 0) } } private fun compareBeacons(aSet: Set<Point>, bSet: Set<Point>): Result? { (0..23).forEach { combination -> val bSetRotated = bSet.map { rotate(it, combination) }.toSet() aSet.forEach { a -> bSetRotated.forEach { b -> val offset = a.minus(b) val bSetRotatedTranslated = bSetRotated.map { it.plus(offset) }.toSet() val intersect = aSet.intersect(bSetRotatedTranslated) if (intersect.size >= overlapCount) { return Result(bSetRotatedTranslated, offset) } } } } return null } fun part1(): Int { scanner[0].solved = true finalBeacons.addAll(scanner[0].beacon) while (scanner.count { it.solved } < scanner.size) { for (i in 0 until scanner.size) { // Don't anchor on unsolved scanner if (!scanner[i].solved) { continue } for (j in 0 until scanner.size) { // Don't compare against self, don't compare with already solved scanner if ((i == j) || scanner[j].solved) { continue } val result = compareBeacons(scanner[i].beacon, scanner[j].beacon) if (result != null) { println("scanners $i and $j overlap") finalBeacons.addAll(result.beacons) scanner[j] = Scanner(result.beacons, true, result.offset) } } } } return finalBeacons.size } fun part2(): Int { var max = 0 for (a in scanner) { for (b in scanner) { if (a.offset == b.offset) { continue } val distance = a.offset.manhattan(b.offset) if (distance > max) { max = distance } } } return max } } fun main() { val aoc = Day19("day19/input.txt") println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
4,779
aoc2021
Apache License 2.0
src/main/kotlin/days/Day16.kt
vovarova
572,952,098
false
{"Kotlin": 103799}
package days import java.util.* class Day16 : Day(16) { class Valves(intput: List<String>) { inner class Valve(val name: String, val rate: Int, val lead: List<String>) { fun leads(): List<Valve> = lead.map { index[it]!! } override fun toString(): String { return "Valve(name='$name', rate=$rate, lead=$lead)" } } val index: Map<String, Valve> val orderedValves: List<Valve> val distance: Map<Valve, Map<Valve, Int>> init { val regExp = "Valve (?<valveName>.+?) has flow rate=(?<rate>\\d+); tunnel[s]? lead[s]? to valve[s]? (?<lead>.*)".toRegex() index = intput.map { line -> regExp.matchEntire(line)?.let { Valve( it.groups["valveName"]!!.value, it.groups["rate"]!!.value.toInt(), it.groups["lead"]!!.value.split(", ").toList() ) } }.also { it.forEach { println(it) } }.map { it!!.name to it }.toMap() orderedValves = index.values.filter { it.rate > 0 }.sortedByDescending { it.rate } distance = (orderedValves + index["AA"]!!).map { it to minDistance(it) }.toMap() } fun minDistance(from: Valve): MutableMap<Valve, Int> { val distance = mutableMapOf<Valve, Int>() val stack = PriorityQueue<Pair<Valve, Int>>(Comparator.comparing { it.second }) stack.add(Pair(from, 0)) while (stack.isNotEmpty()) { val poll = stack.poll() distance.put(poll.first, poll.second) poll.first.leads().filter { !distance.contains(it) }.forEach { stack.add(Pair(it, poll.second + 1)) } } return distance } fun initialPathPart1(): Path { return Path(listOf(index["AA"]!!), 30) } fun initialPathPart2(): Path { return Path(listOf(index["AA"]!!), 26) } inner class Path(val valves: List<Valves.Valve> = emptyList(), val time: Int) { fun addOpenedNode(valve: Valves.Valve): Path { return Path(valves + valve, time) } val potentialBenefit = run { var benefit = 0 var timeLeft = timeLeft() val leftToOpen = orderedValves - valves.toSet() val minDistance = leftToOpen.map { distance[valves.last()]!![it]!! }.min() for (valve in leftToOpen) { timeLeft -= minDistance + 1 benefit += valve.rate * Math.max(0, timeLeft) } pressure() + benefit } fun timeLeft(): Int { return time - valves.windowed(2).map { distance[it[0]]!!.get(it[1])!! + 1 }.sum() } fun pressure(): Long { var timeLeft = time var pressure = 0L valves.windowed(2).forEach { val distance = distance[it[0]]!!.get(it[1])!! timeLeft -= distance + 1 pressure += timeLeft * it[1].rate } return pressure } } companion object { fun potentialBenefit(leftTime: Int, leftToOpen: Set<Valve>): Long { var benefit = 0L var timeLeft = leftTime leftToOpen.windowed(2, step = 2) { timeLeft -= 2 benefit += it[0].rate * Math.max(timeLeft, 0) benefit += it[1].rate * Math.max(timeLeft, 0) } return benefit } } } override fun partOne(): Any { val valves = Valves(inputList) val nodesToOpen = valves.orderedValves.toMutableSet() var maxPresure = 1809L var maxPath = valves.initialPathPart1() val pathes: LinkedList<Valves.Path> = LinkedList<Valves.Path>().apply { addLast(valves.initialPathPart1()) } while (!pathes.isEmpty()) { val poll = pathes.pollLast()!! if (poll.potentialBenefit <= maxPresure) { continue } if (poll.pressure() > maxPresure) if (poll.pressure() > maxPresure) { maxPresure = poll.pressure() maxPath = poll } val notOpened = nodesToOpen - poll.valves notOpened.map { poll.addOpenedNode(it) }.filter { it.timeLeft() >= 0 }.forEach { pathes.addLast(it) } } return maxPresure } override fun partTwo(): Any { val valves = Valves(inputList) val nodesToOpen = valves.orderedValves.toMutableSet() var maxPresure = 0L var maxPath = Pair(valves.initialPathPart2(), valves.initialPathPart2()) val pathes: LinkedList<Pair<Valves.Path, Valves.Path>> = LinkedList<Pair<Valves.Path, Valves.Path>>().apply { add(maxPath) } while (!pathes.isEmpty()) { val poll = pathes.pollLast()!! // trick to remove most of useless nodes val potentialBenefit = Valves.potentialBenefit( Math.min(poll.first.timeLeft(), poll.second.timeLeft()), nodesToOpen - (poll.first.valves + poll.second.valves).toSet() ) if (potentialBenefit + poll.first.pressure() + poll.second.pressure() < maxPresure) { continue } if (poll.first.pressure() + poll.second.pressure() > maxPresure) { maxPresure = poll.first.pressure() + poll.second.pressure() maxPath = poll } val openValves = nodesToOpen - (poll.first.valves + poll.second.valves) openValves.flatMap { if (poll.first.valves.last() == poll.second.valves.last()) { listOf( Pair(poll.first.addOpenedNode(it), poll.second) ) } else { listOf( Pair(poll.first.addOpenedNode(it), poll.second), Pair(poll.first, poll.second.addOpenedNode(it)) ) } }.filter { it.first.timeLeft() >= 0 }.filter { it.second.timeLeft() >= 0 }.forEach { pathes.addLast(it) } } println(maxPresure) return maxPresure } }
0
Kotlin
0
0
e34e353c7733549146653341e4b1a5e9195fece6
6,664
adventofcode_2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/javadev/sort/QuickSort.kt
javadev
156,964,261
false
null
package com.github.javadev.sort /* public class QuickSort { public void quickSort(int[] array) { quickSort(array, 0, array.length - 1); } void quickSort(int[] array, int low, int high) { if (low < high) { int p = partition(array, low, high); quickSort(array, low, p); quickSort(array, p + 1, high); } } // Partition the array list[first..last] int partition(int[] list, int first, int last) { int pivot = list[first]; // Choose the first element as the pivot int low = first + 1; // Index for forward search int high = last; // Index for backward search while (high > low) { // Search forward from left while (low <= high && list[low] <= pivot) { low++; } // Search backward from right while (low <= high && list[high] > pivot) { high--; } // Swap two elements in the list if (high > low) { swap(list, low, high); } } while (high > first && list[high] >= pivot) { high--; } // Swap pivot with list[high] if (pivot > list[high]) { list[first] = list[high]; list[high] = pivot; return high; } else { return first; } } void swap(int[] array, int low, int high) { int value = array[low]; array[low] = array[high]; array[high] = value; } } */ class QuickSort { fun quickSort(array:IntArray) { quickSort(array, 0, array.size - 1) } internal fun quickSort(array:IntArray, low:Int, high:Int) { if (low < high) { val p = partition(array, low, high) quickSort(array, low, p) quickSort(array, p + 1, high) } } // Partition the array list[first..last] internal fun partition(list:IntArray, first:Int, last:Int):Int { val pivot = list[first] // Choose the first element as the pivot var low = first + 1 // Index for forward search var high = last // Index for backward search while (high > low) { // Search forward from left while (low <= high && list[low] <= pivot) { low++ } // Search backward from right while (low <= high && list[high] > pivot) { high-- } // Swap two elements in the list if (high > low) { swap(list, low, high) } } while (high > first && list[high] >= pivot) { high-- } // Swap pivot with list[high] if (pivot > list[high]) { list[first] = list[high] list[high] = pivot return high } else { return first } } internal fun swap(array:IntArray, low:Int, high:Int) { val value = array[low] array[low] = array[high] array[high] = value } }
0
Kotlin
0
5
3f71122f1d88ee1d83acc049f9f5d44179c34147
2,720
classic-cherries-kotlin
Apache License 2.0
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/SwapPairs.kt
scientificCommunity
352,868,267
false
{"Java": 154453, "Kotlin": 69817}
package org.baichuan.sample.algorithms.leetcode.middle /** * https://leetcode.cn/problems/swap-nodes-in-pairs/ */ class SwapPairs { fun swapPairs(head: ListNode?): ListNode? { if (head?.next == null) { return head } val newHead = head.next //交换后head变成后面的节点,所以head需要连接递归后的后续链表 head.next = swapPairs(newHead?.next) //第二个节点变成头节点, 原头节点跟在第二个节点后 newHead?.next = head return newHead } /** * 非递归解法 */ fun swapPairs1(head: ListNode?): ListNode? { if (head?.next == null) { return head } var curr = head val result = head.next var pre: ListNode? = null while (curr?.next != null) { val newHead = curr.next val newCurr = newHead?.next newHead?.next = curr curr.next = newCurr pre?.next = newHead pre = curr if (newCurr == null) { break } curr = newCurr } return result } } fun main() { val head1 = ListNode(1) val head2 = ListNode(2) val head3 = ListNode(3) // val head4 = ListNode(4) head1.next = head2 head2.next = head3 // head3.next = head4 SwapPairs().swapPairs1(head1) }
1
Java
0
8
36e291c0135a06f3064e6ac0e573691ac70714b6
1,411
blog-sample
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/SmallestDifference.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.arrays fun main() { val arrOne = mutableListOf(2, -9, 0, 14, 1, -8, -3, -1, 8, -6, 5, -5) val arrTwo = mutableListOf(15, -8, 3, 1, 7, -10, 2, -1, 4, -3, 17, -2) print(smallestDifference(arrOne, arrTwo)) // [-8, -8] } // O(nlog(n) + mlog(m)) time | O(1) space private fun smallestDifference(arrOne: MutableList<Int>, arrTwo: MutableList<Int>): List<Int> { arrOne.sort() arrTwo.sort() var smallestPair = listOf<Int>() var idxOne = 0 var idxTwo = 0 var smallest = Int.MAX_VALUE var curr: Int while (idxOne < arrOne.size && idxTwo < arrTwo.size) { val numOne = arrOne[idxOne] val numTwo = arrTwo[idxTwo] when { numOne < numTwo -> { curr = numTwo - numOne idxOne++ } numTwo < numOne -> { curr = numOne - numTwo idxTwo++ } else -> return listOf(numOne, numTwo) } if (curr < smallest) { smallest = curr smallestPair = listOf(numOne, numTwo) } } return smallestPair }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,167
algs4-leprosorium
MIT License
test/leetcode/MissingNumber.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.* import net.jqwik.api.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.* import org.junit.jupiter.params.converter.* import org.junit.jupiter.params.provider.* /** * https://leetcode.com/problems/missing-number/ * * 268. Missing Number * [Easy] * * Given an array nums containing n distinct numbers in the range [0, n], * return the only number in the range that is missing from the array. * * Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? * * Constraints: * - n == nums.length * - 1 <= n <= 10^4 * - 0 <= nums[i] <= n * - All the numbers of nums are unique. */ fun missingNumber(nums: List<Int>) = sum0ToN(nums.size) - nums.sum() fun sum0ToN(n: Int) = (n * (n + 1)) / 2 // gauss summation /** * What if there are multiple missing numbers? */ fun missingNumbers(n: Int, nums: List<Int>) = with(nums.toHashSet()) { (0..n).filter { !contains(it) } } /** * Unit tests */ class MissingNumberTest { @ParameterizedTest @CsvSource( "[3,0,1]; 2", "[0,1]; 2", "[0]; 1", "[9,6,4,2,3,5,7,0,1]; 8", delimiter = ';' ) fun `missing number in the range 0 to n`( @ConvertWith(IntArrayArg::class) nums: Array<Int>, missingNumber: Int ) { assertThat( missingNumber(nums.toList()) ).isEqualTo( missingNumber ) } @ParameterizedTest @CsvSource( "5; [3,0,1]; [2,4,5]", "2; [0,1]; [2]", "9; []; [0,1,2,3,4,5,6,7,8,9]", "9; [9,8,6,4,2,3,5,7,0,1]; []", delimiter = ';' ) fun `missing numbers in the range 0 to n`( n: Int, @ConvertWith(IntArrayArg::class) nums: Array<Int>, @ConvertWith(IntArrayArg::class) missingNumbers: Array<Int> ) { assertThat( missingNumbers(n, nums.toList()) ).containsExactlyElementsOf( missingNumbers.asIterable() ) } } class MissingNumberPropertyBasedTest { @Property fun `missing number in the range 0 to n`(@ForAll("1 to 10000") n: Int) { val missingNumber = (0..n).random() val numbers = (0..n).filterNot { it == missingNumber }.shuffled() assertThat( missingNumber(numbers) ).isEqualTo( missingNumber ) } @Provide("1 to 10000") @Suppress("unused") private fun numbers() = Arbitraries.integers().between(1, 10000) }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
2,545
coding-challenges
MIT License
src/leetcode_study_badge/data_structure/Day8.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.data_structure class Day8 { fun groupAnagrams(strs: Array<String>): List<List<String>> { val hashToStrs = HashMap<Int, MutableList<String>>() for (str in strs) { hashToStrs.getOrPut(hash(str)) { mutableListOf() }.add(str) } return hashToStrs.values.toList() } private fun hash(str: String): Int { val freqs = IntArray(26) { 0 } for (ch in str) { ++freqs[ch - 'a'] } return freqs.contentHashCode() } // One line solution fun groupAnagramsOneLine(strs: Array<String>): List<List<String>> = mutableMapOf<String, MutableList<String>>().apply { strs.forEach { getOrPut(it.toCharArray().sorted().joinToString("")) { mutableListOf() }.add(it) } }.values.toList() fun multiply(num1: String, num2: String): String { if ("0" == num1 || "0" == num2) return "0" val list = Array(num1.length + num2.length - 1){0} for (i in num1.length - 1 downTo 0) { for (j in num2.length - 1 downTo 0) { list[i + j] += (num1[i] - '0') * (num2[j] - '0') } } for (i in list.size - 1 downTo 1) { list[i - 1] += list[i] / 10 list[i] %= 10 } val builder = StringBuilder() list.forEach { builder.append(it) } return builder.toString() } } fun main() { val result = Day8().groupAnagramsOneLine(arrayOf("eat", "tea", "tan", "ate", "nat", "bat")) println(Day8().multiply("145","12")) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,625
dsa-kotlin
MIT License
src/main/kotlin/algorithms/FindSharedMotif.kt
jimandreas
377,843,697
false
null
@file:Suppress("unused") package algorithms /** * See also: * http://rosalind.info/problems/lcsm/ * Finding a Shared Motif (Longest Common Substring) * * Problem A common substring of a collection of strings is a substring of every member of the collection. We say that a common substring is a longest common substring if there does not exist a longer common substring. For example, "CG" is a common substring of "ACGTACGT" and "AACCGTATA", but it is not as long as possible; in this case, "CGTA" is a longest common substring of "ACGTACGT" and "AACCGTATA". Note that the longest common substring is not necessarily unique; for a simple example, "AA" and "CC" are both longest common substrings of "AACC" and "CCAA". Given: A collection of k (k≤100) DNA strings of length at most 1 kbp each in FASTA format. Return: A longest common substring of the collection. (If multiple solutions exist, you may return any single solution.) */ class FindSharedMotif { // NOTE that the strings DO NOT have to all be the same length fun findMostLikelyCommonAncestor(sList: List<String>): String { // brute force search, keep going until nothing works // find the longest string to use for our sampling val longestString = sList.maxByOrNull { it.length } val len = longestString!!.length var tryThisLen = len // optimistic - but try the full length string first while (len > 0) { for (i in 0 until len - tryThisLen + 1) { // get test pattern val testString = longestString.substring(i, i + tryThisLen) var success = true for (s in sList) { if (!s.contains(testString)) { success = false break } } if (success) { return testString } } tryThisLen-- } return "" } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
2,023
stepikBioinformaticsCourse
Apache License 2.0
Codeforces/1530/C.kt
thedevelopersanjeev
112,687,950
false
null
private fun readLn() = readLine() ?: "" private fun readLns() = readLn().split(" ") private fun readInt() = readLn().toInt() private fun readInts() = readLns().map { it.toInt() } private fun good( a: List<Int>, b: List<Int>, extra: Int ): Boolean { var contests = a.size + extra contests -= (contests / 4) var (myCount, myScore, oppCount, oppScore) = listOf(0, 0, 0, 0) for (i in 0 until extra) { if (myCount < contests) { myScore += 100 ++myCount } } for (i in a.indices) { if (myCount < contests) { myScore += a[i] ++myCount } if (oppCount < contests) { oppScore += b[i] ++oppCount } } return myScore >= oppScore } fun main() { val T = readInt() repeat(T) { val N = readInt() val a = readInts().sortedDescending() val b = readInts().sortedDescending() var (lo, hi, ans) = listOf(0, 100000, 100000) while (lo <= hi) { val mid = lo + (hi - lo) / 2 if (good(a, b, mid)) { ans = mid hi = mid - 1 } else { lo = mid + 1 } } println(ans) } }
0
C++
58
146
610520cc396fb13a03c606b5fb6739cfd68cc444
1,316
Competitive-Programming
MIT License
src/Day04.kt
paul-matthews
433,857,586
false
{"Kotlin": 18652}
typealias BingoNumbers = List<Int> fun List<String>.toInts(): List<Int> = map{ it.toInt() } fun List<String>.getBingoNumbers(): BingoNumbers = first().split(",").map { it.toInt() } data class BingoBoard(val raw: RawBingoBoard, val scoreLines: List<BingoScoreLine>, val matched: BingoNumbers, val unmatched: BingoNumbers) { companion object { fun fromRawBingoBoard(raw: RawBingoBoard): BingoBoard { return BingoBoard( raw = raw, scoreLines = raw.getScoreLines(), matched = emptyList(), unmatched = raw.flatten() ) } } fun mark(num: Int): BingoBoard { var hasMatched = false val newScores = scoreLines.map { val newScore = it.mark(num) if (newScore !== it) hasMatched = true newScore } if (!hasMatched) { return this } return copy(scoreLines = newScores, matched = matched + num, unmatched = unmatched.filter { it != num }) } fun hasWon() = scoreLines.any { it.hasWon() } fun score(): Int { return unmatched.sum() * matched.last() } } typealias RawBingoBoard = List<List<Int>> fun List<String>.getRawBoards(): List<RawBingoBoard> { var remainingLines = drop(1) val boards = mutableListOf<RawBingoBoard>() while (remainingLines.isNotEmpty()) { val (newRemain, currentBoard) = remainingLines.getNextBoardAndRemainder() boards.add(currentBoard) remainingLines = newRemain } return boards } fun List<RawBingoBoard>.getBingoBoards() = map { BingoBoard.fromRawBingoBoard(it) } fun RawBingoBoard.getScoreLines(): List<BingoScoreLine> { val scoreLines = mutableListOf<BingoScoreLine>() /* Add Rows */ scoreLines.addAll(map { BingoScoreLine(0, it) }) /* Add Columns */ scoreLines.addAll(first().indices.map {index -> BingoScoreLine(0, map { it[index] }) }) return scoreLines } fun List<String>.getNextBoardAndRemainder(): Pair<List<String>, RawBingoBoard> { val rows = drop(1).takeWhile { it != "" }.map() { it.splitFilterBlanks(" ").toInts() } return Pair(drop(1).dropWhile { it != "" }, rows) } typealias BingoGame = Pair</* The game numbers */ BingoNumbers, /* The Score Boards */ List<BingoBoard>> fun List<String>.getBingoGame() = BingoGame( getBingoNumbers(), getRawBoards().getBingoBoards()) typealias BingoScoreLine = Pair</* Score */ Int, /* Remaining Numbers */ List<Int>> fun BingoScoreLine.hasWon(): Boolean = (second.size == 0) fun BingoScoreLine.mark(num: Int): BingoScoreLine = if (hasWon() || !second.contains(num)) this else BingoScoreLine(first + num, second.filter { it != num }) fun BingoGame.countWins(): Int = second.count { it.hasWon() } fun BingoGame.scoreLastWin(): Int { if (first.isEmpty()) { return second.minOf { it.score() } } val drawnNumber = first.first() val previousWins = countWins() return BingoGame(first.drop(1), second.map { val marked = it.mark(drawnNumber) val previousWinState = it.hasWon() if (((previousWins + 1) == second.size) && previousWinState != marked.hasWon()) { return marked.score() } marked }).scoreLastWin() } fun BingoGame.score(): Int { if (first.isEmpty()) { return second.maxOf { it.score() } } val drawnNumber = first.first() return BingoGame(first.drop(1), second.map { val marked = it.mark(drawnNumber) if (marked.hasWon()) { return marked.score() } marked }).score() } fun main() { fun part1(input: List<String>) = input.getBingoGame().score() fun part2(input: List<String>) = input.getBingoGame().scoreLastWin() val testInput = readFileContents("Day04_test") val part1Result = part1(testInput) check(part1Result == 4512) { "Expected: 4512 but found $part1Result" } val part2Result = part2(testInput) check(part2Result == 1924) { "Expected 1924 but is: $part2Result" } val input = readFileContents("Day04") println("Part1: " + part1(input)) println("Part2: " + part2(input)) }
0
Kotlin
0
0
2f90856b9b03294bc279db81c00b4801cce08e0e
4,257
advent-of-code-kotlin-template
Apache License 2.0
shape/src/commonMain/kotlin/io/data2viz/shape/stack/StackOrder.kt
data2viz
89,368,762
false
null
/* * Copyright (c) 2018-2021. data2viz sàrl. * * 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.data2viz.shape.stack public enum class StackOrder { /** * Returns the given series order [0, 1, … n - 1] where n is the number of elements in series. * Thus, the stack order is given by the key accessor. */ NONE, /** * Returns a series order such that the smallest series (according to the sum of values) is at the bottom. */ ASCENDING, /** * Returns a series order such that the largest series (according to the sum of values) is at the bottom. */ DESCENDING, /** * Returns the reverse of the given series order [n - 1, n - 2, … 0] where n is the number of elements in series. * Thus, the stack order is given by the reverse of the key accessor. */ REVERSE, /** * Returns a series order such that the larger series (according to the sum of values) are on the inside and * the smaller series are on the outside. * This order is recommended for streamgraphs in conjunction with the wiggle offset. * See [Stacked Graphs—Geometry & Aesthetics by Byron & Wattenberg for more information.](http://leebyron.com/streamgraph/) */ INSIDEOUT; internal fun <T> sort(stackParams: List<StackParam<T>>): List<Int> = when (this) { ASCENDING -> stackParams.sortAscending() DESCENDING -> stackParams.sortDescending() REVERSE -> stackParams.sortReverse() INSIDEOUT -> stackParams.sortInsideOut() NONE -> stackParams.sortNone() } } private fun <T> List<StackParam<T>>.sortInsideOut(): List<Int> { val ascendingIndexes = this.sortDescending() var topSum = .0 var bottomSum = .0 val top = mutableListOf<Int>() val bottom = mutableListOf<Int>() ascendingIndexes.forEach { index -> val stackParam = this[index] if (topSum < bottomSum) { top.add(stackParam.index) topSum += stackParam.stackedValues.sumOf { it.to } } else { bottom.add(stackParam.index) bottomSum += stackParam.stackedValues.sumOf { it.to } } } return bottom.reversed() + top } private fun <T> List<StackParam<T>>.sortAscending() = sumSeries() .sortedBy { it.sum } .map { it.index } private fun <T> List<StackParam<T>>.sortDescending() = sumSeries() .sortedByDescending { it.sum } .map { it.index } private fun <T> List<StackParam<T>>.sortNone() = sumSeries() .map { it.index } private fun <T> List<StackParam<T>>.sortReverse(): List<Int> = sumSeries() .map { it.index } .reversed() internal fun <T> List<StackParam<T>>.sumSeries(): List<SeriesSum> = map { serie -> SeriesSum(serie.index, serie.stackedValues.sumOf { it.to - it.from }) } internal data class SeriesSum( val index: Int, val sum: Double )
79
Kotlin
29
389
5640d3e8f1ce4cd4e5d651431726869e329520fc
3,619
data2viz
Apache License 2.0
solutions/aockt/y2023/Y2023D10.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.spacial.Direction import aockt.util.spacial.Direction.* import aockt.util.spacial.Point import aockt.util.spacial.move import aockt.util.spacial.opposite import aockt.util.parse import aockt.util.spacial.polygonArea import io.github.jadarma.aockt.core.Solution object Y2023D10 : Solution { /** * A pipe segment. * @property location The coordinates where this pipe segment is placed. * @property flow The directions in which this pipe redirects fluids. */ private data class PipeSegment(val location: Point, val flow: Pair<Direction, Direction>) { init { require(flow.first != flow.second) { "A pipe cannot have the same output direction as the input." } } /** * Returns which direction would the contents of the pipe go depending on the [incoming] direction. * If the pipe cannot accept input from that direction, returns `null` instead. */ fun redirectFlow(incoming: Direction): Direction? = when (incoming) { flow.first -> flow.second flow.second -> flow.first else -> null } } /** * A map of the pipe system observed on the floating metal island. * @property nodes The pipe segments in the maze, indexed by their coordinates. * @param start The starting location from which to find the loop. */ private class PipeMaze( private val nodes: Map<Point, PipeSegment>, start: Point, ) { /** The loop contained in this pipe maze, obtained by following the pipes from the start location. */ val loop: List<PipeSegment> = buildList { /** From a pipe segment and the current flow direction, find the next segment and its respective output. */ fun Pair<PipeSegment, Direction>.flow(): Pair<PipeSegment, Direction> { val (node, flow) = this val nextNode = nodes[node.location.move(flow)] checkNotNull(nextNode) { "Invalid loop. Pipe diverted outside of bounds." } val nextFlow = nextNode.redirectFlow(flow.opposite) checkNotNull(nextFlow) { "Invalid loop. Pipe not connected to valid sink." } return nextNode to nextFlow } var pipe: Pair<PipeSegment, Direction> = nodes.getValue(start).let { it to it.flow.first } do { add(pipe.first) pipe = pipe.flow() if (size > nodes.size) error("Loop not detected.") } while (pipe.first.location != start) } /** How many points in the maze are fully contained inside the [loop]. Uses the shoelace formula. */ val loopVolume: Long = loop.map { it.location }.polygonArea(includingPerimeter = false) } /** Parse the [input] and recreate the [PipeMaze]. */ private fun parseInput(input: String): PipeMaze = parse { lateinit var startPoint: Point fun parseNode(x: Int, y: Int, value: Char) = PipeSegment( location = Point(x, y), flow = when (value) { // It is relevant that the Up direction is first, where applicable. '|' -> Up to Down '-' -> Left to Right 'L' -> Up to Right 'J' -> Up to Left '7' -> Down to Left 'F' -> Down to Right else -> error("Unknown pipe type: $value.") }, ) val rows = input.lines() require(rows.all { it.length == rows.first().length }) { "Map not a perfect rectangle." } val pipes = rows .asReversed() .asSequence() .flatMapIndexed { y: Int, line: String -> line.mapIndexed { x, c -> Triple(x, y, c) } } .onEach { (x, y, c) -> if (c == 'S') startPoint = Point(x, y) } .filterNot { it.third in ".S" } .map { (x, y, c) -> parseNode(x, y, c) } .associateBy { it.location } val startPipe = listOf(Up, Down, Left, Right) .filter { direction -> pipes[startPoint.move(direction)]?.redirectFlow(direction.opposite) != null } .also { require(it.size == 2) { "Cannot determine starting pipe type." } } .let { (i, o) -> PipeSegment(startPoint, i to o) } PipeMaze( nodes = pipes.plus(startPoint to startPipe), start = startPoint, ) } override fun partOne(input: String) = parseInput(input).loop.size / 2 override fun partTwo(input: String) = parseInput(input).loopVolume }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,617
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountPrimes.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 CountPrimesStrategy { operator fun invoke(n: Int): Int } class CountPrimesBrutForce : CountPrimesStrategy { override operator fun invoke(n: Int): Int { val notPrime = BooleanArray(n) var count = 0 for (i in 2 until n) { if (!notPrime[i]) { count++ var j = 2 while (i * j < n) { notPrime[i * j] = true j++ } } } return count } } class CountPrimesTimeComplexity : CountPrimesStrategy { override operator fun invoke(n: Int): Int { if (n < 2) return 0 val nonPrime = BooleanArray(n) nonPrime[1] = true var numNonPrimes = 1 for (i in 2 until n) { // Complexity: O(n) if (nonPrime[i]) continue var j = i * 2 // Complexity: O(log(log(n))) while (j < n) { if (!nonPrime[j]) { nonPrime[j] = true numNonPrimes++ } j += i } } return n - 1 - numNonPrimes } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,797
kotlab
Apache License 2.0
src/main/kotlin/Day2Problem2.kt
hbandi188
434,551,848
false
null
fun main() { Day2Problem1.solve() } object Day2Problem1 { fun solve() { val instructions = getInput() val start = State(distance = 0, depth = 0) val end = instructions.fold(start) { state, instruction -> instruction.applyToState(state) } println("Result: ${end.distance * end.depth}") } private fun getInput(): List<Instruction> = readInput2().mapNotNull { (code, magnitude) -> when (code) { "forward" -> Forward(magnitude) "up" -> Up(magnitude) "down" -> Down(magnitude) else -> null } } private sealed class Instruction(protected val magnitude: Int) { abstract fun applyToState(state: State): State } private class Forward(magnitude: Int) : Instruction(magnitude) { override fun applyToState(state: State) = state.copy(distance = state.distance + magnitude) } private class Up(magnitude: Int) : Instruction(magnitude) { override fun applyToState(state: State) = state.copy(depth = state.depth - magnitude) } private class Down(magnitude: Int) : Instruction(magnitude) { override fun applyToState(state: State) = state.copy(depth = state.depth + magnitude) } private data class State(val distance: Long, val depth: Long) }
0
Kotlin
0
0
d33605a7ccb3dc049bef4feba16c45c936a349cf
1,315
adventofcode-2021
Creative Commons Zero v1.0 Universal
src/Day10.kt
kmakma
574,238,598
false
null
fun main() { /** * cathode-ray tube screen and simple CPU */ class CRT { var cycle = 0 var register = 1 var row = mutableListOf<Char>() fun exec(op: String) { doCycle() if ("noop" == op) return doCycle() register += op.split(" ")[1].toInt() } private fun doCycle() { cycle++ drawPixel() } private fun drawPixel() { val idx = row.size if (idx >= register - 1 && idx <= register + 1) row.add('#') else row.add('.') if (cycle % 40 == 0) { println(row.joinToString(" ")) // a bit easier to read with spaces row.clear() } } } fun part1(input: List<String>): Int { val signals = mutableListOf<Int>() var register = 1 var cycle = 0 input.forEach { line -> if ("noop" == line) { cycle++ if ((cycle - 20) % 40 == 0) signals.add(cycle * register) return@forEach } cycle++ if ((cycle - 20) % 40 == 0) signals.add(cycle * register) cycle++ if ((cycle - 20) % 40 == 0) signals.add(cycle * register) register += line.split(" ")[1].toInt() } return signals.sum() } fun part2(input: List<String>): Int { val crt = CRT() input.forEach { line -> crt.exec(line) } return 0 } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
1,686
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Day01.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day01(private val calibrationDocument: List<String>) { private val digitMap = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9", ) private fun filterDigits(str: String, withWords: Boolean): String { if (!withWords) { return str.filter { it.isDigit() } } return buildString { for (i in str.indices) { if (str[i].isDigit()) { append(str[i]) continue } val remainder = str.substring(i) for ((word, digit) in digitMap) { if (remainder.startsWith(word)) { append(digit) break } } } } } private fun solve(withWords: Boolean) = calibrationDocument .map { filterDigits(it, withWords) } .map { it.first().toString() + it.last().toString() } .sumOf { it.toInt() } fun solvePart1() = solve(withWords = false) fun solvePart2() = solve(withWords = true) }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
1,280
advent-2023
MIT License
src/main/kotlin/com/kevinschreuder/adventofcode/days/Day4.kt
TheCoati
435,561,957
false
{"Kotlin": 15259}
package com.kevinschreuder.adventofcode.days import com.kevinschreuder.adventofcode.FileInput import kotlin.collections.ArrayList /** * Day 4: Giant Squid * @see <a href="https://adventofcode.com/2021/day/4">Advent of code</a> */ class Day4 : Day { private val input = FileInput("day4") @Override override fun title(): String { return "Day 4 - Giant Squid" } @Override override fun input(): FileInput { return this.input } @Override override fun part1(input: FileInput): String { val values = input[0].split(",") val clone = input.toMutableList() clone.removeFirst() clone.removeIf { it == "" } val cards = clone.chunked(5).map { it -> it.map { it.trim().split("\\s+".toRegex()) } } for (i in values.indices) { for (card in cards) { val drawn = values.subList(0, i + 1) for (row in card.indices) { val horizontal = card[row] // Horizontal Match if (drawn.containsAll(horizontal)) { return this.sum(card, drawn, values[i]) } // Rotate matrix 90 degrees val vertical = ArrayList<String>() for (k in 0 until card[row].size) { vertical.add(card[k][row]) } // Vertical Match if (drawn.containsAll(vertical)) { return this.sum(card, drawn, values[i]) } } } } return "No result found" } @Override override fun part2(input: FileInput): String { val values = input[0].split(",") val clone = input.toMutableList() clone.removeFirst() clone.removeIf { it == "" } var cards = clone.chunked(5).map { it -> it.map { it.trim().split("\\s+".toRegex()) } } for (i in values.indices) { for (card in cards) { val drawn = values.subList(0, i + 1) for (row in card.indices) { val horizontal = card[row] // Horizontal Match if (drawn.containsAll(horizontal)) { if (cards.size == 1) { return this.sum(cards[0], drawn, values[i]) } cards = cards.filter { it != card } break } // Rotate matrix 90 degrees val vertical = ArrayList<String>() for (k in 0 until card[row].size) { vertical.add(card[k][row]) } // Vertical Match if (drawn.containsAll(vertical)) { if (cards.size == 1) { return this.sum(cards[0], drawn, values[i]) } cards = cards.filter { it != card } break } } } } return "No result found" } /** * Calculate the sum of the remaining numbers times the last called number */ private fun sum(card: List<List<String>>, drawn: List<String>, last: String): String { val flatten = card.flatten().filter { !drawn.contains(it) } val sum = flatten.sumOf { it.toInt() } return (last.toInt() * sum).toString() } }
0
Kotlin
0
1
a780b4cf8acf4349d64764e27fb57bac33aa31d3
3,851
Advent-of-Code-2021
Apache License 2.0
src/Ext.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
import kotlin.math.max infix fun Int.toward(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this, to, step) } infix fun Int.towardExclusiveFrom(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this + step, to, step) } fun String.sortAlphabetically() = String(toCharArray().apply { sort() }) fun <T> List<T>.orderedPairs(): Sequence<Pair<T, T>> = sequence { for (i in 0 until size - 1) { for (j in 0 until size - 1) { if (i == j) continue yield(get(i) to get(j)) } } } fun ClosedRange<Int>.intersect(other: ClosedRange<Int>) = !(start > other.endInclusive || endInclusive < other.start) fun ClosedRange<Int>.contains(other: ClosedRange<Int>) = other.start >= start && other.endInclusive <= endInclusive fun ClosedRange<Int>.count() = endInclusive - start + 1 fun Int.getMax(other: Int): Int { return max(this, other) } fun <T> MutableList<T>.swap(i: Int, j: Int) { val tmp = this[i] this[i] = this[j] this[j] = tmp } fun List<Int>.lcm() = lcmList(this)
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
1,147
advent-of-code-2022
Apache License 2.0
2015/src/main/kotlin/day9_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Graph import utils.Parser import utils.Solution import utils.mapItems import utils.triplicut fun main() { Day9Func.run() } object Day9Func : Solution<Graph<String, Int>>() { override val name = "day9" override val parser = Parser.lines.mapItems { line -> line.triplicut(" to ", " = ") }.map { list -> val bidirectional = list.flatMap { (a, b, dist) -> listOf(Triple(a, b, dist), Triple(b, a, dist)) } val edges = bidirectional.groupBy { (src, _, _) -> src }.mapValues { (_, v) -> v.map { (_, city, dist) -> dist.toInt() to city } } Graph( edgeFn = { node -> edges[node] ?: emptyList() }, weightFn = { it }, nodes = edges.keys ) } override fun part1(input: Graph<String, Int>) = input.shortestTour() override fun part2(input: Graph<String, Int>) = input.longestTour() }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
858
aoc_kotlin
MIT License
LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RegularExpressionMatching.kt
ani03sha
297,402,125
false
null
package org.redquark.tutorials.leetcode fun isMatch(s: String, p: String): Boolean { val rows = s.length val columns = p.length /// Base conditions if (rows == 0 && columns == 0) { return true } if (columns == 0) { return false } // DP array val dp = Array(rows + 1) { BooleanArray(columns + 1) } // Empty string and empty pattern are a match dp[0][0] = true // Deals with patterns with * for (i in 2 until columns + 1) { if (p[i - 1] == '*') { dp[0][i] = dp[0][i - 2] } } // For remaining characters for (i in 1 until rows + 1) { for (j in 1 until columns + 1) { if (s[i - 1] == p[j - 1] || p[j - 1] == '.') { dp[i][j] = dp[i - 1][j - 1] } else if (j > 1 && p[j - 1] == '*') { dp[i][j] = dp[i][j - 2] if (p[j - 2] == '.' || p[j - 2] == s[i - 1]) { dp[i][j] = dp[i][j] or dp[i - 1][j] } } } } return dp[rows][columns] } fun main() { println(isMatch("aa", "a")) println(isMatch("aa", "a*")) println(isMatch("ab", ".")) println(isMatch("aab", "c*a*b")) println(isMatch("mississippi", "mis*is*p*.")) println(isMatch("", ".*")) }
2
Java
40
64
67b6ebaf56ec1878289f22a0324c28b077bcd59c
1,303
RedQuarkTutorials
MIT License
src/Day01.kt
wujingwe
574,096,169
false
null
fun main() { fun total(input: String): List<Int> { return input.split("\n\n") .map { elf -> elf.lines().sumOf { it.toInt() } } } fun part1(testInput: String): Int { return total(testInput).max() } fun part2(testInput: String): Int { return total(testInput) .sortedDescending() .take(3) .fold(0) { acc, elem -> acc + elem } } val testInput = readText("../data/Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readText("../data/Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
646
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day01.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.* fun main() = Day01.run() object Day01 : Day(2016, 1) { override fun part1(): Any { val walker = Walker(Pair(0, 0), Walker.Dir.N) input.split(",") .map { it.trim() } .map { P(if (it.substring(0, 1) == "R") Turn.R else Turn.L, it.substring(1).toInt()) } .forEach { walker.turn(it.first) walker.move(it.second) } return walker.distanceTo(P(0, 0)) } override fun part2(): Any { val walker = Walker(Pair(0, 0), Walker.Dir.N) val visited = hashSetOf(walker.pos) val instructions = input.split(",") .map { it.trim() } .map { P(if (it.substring(0, 1) == "R") Turn.R else Turn.L, it.substring(1).toInt()) } .toList() outer@ for (instr in instructions) { walker.turn(instr.first) for (step in 1..instr.second) { walker.move(1) if (visited.contains(walker.pos)) break@outer else visited.add(walker.pos) } } return walker.distanceTo(P(0, 0)) } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,192
adventofkotlin
MIT License
app/src/main/kotlin/xyz/lbres/trickcalculator/ui/history/generateRandomHistory.kt
lbressler13
464,331,572
false
{"Kotlin": 360254}
package xyz.lbres.trickcalculator.ui.history import xyz.lbres.exactnumbers.exactfraction.ExactFraction import xyz.lbres.kotlinutils.general.simpleIf import xyz.lbres.kotlinutils.list.StringList import xyz.lbres.kotlinutils.random.ext.nextBoolean import xyz.lbres.trickcalculator.SharedValues.random import xyz.lbres.trickcalculator.utils.History import xyz.lbres.trickcalculator.utils.seededShuffled fun generateRandomHistory(history: History, randomness: Int?): History { return when (randomness) { 0 -> history // no randomness 1 -> history.seededShuffled() // shuffled order 2 -> shuffleHistoryValues(history) // shuffled values 3 -> createRandomizedHistory(history) ?: emptyList() // random generation else -> history } } /** * Shuffle history computations and results/errors. * Returns a list that contains all computations and results/errors, but not necessarily in their original pari. * * @return [History]: history where computations and values have been shuffled */ private fun shuffleHistoryValues(history: History): History { val computations: List<StringList> = history.map { it.computation }.seededShuffled() val values: List<Pair<ExactFraction?, String?>> = history.map { Pair(it.result, it.error) }.seededShuffled() val shuffledHistory = computations.mapIndexed { index, comp -> val valuePair = values[index] if (valuePair.first != null) { HistoryItem(comp, valuePair.first!!) } else { HistoryItem(comp, valuePair.second!!) } } return shuffledHistory } /** * Generate randomized history items based on the length of the input. * Returns null randomly or if history is empty, to indicate an "error" in retrieving history. * * @return [History]: possibly null history of generated computations, with same length as real history (if not null) */ private fun createRandomizedHistory(history: History): History? { val probabilityError = simpleIf(history.isEmpty(), 1f, 0.2f) if (random.nextBoolean(probabilityError)) { return null } return List(history.size) { generateRandomHistoryItem() } }
0
Kotlin
0
2
5569809d1754159f4b5c6b409f7f93b09f8fcdb6
2,227
trick-calculator
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem36/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem36 /** * LeetCode page: [36. Valid Sudoku](https://leetcode.com/problems/valid-sudoku/); */ class Solution { /* Complexity: * Time O(|board|) and Space O(1); */ fun isValidSudoku(board: Array<CharArray>): Boolean { return checkRows(board) && checkColumns(board) && checkSubBoxes(board) } private fun checkRows(board: Array<CharArray>): Boolean { for (row in board) { val visited = BooleanArray(9) for (value in row) { if (value == '.') continue val index = value - '1' if (visited[index]) return false else visited[index] = true } } return true } private fun checkColumns(board: Array<CharArray>): Boolean { for (column in board[0].indices) { val visited = BooleanArray(9) for (row in board.indices) { val value = board[row][column] if (value == '.') continue val index = value - '1' if (visited[index]) return false else visited[index] = true } } return true } private fun checkSubBoxes(board: Array<CharArray>): Boolean { for (row in board.indices step 3) { for (column in board[row].indices step 3) { val isValidSubBox = checkSubBox(board, row, column) if (!isValidSubBox) return false } } return true } private fun checkSubBox(board: Array<CharArray>, rowTopLeft: Int, columnTopLeft: Int): Boolean { val visited = BooleanArray(9) for (row in rowTopLeft until rowTopLeft + 3) { for (column in columnTopLeft until columnTopLeft + 3) { val value = board[row][column] if (value == '.') continue val index = value - '1' if (visited[index]) return false else visited[index] = true } } return true } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,037
hj-leetcode-kotlin
Apache License 2.0
src/chapter4/section2/ex30_QueueBasedTopologicalSort.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter4.section2 import edu.princeton.cs.algs4.Queue /** * 基于队列的拓扑排序 * 实现一种拓扑排序,使用由顶点索引的数组来保存每个顶点的入度。 * 遍历一遍所有边并使用练习4.2.7给出的Degrees类来初始化数组以及一条含有所有起点的队列。 * 然后,重复以下操作直到起点队列为空: * 1、从队列中删去一个起点并将其标记 * 2、遍历由被删除顶点指出的所有边,将所有被指向的顶点的入度减一 * 3、如果顶点的入度变为0,将它插入起点队列 */ class QueueBasedTopologicalSort(digraph: Digraph) { private var order: Queue<Int>? = null init { val cycle = DirectedCycle(digraph) // 先判断是否有环 if (!cycle.hasCycle()) { val degrees = Degrees(digraph) val inDegrees = IntArray(digraph.V) val startQueue = Queue<Int>() for (i in 0 until digraph.V) { inDegrees[i] = degrees.inDegree(i) if (degrees.inDegree(i) == 0) { startQueue.enqueue(i) } } while (!startQueue.isEmpty) { // 从起点队列中删除一个起点 val s = startQueue.dequeue() if (order == null) { order = Queue<Int>() } order!!.enqueue(s) // 与起点s直接相连的顶点v入度减一 digraph.adj(s).forEach { v -> inDegrees[v]-- if (inDegrees[v] == 0) { startQueue.enqueue(v) } } } } } /** * G是有向无环图吗 */ fun isDAG(): Boolean { return order != null } /** * 拓扑有序的所有顶点 */ fun order(): Iterable<Int>? { return order } } fun main() { val symbolDigraph = getJobsSymbolDigraph() val digraph = symbolDigraph.G() val topological = QueueBasedTopologicalSort(digraph) if (topological.isDAG()) { topological.order()!!.forEach { println(symbolDigraph.name(it)) } } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,247
Algorithms-4th-Edition-in-Kotlin
MIT License
src/test/kotlin/com/dambra/adventofcode2018/day12/GrowingPlants.kt
pauldambra
159,939,178
false
null
package com.dambra.adventofcode2018.day12 import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class GrowingPlants { private val exampleInput = """initial state: #..#.#..##......###...### ...## => # ..#.. => # .#... => # .#.#. => # .#.## => # .##.. => # .#### => # #.#.# => # #.### => # ##.#. => # ##.## => # ###.. => # ###.# => # ####. => #""".trimIndent() @Test fun `generation zero has the initial state`() { val genZero = Plants(exampleInput).generation(0) assertThat(genZero).isEqualTo("#..#.#..##......###...###") } @Test fun `generation zero can read initial state from other input too`() { val genZero = Plants( """initial state: ####.#..##......###...### ...## => # ..#.. => # .#... => # .#.#. => # .#.## => # .##.. => # .#### => # #.#.# => # #.### => # ##.#. => # ##.## => # ###.. => # ###.# => # ####. => #""".trimIndent() ).generation(0) assertThat(genZero).isEqualTo("####.#..##......###...###") } @Test fun `can apply rules to generate generation 1`() { val genOne = Plants(exampleInput).generation(1) assertThat(genOne).isNotEqualTo("#..#.#..##......###...###") assertThat(genOne).isEqualTo("#...#....#.....#..#..#..#") } @Test fun `can map a very simple generation`() { val genOne = Plants(""" initial state: #.. ..#.. => . """.trimIndent()).generation(1) assertThat(genOne).isEqualTo("...") } @Test fun `can map another very simple generation`() { val genOne = Plants(""" initial state: #..###. ..#.. => # .#.#. => # """.trimIndent()).generation(1) assertThat(genOne).isEqualTo("#....#.") } } class Plants(instructions: String) { private val initialState: String private val rules: Map<String, String> init { val lines = instructions.split("\n") initialState = lines.first().split(": ").last() rules = lines.drop(1) .filterNot { it.isEmpty() } .map { it.split(" => ") } .map { it.first() to it.last() } .toMap() println(rules) } fun generation(i: Int): String { if (i == 0) return initialState val letters = toLetters(initialState).toMutableList() println("letters: $letters") letters.forEachIndexed { pot, letter -> val a = letterAt(letters, pot - 2) val b = letterAt(letters, pot - 1) val c = letterAt(letters, pot + 1) val d = letterAt(letters, pot + 2) val candidate = "$a$b$letter$c$d" if (pot == 4) { println(candidate) } if (rules.containsKey(candidate)) { println("matched rule $candidate at pot $pot which says change to ${rules[candidate]}") letters[pot] = rules[candidate]!! } else { letters[pot] = "." } println("index $pot changed from $letter to ${letters[pot]}") } println("finished as $letters") return letters.joinToString("") } private fun letterAt(letters: List<String>, index: Int): String { return when { index < 0 -> return "." index > letters.size - 1 -> return "." else -> letters[index] } } //this split makes empty head and tail private fun toLetters(s: String) = s.split("").drop(1).dropLast(1) }
0
Kotlin
0
1
7d11bb8a07fb156dc92322e06e76e4ecf8402d1d
3,596
adventofcode2018
The Unlicense
src/main/kotlin/GiveDirections.kt
sam-hoodie
534,831,633
false
{"Kotlin": 43732}
fun printDirections() { println("To get the directions to commands for these genres, type: ") println(" 0: Names Information") println(" 1: Age and Gender Information") println(" 2: Term Information") println(" 3: Current Legislator Information") print(" > ") when (readLine().toString().toInt()) { 0 -> printDirectionsNames() 1 -> printAgeAndGenderDirections() 2 -> printTermInfoDirections() 3 -> printDirectionsCurrent() } println(" If you want to exit the directions menu, enter 0. If you want to restart, enter 1") print(" > ") when (readLine().toString().toInt()) { 0 -> return 1 -> printDirections() else -> println("Invalid Input") } } fun printDirectionsCurrent() { println(" To get the commands for information on current congressmen in specified states, type: ") println(" 0: Get serving congressmen from a specified state") println(" 1: Get serving senate members from a specified state") println(" 2: Get serving house members from a specified state") print(" > ") when (readLine().toString().toInt()) { 0 -> println(" Type the command: -get congress.(serving/historic/all).current.(any state name not case sensitive)") 1 -> println(" Type the command: -get senate.(serving/historic/all).current.(any state name not case sensitive)") 2 -> println(" Type the command: -get house.(serving/historic/all).current.(any state name not case sensitive)") else -> println(" Invalid input") } } fun printDirectionsNames() { println(" To get the commands for information on congressmen names, type: ") println(" 0: Get shortest first name") println(" 1: Get shortest last name") println(" 2: Get longest first name") println(" 3: Get longest last name") print(" > ") when (readLine().toString().toInt()) { 0 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).names.shortest.first") 1 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).names.shortest.last") 2 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).names.longest.first") 3 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).names.longest.last") else -> println(" Invalid input") } } fun printAgeAndGenderDirections() { println(" To get the age/gender commands, type: ") println(" 0: Get the youngest congressman") println(" 1: Get the oldest congressman") println(" 2: get the most common gender of the congressmen") print(" > ") when (readLine().toString().toInt()) { 0 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).age.youngest") 1 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).age.oldest") 2 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).gender.prevalent") else -> println(" Invalid input") } } fun printTermInfoDirections() { println(" To get the term information commands, type: ") println(" 0: Get the most prevalent party") println(" 1: Get the most prevalent state") println(" 2: Get the commands for term dates") print(" > ") when (readLine().toString().toInt()) { 0 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).terms.pop.party") 1 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).terms.pop.state") 2 -> printTermDateDirections() else -> println(" Invalid input") } } fun printTermDateDirections() { println(" To get the term date information commands, type: ") println(" 0: Get the longest single term") println(" 1: Get the most time served by one person") println(" 2: Get the most individual terms served by a person") print(" > ") when (readLine().toString().toInt()) { 0 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).terms.longest_single") 1 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).terms.longest_time") 2 -> println(" Type the command: -get (congress/senate/house).(serving/historic/all).terms.most_terms") else -> println(" Invalid input") } }
0
Kotlin
0
0
9efea9f9eec55c1e61ac1cb11d3e3460f825994b
4,761
congress-challenge
Apache License 2.0
src/day01/Day01.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day01 import println import readInput fun main() { fun readSignal(input: List<String>) = input.filter { line -> line.trim().isNotEmpty() } .map(String::toInt) fun countIncreases(readSignal: List<Int>) = readSignal .windowed(2) .fold(0) { acc, next -> if (next[1] > next[0]) acc + 1 else acc } fun part1(input: List<String>): Int { return countIncreases(readSignal(input)) } fun part2(input: List<String>): Int { return countIncreases(readSignal(input).windowed(3).map { it -> it.sum() }) } val testInput = readInput("day01/Day01_test") check(part1(testInput) == 7) check(part2(testInput) == 5) val input = readInput("day01/Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
783
advent-of-code-2021
Apache License 2.0
kotlin/app/src/main/kotlin/coverick/aoc/day10/CathodeRayTube.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day10 import readResourceFile val INPUT_FILE = "cathodeRayTube-input.txt" class CRT(x:Int) { var clock: Int var pixels: ArrayList<ArrayList<Char>> val WIDTH = x init { clock = 1 pixels = ArrayList<ArrayList<Char>>() pixels.add(ArrayList<Char>()) } fun draw(sprite: Int) { val row = clock / WIDTH if(row > pixels.size -1 ){ pixels.add(ArrayList<Char>()) } val col = clock % WIDTH val isLit = col >= sprite-1 && col <= sprite+1 if(isLit){ pixels.get(row).add('#') } else { pixels.get(row).add('.') } clock++ } } class CPU(crt: CRT) { var registerValue = 1 var clock = 1 val importantCycles = setOf(20,60,100,140,180,220) val crt = crt // returns non null if during this cmd we have an important cycle needed fun execute(cmd: String): Int? { val instruction = cmd.split(" ")[0] var result: Int? = null when(instruction){ "noop" -> { clock += 1 if(clock in importantCycles){ result = registerValue * clock } crt.draw(registerValue) } "addx" -> { val value = cmd.split(" ")[1].toInt() clock += 1 if(clock in importantCycles){ result = registerValue * clock } crt.draw(registerValue) registerValue += value clock += 1 if(clock in importantCycles){ result = registerValue * clock } crt.draw(registerValue) } } return result } } fun part1(): Int { val instructions = readResourceFile(INPUT_FILE) val crt = CRT(40) val cpu = CPU(crt) var sum = 0 for(cmd in instructions){ val res = cpu.execute(cmd) if(res != null){ sum += res } } return sum } fun part2(): CRT { val instructions = readResourceFile(INPUT_FILE) val crt = CRT(40) val cpu = CPU(crt) instructions.forEach{cpu.execute(it)} return crt } fun solution(){ println("Cathode-Ray Tube Solution Part 1 Solution ${part1()}") println("Cathode-Ray Tube Solution Part 2 Solution") val part2 = part2() for(row in part2.pixels){ println("\t${row.joinToString("")}") } }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
2,518
adventofcode2022
Apache License 2.0
src/main/kotlin/descriptive/Descriptive.kt
widi-nugroho
280,354,028
false
null
package descriptive import java.util.* import kotlin.math.floor import kotlin.math.sqrt object Descriptive { fun mean (a:List<Double>):Double{ var res=0.0 for (i in a){ res+=i } return res/a.size } fun median(a:List<Double>):Double{ val sorted=a.sorted() if (sorted.size%2==0){ val i1=sorted.size/2 val i2=i1-1 return (sorted[i1]+sorted[i2])/2 }else{ val i= floor((sorted.size/2).toDouble()).toInt() return sorted[i] } } fun mode(a:List<Double>):Double{ val res= mutableMapOf<Double,Int>() val listnya= mutableListOf<Pair<Double,Int>>() for (i in a){ if (res.containsKey(i)){ res[i]=res[i]!!+1 }else{ res[i]=1 } } for ((k,v) in res){ var a = Pair(k,v) listnya.add(a) } listnya.sortBy { it.second } return listnya.last().first } fun varians(a:List<Double>):Double{ val mean= mean(a) var difftotal=0.0 for (i in a){ var diff=i-mean difftotal+=diff*diff } var res=difftotal/a.size return res } fun standardDeviaton(a:List<Double>):Double{ return(sqrt(varians(a))) } } fun main(){ var a=mutableListOf<Double>(5.0,2.0,2.0,2.0,7.0,4.0,1.0) println(a.sorted()) println(Descriptive.median(a)) println(Descriptive.mode(a)) println(Descriptive.varians(a)) println(Descriptive.standardDeviaton(a)) var c=Random(10) println(c) }
0
Kotlin
0
0
a1166092e50303dcd6da9ee3146696c64f6d1bcf
1,663
kotlin-statistics
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1456/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1456 /** * LeetCode page: [1456. Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the length of s; */ fun maxVowels(s: String, k: Int): Int { var maxVowels = 0 slidingWindow(s, k) { windowVowels -> if (maxVowels < windowVowels) { maxVowels = windowVowels } } return maxVowels } private fun slidingWindow( s: String, windowSize: Int, onEachWindow: (numVowels: Int) -> Unit ) { val vowels = charArrayOf('a', 'e', 'i', 'o', 'u') var windowVowels = 0 // Update the vowels count for the first window and call onEachWindow for (index in 0 until windowSize) { val char = s[index] if (char in vowels) { windowVowels++ } } onEachWindow(windowVowels) /* Slide the window, update the vowels count and call onEachWindow for each window, until reach * the end of s. */ for (windowEnd in windowSize until s.length) { val newChar = s[windowEnd] if (newChar in vowels) { windowVowels++ } val popChar = s[windowEnd - windowSize] if (popChar in vowels) { windowVowels-- } onEachWindow(windowVowels) } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,591
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/twentytwenty/Day8.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
data class Instruction(val operation: String, val value: Int){ var seen = false } fun main() { val run = readInput().run() println("part 1: ${run.first}") readInput().forEachIndexed { index, _ -> val output = readInput().run(index) if (!output.second) { println("part 2: ${output.first}") return } } } private fun readInput() = {}.javaClass.getResource("/twentytwenty/input8.txt").readText().lines() .map { Instruction(it.split(" ")[0], it.split(" ")[1].toInt()) } fun List<Instruction>.run(index: Int = -1): Pair<Int, Boolean> { var (acc, pos) = 0 to 0 while (!this[pos].seen) { var command = this[pos].operation if (index == pos) { command = when (command) { "nop" -> "jmp" "jmp" -> "nop" else -> "acc" } } when (command) { "jmp" -> pos += this[pos].value "acc" -> { acc += this[pos].value pos++ } "nop" -> pos++ } if (pos == this.size) return acc to false } return acc to true }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
1,181
aoc202xkotlin
The Unlicense
src/main/kotlin/com/colinodell/advent2021/Day17.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 import kotlin.math.abs class Day17(input: String) { private val targetArea: Region init { "target area: x=(-?\\d+)..(-?\\d+), y=(-?\\d+)..(-?\\d+)".toRegex().matchEntire(input)!!.groupValues.drop(1).map { it.toInt() }.let { targetArea = Region(Vector2(it[0], it[2]), Vector2(it[1], it[3])) } } fun solvePart1() = triangularNumber(targetArea.topLeft.y * -1 - 1) fun solvePart2() = (1..targetArea.bottomRight.x).cartesianProduct(targetArea.topLeft.y..abs(targetArea.topLeft.y)) .map { Vector2(it.first, it.second) } .count { v -> fire(v).first { it in targetArea || missed(targetArea, it) } in targetArea } private fun fire(initialVelocity: Vector2) = sequence { var currentPosition = Vector2(0, 0) var currentVelocity = initialVelocity while (true) { currentPosition += currentVelocity currentVelocity += Vector2( if (currentVelocity.x > 0) -1 else if (currentVelocity.x < 0) 1 else 0, -1 ) yield (currentPosition) } } private fun missed(targetArea: Region, position: Vector2): Boolean { return position.x > targetArea.bottomRight.x || position.y < targetArea.topLeft.y } // Calculate the triangular number for n (see https://oeis.org/A000217) private fun triangularNumber(n: Int) = (n * (n + 1)) / 2 private fun <T, U> Iterable<T>.cartesianProduct(other: Iterable<U>): Iterable<Pair<T, U>> { return flatMap { left -> other.map { right -> left to right } } } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
1,635
advent-2021
Apache License 2.0
Retos/Reto #4 - PRIMO, FIBONACCI Y PAR [Media]/kotlin/IsmaelMatiz.kts
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}
/* * Escribe un programa que, dado un número, compruebe y muestre si es primo, * fibonacci y par. * Ejemplos: * - Con el número 2, nos dirá: "2 es primo, fibonacci y es par" * - Con el número 7, nos dirá: "7 es primo, no es fibonacci y es impar" */ var num = 89 var result = "$num " result += if (checkPrime(num)) "es primo," else "no es primo," result += if (checkFibonacci(num)) " fibonacci y " else "no es fibonacci y " result += if (checkEvenNum(num)) "es par" else "es impar" println(result) fun checkPrime(numToBeChecked: Int): Boolean { if(numToBeChecked <= 0) { println("Ingrese un numero valido") return false } var primo: Boolean = true for (i in 2..numToBeChecked){ if(i == numToBeChecked) continue if (numToBeChecked % i == 0) { primo = false break } } return primo } fun checkFibonacci(numToBeChecked: Int): Boolean{ var fibonacci: Boolean = true var pastFibonacci = 1 var tempFibonacci = 0 var currentFibonacci = 1 while ( currentFibonacci <= numToBeChecked){ if (currentFibonacci == numToBeChecked){ fibonacci = true break }else{ fibonacci = false } tempFibonacci = currentFibonacci currentFibonacci = pastFibonacci + currentFibonacci pastFibonacci = tempFibonacci } return fibonacci } fun checkEvenNum(numToBeChecked: Int): Boolean{ return if (numToBeChecked % 2 == 0) true else false }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
1,534
retos-programacion-2023
Apache License 2.0
src/Day06.kt
haraldsperre
572,671,018
false
{"Kotlin": 17302}
fun main() { fun getFirstDistinctSubSequence(input: String, length: Int): Int { for (i in length..input.length) { if (input.subSequence(i - length, i).toSet().size == length) { return i } } return -1 } fun part1(input: String): Int { return getFirstDistinctSubSequence(input, 4) } fun part2(input: String): Int { return getFirstDistinctSubSequence(input, 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test").first() check(part1(testInput) == 5) check(part2(testInput) == 23) val input = readInput("Day06").first() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c4224fd73a52a2c9b218556c169c129cf21ea415
759
advent-of-code-2022
Apache License 2.0
calendar/day13/Day13.kt
starkwan
573,066,100
false
{"Kotlin": 43097}
package day13 import Day import Lines import kotlin.math.sign class Day13 : Day() { override fun part1(input: Lines): Any { return input.windowed(2, 3) .map { isRightOrder(parse(it[0]), parse(it[1])) >= 0 } .mapIndexed { i, isRightOrder -> if (isRightOrder) i + 1 else 0 } .sum() } override fun part2(input: Lines): Any { val packets = input.filter { it.isNotEmpty() }.map { parse(it) }.toMutableList() val divider1 = parse("[[2]]").also { packets.add(it) } val divider2 = parse("[[6]]").also { packets.add(it) } return packets.sortedWith { left, right -> isRightOrder(right, left) } .withIndex() .filter { it.value === divider1 || it.value === divider2 } .let { (it[0].index + 1) * (it[1].index + 1) } } private fun parse(line: String): Content { val rootContent = Content() var currentContent: Content = rootContent val intCache = mutableListOf<Char>() for (char in line.toList()) { if (char == '[') { val newContent = Content() newContent.parent = currentContent currentContent.addContent(newContent) currentContent = newContent } else if (char.isDigit()) { intCache.add(char) } else if (char == ',' || char == ']') { if (intCache.isNotEmpty()) { val intValue = intCache.joinToString("").toInt() currentContent.addContent(Content().setInt(intValue)) intCache.clear() } if (char == ']') { if (currentContent.listValue == null) { currentContent.listValue = mutableListOf() } currentContent = currentContent.parent!! } } else { error("invalid char") } } return rootContent.listValue!!.first() } private fun isRightOrder(left: Content, right: Content): Int { if (left.isInt() && right.isInt()) { return (right.intValue!! - left.intValue!!).sign } else if (!left.isInt() && right.isInt()) { return isRightOrder(left, Content().addContent(right)) } else if (left.isInt() && !right.isInt()) { return isRightOrder(Content().addContent(left), right) } else { for (i in 0 until minOf(left.listValue!!.size, right.listValue!!.size)) { val isRightOrder = isRightOrder(left.listValue!![i], right.listValue!![i]) if (isRightOrder != 0) { return isRightOrder } } return (right.listValue!!.size - left.listValue!!.size).sign } } class Content { var parent: Content? = null var intValue: Int? = null var listValue: MutableList<Content>? = null fun isInt(): Boolean { return intValue != null } fun setInt(value: Int): Content { if (listValue != null) { error("Already set list value") } intValue = value return this } fun addContent(content: Content): Content { if (intValue != null) { error("Already set int value") } listValue = (listValue ?: mutableListOf()).apply { this.add(content) } return this } } }
0
Kotlin
0
0
13fb66c6b98d452e0ebfc5440b0cd283f8b7c352
3,557
advent-of-kotlin-2022
Apache License 2.0
src/Day06.kt
VadimB95
574,449,732
false
{"Kotlin": 19743}
import java.util.* fun main() { // test if implementation meets criteria from the description, like: val testInput = readInputAsString("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInputAsString("Day06") println(part1(input)) println(part2(input)) } private fun part1(input: String): Int { return scanForMarker(input, 4) } private fun part2(input: String): Int { return scanForMarker(input, 14) } private fun scanForMarker(input: String, markerCharactersCount: Int): Int { input.scanIndexed(LinkedList<Char>()) { index, acc, c -> acc.add(c) if (acc.size > markerCharactersCount) { acc.removeFirst() } if (acc.size == markerCharactersCount && acc.distinct().size == markerCharactersCount) { return@scanForMarker index + 1 } acc } return 0 }
0
Kotlin
0
0
3634d1d95acd62b8688b20a74d0b19d516336629
908
aoc-2022
Apache License 2.0