path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/be/brammeerten/graphs/AStar.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.graphs import java.util.function.Function object AStar { fun <K, V> findShortestPath(graph: Graph<K, V>, start: K, end: K, h: Function<Pair<K, K>, Double>, cache: HashMap<Pair<K, K>, List<Node<K, V>>?>? = null): List<Node<K, V>>? { // Check cache val cached = cache?.get(start to end) if (cached != null) return cached // Traverse graph val prevs = traverse(graph, h, start, end) // Calculate path val result = toPath(end, start, prevs, graph) // Store in cache if (cache != null) { cache[start to end] = result cache[end to start] = result?.reversed() } return result } private fun <K, V> traverse(graph: Graph<K, V>, h: Function<Pair<K, K>, Double>, start: K, end: K): HashMap<K, K?> { val unvisited = HashSet<K>(graph.nodes.keys) val prevs = HashMap<K, K?>() val gScore = HashMap<K, Int>() graph.nodes.values.forEach { gScore[it.key] = Int.MAX_VALUE } gScore[start] = 0 val fScore = HashMap<K, Double>() graph.nodes.values.forEach { fScore[it.key] = Double.MAX_VALUE } fScore[start] = h.apply(start to end) while (unvisited.isNotEmpty()) { val cur = graph.nodes.values .filter { unvisited.contains(it.key) } .minBy { fScore[it.key]!!} if (cur.key == end) return prevs unvisited.remove(cur.key) cur.vertices.forEach { vertex -> val d = gScore[cur.key]!! + vertex.weight if (d < gScore[vertex.to]!!) { gScore[vertex.to] = d val hResult = h.apply(vertex.to to end) fScore[vertex.to] = d + hResult prevs[vertex.to] = cur.key } } } return prevs } private fun <K, V> toPath(end: K, start: K, prevs: HashMap<K, K?>, graph: Graph<K, V>): List<Node<K, V>>? { val path = ArrayList<K>() var curr: K? = end while (curr != null && curr != start) { path.add(curr) curr = prevs[curr] } if (curr == null) return null path.add(curr) return path.map { graph.nodes[it]!! }.reversed() } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
2,411
Advent-of-Code
MIT License
atcoder/arc154/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc154 private fun solve(): Boolean { val (_, a, b) = List(3) { readInts() } if (a == b) return true if (b.toSet().size == 1) return b[0] in a val want = b.filterIndexed { i, it -> it != b.getCycled(i + 1) } if (want.size == b.size) return false for (aShifted in a.allShifts()) { var k = 0 for (x in aShifted) if (want[k] == x) if (++k == want.size) return true } return false } fun main() = repeat(readInt()) { println(solve().iif("Yes", "No")) } private fun <T> List<T>.getCycled(index: Int) = getOrElse(index) { get(if (index >= 0) index % size else lastIndex - index.inv() % size) } private fun <T> List<T>.shifted(shift: Int) = drop(shift) + take(shift) private fun <T> List<T>.allShifts() = List(size) { shifted(it) } private fun <T> Boolean.iif(onTrue: T, onFalse: T) = if (this) onTrue else onFalse private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,022
competitions
The Unlicense
src/day11/Day11.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day11 import day11.Monkey.Companion.parseMonkeys import readInput import java.util.ArrayDeque import java.util.Queue data class Monkey( val id: MonkeyID, val holdingItems: Queue<Item>, val itemOperation: (Item) -> Unit, val rule: ThrowRule ) { fun processItems(divideByThree: Boolean, keepInCheck: Long = 0, inspectCallback: () -> Unit): List<ItemOperation> { return buildList { while (holdingItems.isNotEmpty()) { val item = holdingItems.poll() if (keepInCheck > 0) { item.worryLevel %= keepInCheck } itemOperation(item) if (divideByThree) { item.worryLevel /= 3 } add(ItemOperation(item, rule.getMonkeyID(item.worryLevel))) inspectCallback() } } } companion object { private val monkeyIDRegex = Regex("day11.Monkey (\\d+):") private val itemRegex = Regex("""Starting items: ((\d+)(, (\d+))*)""") private val itemOperationRegex = Regex("""Operation: new = old ([+*]) (\d+|old)""") private val conditionRegex = Regex("Test: divisible by (\\d+)") private val ifTrueRegex = Regex("If true: throw to monkey (\\d+)") private val ifFalseRegex = Regex("If false: throw to monkey (\\d+)") private fun String.match(regex: Regex): MatchResult { return regex.matchEntire(this.trim())!! } private fun Queue<String>.parseMonkey(): Monkey { val id = poll().match(monkeyIDRegex).groupValues[1].toInt() val itemsMatch = poll().match(itemRegex).groupValues[1] val items = itemsMatch.split(", ").map { Item(it.toLong()) }.toCollection(ArrayDeque()) val itemOperation = poll().match(itemOperationRegex).groupValues.let { (_, op, value) -> val number = value.toIntOrNull() when (op) { "+" -> { if (number == null) { check(value == "old") { "Invalid value: $value" } AddToOld } else { AddTo(number) } } "*" -> { if (number == null) { check(value == "old") { "Invalid value: $value" } MultiplyByOld } else { MultiplyBy(number) } } else -> throw IllegalArgumentException("Unknown operation: $op") } } val rule = ThrowRule( poll().match(conditionRegex).groupValues[1].toLong(), MonkeyID(poll().match(ifTrueRegex).groupValues[1].toInt()), MonkeyID(poll().match(ifFalseRegex).groupValues[1].toInt()) ) return Monkey(MonkeyID(id), items, itemOperation, rule) } fun Queue<String>.parseMonkeys(): List<Monkey> { return buildList { while (this@parseMonkeys.isNotEmpty()) { val monkey = parseMonkey() add(monkey) } } } } } data class MultiplyBy(val value: Int): (Item) -> Unit { override fun invoke(p1: Item) { p1.worryLevel *= value } } data class AddTo(val value: Int): (Item) -> Unit { override fun invoke(p1: Item) { p1.worryLevel += value } } object MultiplyByOld: (Item) -> Unit { override fun invoke(p1: Item) { p1.worryLevel *= p1.worryLevel } override fun toString(): String { return "Self multiply" } } object AddToOld: (Item) -> Unit { override fun invoke(p1: Item) { p1.worryLevel += p1.worryLevel } override fun toString(): String { return "Self add" } } data class ItemOperation(val item: Item, val toMonkey: MonkeyID) data class ThrowRule(val modulo: Long, val ifTrue: MonkeyID, val ifFalse: MonkeyID) { fun getMonkeyID(worryLevel: Long): MonkeyID { return if (worryLevel % modulo == 0L) ifTrue else ifFalse } } @JvmInline value class MonkeyID(val id: Int) data class Item(var worryLevel: Long) fun lowestCommonMultiple(vararg values: Long): Long { var result = 1L while (true) { if (values.all { result % it == 0L }) { return result } result++ } } fun main() { fun part1(input: List<String>): Int { val monkeys = input.toCollection(ArrayDeque()).parseMonkeys() val counts = mutableMapOf<MonkeyID, Int>() monkeys.forEach { counts[it.id] = 0 } repeat(20) { monkeys.forEach { monkey -> val itemOperations = monkey.processItems(true) { counts[monkey.id] = counts[monkey.id]!! + 1 } itemOperations.forEach { (item, toMonkey) -> monkeys[toMonkey.id].holdingItems.add(item) } } } return counts.entries.toList().sortedByDescending { it.value }.take(2).let { (first, second) -> first.value * second.value } } fun part2(input: List<String>): Long { val monkeys = input.toCollection(ArrayDeque()).parseMonkeys() val counts = mutableMapOf<MonkeyID, Int>() monkeys.forEach { counts[it.id] = 0 } val lcm = lowestCommonMultiple(*monkeys.map { it.rule.modulo }.toLongArray()) repeat(10000) { val it = it + 1 monkeys.forEach { monkey -> val itemOperations = monkey.processItems(false, lcm) { counts[monkey.id] = counts[monkey.id]!! + 1 } itemOperations.forEach { (item, toMonkey) -> monkeys[toMonkey.id].holdingItems.add(item) } } // if (it % 1000 == 0 || it == 1 || it == 20) { // println("Iteration $it") // println(counts) // } } return counts.entries.toList().sortedByDescending { it.value }.take(2).let { (first, second) -> first.value.toLong() * second.value.toLong() } } val testInput = readInput(11, true) part1(testInput).let { check(it == 10605) { println(it) } } part2(testInput).let { check(it == 2713310158) { println(it) } } val input = readInput(11) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
6,481
Advent-Of-Code
Apache License 2.0
Insert_Interval.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import kotlin.math.max import kotlin.math.min class Solution { fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { val result = ArrayList<IntArray>() var i = 0 while (i < intervals.size && intervals[i][1] < newInterval[0]) { result.add(intervals[i]) i++ } val insertInterval = newInterval.copyOf() while (i < intervals.size && intervals[i][0] <= newInterval[1]) { insertInterval[0] = min(insertInterval[0], intervals[i][0]) insertInterval[1] = max(insertInterval[1], intervals[i][1]) i++ } result.add(insertInterval) while (i < intervals.size) { result.add(intervals[i]) i++ } return result.toTypedArray() } } class TestCase(val intervals: Array<IntArray>, val newInterval: IntArray) fun main() { val solution = Solution() val testCases = arrayOf(TestCase(arrayOf(intArrayOf(1, 3), intArrayOf(6, 9)), intArrayOf(2, 5)), TestCase(arrayOf(intArrayOf(1, 2), intArrayOf(3, 10)), intArrayOf(12, 16)), TestCase(arrayOf(), intArrayOf(5, 7)), TestCase(arrayOf(intArrayOf(1, 5)), intArrayOf(2, 3)), TestCase(arrayOf(intArrayOf(1, 2), intArrayOf(3, 5), intArrayOf(6, 7), intArrayOf(8, 10), intArrayOf(12, 16)), intArrayOf(4, 8))) for (case in testCases) { println(solution.insert(case.intervals, case.newInterval).joinToString(" ") { it.joinToString(",") }) } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,520
leetcode
MIT License
kotlin/127.Word Ladder(单词接龙).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>Given two words (<em>beginWord</em> and <em>endWord</em>), and a dictionary&#39;s word list, find the length of shortest transformation sequence from <em>beginWord</em> to <em>endWord</em>, such that:</p> <ol> <li>Only one letter can be changed at a time.</li> <li>Each transformed word must exist in the word list. Note that <em>beginWord</em> is <em>not</em> a transformed word.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>Return 0 if there is no such transformation sequence.</li> <li>All words have the same length.</li> <li>All words contain only lowercase alphabetic characters.</li> <li>You may assume no duplicates in the word list.</li> <li>You may assume <em>beginWord</em> and <em>endWord</em> are non-empty and are not the same.</li> </ul> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>Output: </strong>5 <strong>Explanation:</strong> As one shortest transformation is &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;, return its length 5. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> beginWord = &quot;hit&quot; endWord = &quot;cog&quot; wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>Output:</strong>&nbsp;0 <strong>Explanation:</strong>&nbsp;The endWord &quot;cog&quot; is not in wordList, therefore no possible<strong>&nbsp;</strong>transformation. </pre> <ul> </ul> <p>给定两个单词(<em>beginWord&nbsp;</em>和 <em>endWord</em>)和一个字典,找到从&nbsp;<em>beginWord</em> 到&nbsp;<em>endWord</em> 的最短转换序列的长度。转换需遵循如下规则:</p> <ol> <li>每次转换只能改变一个字母。</li> <li>转换过程中的中间单词必须是字典中的单词。</li> </ol> <p><strong>说明:</strong></p> <ul> <li>如果不存在这样的转换序列,返回 0。</li> <li>所有单词具有相同的长度。</li> <li>所有单词只由小写字母组成。</li> <li>字典中不存在重复的单词。</li> <li>你可以假设 <em>beginWord</em> 和 <em>endWord </em>是非空的,且二者不相同。</li> </ul> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>输出: </strong>5 <strong>解释: </strong>一个最短转换序列是 &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;, 返回它的长度 5。 </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot; endWord = &quot;cog&quot; wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>输出:</strong>&nbsp;0 <strong>解释:</strong>&nbsp;<em>endWord</em> &quot;cog&quot; 不在字典中,所以无法进行转换。</pre> <p>给定两个单词(<em>beginWord&nbsp;</em>和 <em>endWord</em>)和一个字典,找到从&nbsp;<em>beginWord</em> 到&nbsp;<em>endWord</em> 的最短转换序列的长度。转换需遵循如下规则:</p> <ol> <li>每次转换只能改变一个字母。</li> <li>转换过程中的中间单词必须是字典中的单词。</li> </ol> <p><strong>说明:</strong></p> <ul> <li>如果不存在这样的转换序列,返回 0。</li> <li>所有单词具有相同的长度。</li> <li>所有单词只由小写字母组成。</li> <li>字典中不存在重复的单词。</li> <li>你可以假设 <em>beginWord</em> 和 <em>endWord </em>是非空的,且二者不相同。</li> </ul> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;] <strong>输出: </strong>5 <strong>解释: </strong>一个最短转换序列是 &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;, 返回它的长度 5。 </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> beginWord = &quot;hit&quot; endWord = &quot;cog&quot; wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;] <strong>输出:</strong>&nbsp;0 <strong>解释:</strong>&nbsp;<em>endWord</em> &quot;cog&quot; 不在字典中,所以无法进行转换。</pre> **/ class Solution { fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
4,818
leetcode
MIT License
src/main/kotlin/io/undefined/FriendOfAppropriateAges.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.undefined import io.utils.runTests // https://leetcode.com/problems/friends-of-appropriate-ages/ class FriendOfAppropriateAges { fun execute(input: IntArray): Int { val count = input.fold(IntArray(121)) { acc, value -> acc.apply { this[value]++ } } var result = 0 count.forEachIndexed { ageA, numberOfPeople -> for (ageB in count.indices) { if (ageA * 0.5 + 7 >= ageB) continue if (ageA < ageB) continue result += numberOfPeople * count[ageB] if (ageA == ageB) result -= numberOfPeople } } return result } fun numFriendRequests(input: IntArray): Int { val numInAge = input.fold(IntArray(121)) { acc, value -> acc.apply { this[value]++ } } val sumInAge = IntArray(121) for (i in 1..120) sumInAge[i] = numInAge[i] + sumInAge[i - 1] var result = 0 for (i in 15..120) { if (numInAge[i] == 0) continue val accum = sumInAge[i] - sumInAge[i / 2 + 7] result += accum * numInAge[i] - numInAge[i] //people will not friend request themselves, so - numInAge[i] } return result } } fun main() { runTests(listOf( intArrayOf(16, 16) to 2 )) { (input, value) -> value to FriendOfAppropriateAges().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,244
coding
MIT License
src/main/kotlin/io/github/t45k/scm/matching/algorithms/rollingHash/RollingHash.kt
T45K
255,912,849
false
null
package io.github.t45k.scm.matching.algorithms.rollingHash import io.github.t45k.scm.entity.TokenSequence import io.github.t45k.scm.matching.algorithms.StringSearchAlgorithm class RollingHash(query: TokenSequence) : StringSearchAlgorithm(query) { private val querySize: Int = query.size private val memo: List<HashedInt> private val hashedQuery: Int init { var tmp = 1.toHashable() memo = (1 until querySize) .map { tmp *= BASE tmp } .reversed() .plus(1.toHashable()) hashedQuery = calcInitial(query) } companion object { const val BASE: Int = 1_020_544_910 } override fun search(from: TokenSequence): List<Int> { if (from.size < querySize) { return emptyList() } var rollingHash: Int = calcInitial(from.take(querySize)) return listOf(rollingHash).plus( (querySize until from.size) .map { index -> rollingHash = calcWithBefore(rollingHash, from[index - querySize], from[index]) rollingHash }) .mapIndexed { index, hash -> index to hash } .filter { it.second == hashedQuery } .map { it.first } } private fun calcInitial(elements: TokenSequence) = elements .map { it.toHashable() } .mapIndexed { index, value -> value * memo[index] } .reduce { acc, i -> (acc + i) }.value private fun calcWithBefore(before: Int, old: Int, new: Int) = ((before - old * memo[0]) * BASE + new).value }
0
Kotlin
0
0
37b3ffac9bdf6e24a3fc3ae9282f3f692ec8d12d
1,663
SCM
MIT License
common/geometry/src/main/kotlin/com/curtislb/adventofcode/common/geometry/Ray.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.common.geometry import com.curtislb.adventofcode.common.number.Fraction /** * A unique representation of a ray with a given origin and direction in a 2D grid. * * @property source The origin point of the ray. * @property slope The slope of the ray, or `null` if its slope is infinite. * @property isPositive A boolean flag indicating the direction of the ray. If [slope] is finite, * this is `true` if the x-coordinates of points on the ray approach positive infinity. If [slope] * is `null`, this is `true` if the y-coordinates of points on the ray approach positive infinity. * * @constructor Creates a new instance of [Ray] with the given [source] point, [slope], and * direction indicated by [isPositive]. */ data class Ray(val source: Point, val slope: Fraction?, val isPositive: Boolean) { /** * Returns a sequence of all grid points that fall on this ray, including the [source] point, * sorted by their distance from [source]. */ fun points(): Sequence<Point> = sequence { // Calculate the change in x and y between subsequent points val sign = if (isPositive) 1 else -1 val deltaX = sign * (slope?.denominator?.toInt() ?: 0) val deltaY = sign * (slope?.numerator?.toInt() ?: 1) // Determine last coordinate values before integer overflow val lastX = when { deltaX > 0 -> Int.MAX_VALUE - (deltaX - 1) deltaX < 0 -> Int.MIN_VALUE - (deltaX + 1) else -> 0 } val lastY = when { deltaY > 0 -> Int.MAX_VALUE - (deltaY - 1) deltaY < 0 -> Int.MIN_VALUE - (deltaY + 1) else -> 0 } // Produce each point in order, starting with source var x = source.x var y = source.y while (true) { yield(Point(x, y)) // Stop producing points if either coordinate would overflow if ( deltaX > 0 && x >= lastX || deltaX < 0 && x <= lastX || deltaY > 0 && y >= lastY || deltaY < 0 && y <= lastY ) { break } x += deltaX y += deltaY } } companion object { /** * Returns the unique [Ray] defined by the given [source] point and distinct [member] point. * * @throws IllegalArgumentException If [source] and [member] are the same point. */ fun fromPoints(source: Point, member: Point): Ray { require(source != member) { "Source and member points must be distinct: $source == $member" } val slope: Fraction? val isDirectionPositive: Boolean if (source.x == member.x) { // Ray is vertical (infinite slope) slope = null isDirectionPositive = source.y < member.y } else { // Ray is not vertical (finite slope) slope = Fraction.valueOf(member.y - source.y, member.x - source.x) isDirectionPositive = source.x < member.x } return Ray(source, slope, isDirectionPositive) } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,255
AdventOfCode
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day13.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.* import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.api.zeros import org.jetbrains.kotlinx.multik.ndarray.data.get import org.jetbrains.kotlinx.multik.ndarray.operations.toList open class Part13A : PartSolution() { lateinit var positions: MutableList<Vector2i> lateinit var folds: List<Pair<Char, Int>> override fun parseInput(text: String) { val folds = mutableListOf<Pair<Char, Int>>() positions = mutableListOf() for (line in text.split("\n")) { if (line.startsWith("fold")) { val parts = line.split("=") folds.add(parts[0].last() to parts[1].toInt()) } else if (line.isNotEmpty()) { val pos = line.split(",") positions.add(Vector2i(pos[0].toInt(), pos[1].toInt())) } } this.folds = folds } override fun config() { val fold = folds.first() if (fold.first == 'x') { foldHorizontal(fold.second) } else { foldVertical(fold.second) } discardOverlaps() } fun foldHorizontal(foldingPos: Int) { for (i in positions.indices) { val pos = positions[i] if (pos.x < foldingPos) { continue } positions[i] = pos.withX(2 * foldingPos - pos.x) } } fun foldVertical(foldingPos: Int) { for (i in positions.indices) { val pos = positions[i] if (pos.y < foldingPos) { continue } positions[i] = pos.withY(2 * foldingPos - pos.y) } } fun discardOverlaps() { positions = positions.toSet().toMutableList() } override fun compute(): Int { return positions.size } override fun getExampleAnswer(): Int { return 17 } override fun getExampleInput(): String? { return """ 6,10 0,14 9,10 0,3 10,4 4,11 6,0 6,12 4,1 0,13 10,12 3,4 3,0 8,4 1,10 2,14 8,10 9,0 fold along y=7 fold along x=5 """.trimIndent() } } class Part13B : Part13A() { override fun compute(): Int { for (fold in folds) { if (fold.first == 'x') { foldHorizontal(fold.second) } else { foldVertical(fold.second) } discardOverlaps() } printPoints() return 0 } private fun printPoints() { val (width, height) = getDimension() val grid = mk.zeros<Int>(height, width) for (point in positions) { grid[point] = 1 } var output = "" for (y in 0..<grid.shape[0]) { output += "\n" + grid[y].toList().map { if (it == 0) ' ' else '#' }.joinToString(separator = "") } println(output) } private fun getDimension(): Pair<Int, Int> { val max = positions.reduce { acc, vector2i -> max(acc, vector2i) } return max.x + 1 to max.y + 1 } override fun getExampleAnswer(): Int { return 0 } } fun main() { Day(2021, 13, Part13A(), Part13B(), false) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
3,462
advent-of-code-kotlin
MIT License
src/main/kotlin/twentytwenty/DayOne.kt
philspins
318,606,184
false
null
package twentytwenty import java.io.File import java.nio.file.Paths class DayOne { private var inputList: ArrayList<Int> = ArrayList<Int>() internal var partOneAnswer: Int = 0 internal var partTwoAnswer: Int = 0 fun loadInputFile(filename: String) { val path = Paths.get("").toAbsolutePath().toString() File("$path/$filename").forEachLine { inputList.add(it.toInt()) } } private fun quickSort(input: ArrayList<Int>): ArrayList<Int> { if (input.count() < 2) { return input } val pivot = input[input.count()/2] val equal = input.filter { it == pivot } as ArrayList<Int> val less = input.filter { it < pivot } as ArrayList<Int> val greater = input.filter { it > pivot } as ArrayList<Int> return (quickSort(less) + equal + quickSort(greater)) as ArrayList<Int> } fun solvePartOne() { if (inputList.count()==0) { loadInputFile("src/data/DayOneInput.txt") } var filtered = inputList.filter { it < 2020 } var sorted = quickSort(filtered as ArrayList<Int>) loop@ for (lowVal in sorted) { for (highVal in sorted.reversed()) { if (lowVal + highVal == 2020) { partOneAnswer = lowVal * highVal break@loop } } } } fun solvePartTwo() { if (inputList.count()==0) { loadInputFile("src/data/DayOneInput.txt") } var filtered = inputList.filter { it < 2020} var sorted = quickSort(filtered as ArrayList<Int>) loop@ for(first in sorted) { for(second in sorted.filter { it != first}) { for(third in sorted.filter { it != first && it != second }) { if (first + second + third == 2020) { partTwoAnswer = first * second * third break@loop } } } } } }
0
Kotlin
0
0
138eac749657475ff93e82a5a4f667f9c249411f
2,005
adventofcode
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day20.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.y2022.data.Day20Data object Day20 { private val input = Day20Data.input private const val decryptionKey = 811589153L fun part1(): Long = findGrove(input.lines().map { it.toLong() }, 1) fun part2(): Long = findGrove(input.lines().map { it.toLong() * decryptionKey }, 10) private fun findGrove(file: List<Long>, mixTimes: Int): Long { val llfile = LinkedList(file.withIndex()) (0 until mixTimes).forEach { _ -> file.indices.forEach { i -> val node = llfile.findNode { it.index == i }!! if (node.value.value >= 0L) { node.moveForward(node.value.value % (file.size - 1).toLong()) } else { node.moveBackward(-node.value.value % (file.size - 1).toLong()) } } } val node0 = llfile.findNode { it.value == 0L }!! val after1000 = node0.skipForward(1000L) val after2000 = after1000.skipForward(1000L) val after3000 = after2000.skipForward(1000L) return after1000.value.value + after2000.value.value + after3000.value.value } private class Node<T>(val value: T) { var next: Node<T>? = null var prev: Node<T>? = null fun moveForward(n: Long) { (0 until n).forEach { _ -> val nextNext = next!!.next nextNext!!.prev = this prev!!.next = next next!!.prev = prev next!!.next = this prev = next next = nextNext } } fun moveBackward(n: Long) { (0 until n).forEach { _ -> val prevPrev = prev!!.prev prevPrev!!.next = this next!!.prev = prev prev!!.prev = this prev!!.next = next next = prev prev = prevPrev } } fun skipForward(n: Long): Node<T> { var node = this (0 until n).forEach { _ -> node = node.next!! } return node } } private class LinkedList<T>(items: Iterable<T> = emptyList()) { init { items.forEach { add(it) } } var head: Node<T>? = null private set fun add(value: T) { val node = Node(value) node.next = head ?: node node.prev = head?.prev ?: node head?.prev?.next = node head?.prev = node head = head ?: node } fun findNode(pred: (T) -> Boolean): Node<T>? = if (head == null) { null } else if (pred(head!!.value)) { head } else { var node = head!!.next while (node != head && !pred(node!!.value)) { node = node.next } if (node != head) node else null } } }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
3,046
adventofcode2022
MIT License
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day19/Day19.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2022.calendar.day19 import nl.jackploeg.aoc._2022.calendar.day19.Day19.Robot.* import javax.inject.Inject import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile import java.util.* import kotlin.math.max class Day19 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { // mine minerals fun partOne(fileName: String): Int { val input = readStringFile(fileName) return input.sumOf { line -> val tokens = Regex("\\d+").findAll(line).map { it.value.toInt() }.toList() tokens[0] * solve(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], 24) } } // mine first three blueprints // Uses a lot of memory, prefer partTwoAlt fun partTwo(fileName: String): Int { val input = readStringFile(fileName) return input.take(3).map { line -> val tokens = Regex("\\d+").findAll(line).map { it.value.toInt() }.toList() solve(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], 32) }.reduce(Int::times) } data class State( val ore: Int, val clay: Int, val obsidian: Int, val geodes: Int, val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int, val time: Int ) fun solve( oreRobotCostOre: Int, clayRobotCostOre: Int, obsidianRobotCostOre: Int, obsidianRobotCostClay: Int, geodeRobotCostOre: Int, geodeRobotCostObsidian: Int, time: Int ): Int { var maxGeodes = 0 val state = State(0, 0, 0, 0, 1, 0, 0, 0, time) val queue: Queue<State> = LinkedList() queue.add(state) val seen = mutableSetOf<State>() while (queue.isNotEmpty()) { var currentState = queue.poll() var (ore, clay, obsidian, geodes, oreRobots, clayRobots, obisidanRobots, geodeRobots, timeLeft) = currentState maxGeodes = maxOf(maxGeodes, geodes) if (timeLeft == 0) continue val maxOreRobotsNeeded = maxOf(oreRobotCostOre, clayRobotCostOre, obsidianRobotCostOre, geodeRobotCostOre) // Discard extra resources oreRobots = minOf(oreRobots, maxOreRobotsNeeded) clayRobots = minOf(clayRobots, obsidianRobotCostClay) obisidanRobots = minOf(obisidanRobots, geodeRobotCostObsidian) ore = minOf(ore, maxOreRobotsNeeded * timeLeft - oreRobots * (timeLeft - 1)) clay = minOf(clay, obsidianRobotCostClay * timeLeft - clayRobots * (timeLeft - 1)) obsidian = minOf(obsidian, geodeRobotCostObsidian * timeLeft - obisidanRobots * (timeLeft - 1)) currentState = State(ore, clay, obsidian, geodes, oreRobots, clayRobots, obisidanRobots, geodeRobots, timeLeft) if (currentState in seen) continue seen += currentState // What if we do nothing queue.add( State( ore + oreRobots, clay + clayRobots, obsidian + obisidanRobots, geodes + geodeRobots, oreRobots, clayRobots, obisidanRobots, geodeRobots, timeLeft - 1 ) ) // what if we order an Ore robot if (ore >= oreRobotCostOre) queue.add( State( ore - oreRobotCostOre + oreRobots, clay + clayRobots, obsidian + obisidanRobots, geodes + geodeRobots, oreRobots + 1, clayRobots, obisidanRobots, geodeRobots, timeLeft - 1 ) ) // what if we order a Clay robot if (ore >= clayRobotCostOre) queue.add( State( ore - clayRobotCostOre + oreRobots, clay + clayRobots, obsidian + obisidanRobots, geodes + geodeRobots, oreRobots, clayRobots + 1, obisidanRobots, geodeRobots, timeLeft - 1 ) ) // what if we order an Obsidian robot if (ore >= obsidianRobotCostOre && clay >= obsidianRobotCostClay) queue.add( State( ore - obsidianRobotCostOre + oreRobots, clay - obsidianRobotCostClay + clayRobots, obsidian + obisidanRobots, geodes + geodeRobots, oreRobots, clayRobots, obisidanRobots + 1, geodeRobots, timeLeft - 1 ) ) // what if we order a geode cracking robot if (ore >= geodeRobotCostOre && obsidian >= geodeRobotCostObsidian) queue.add( State( ore - geodeRobotCostOre + oreRobots, clay + clayRobots, obsidian - geodeRobotCostObsidian + obisidanRobots, geodes + geodeRobots, oreRobots, clayRobots, obisidanRobots, geodeRobots + 1, timeLeft - 1 ) ) } return maxGeodes } fun partTwoAlt(filename: String) = generatorFactory.forFile(filename).readAs(::blueprint) { input -> input.toList().take(3).fold(1) { acc, blueprint -> acc * maxGeode(blueprint, 32) } } private fun maxGeode(bp: Blueprint, minutes: Int): Int { var maxGeodesSoFar = 0 fun makeRobot(bs: BeachState): Int { // we're trying to move forward by making `robotToMake` // but don't bother going forward if we // (a) have too many (in the case of ore, clay, and obsidian) // (b) will never make enough (in the case of clay and obsidian) when (bs.robotToMake) { ORE -> if (bs.oreRobots >= bp.maxOre) return 0 CLAY -> if (bs.clayRobots >= bp.obsidianRobotClayCost) return 0 OBSIDIAN -> if (bs.obsidianRobots >= bp.geodeRobotObsidianCost || bs.clayRobots == 0) return 0 GEODE -> if (bs.obsidianRobots == 0) return 0 } // Reddit hyper-optimization // if we somehow managed to create nonstop geodes from our current recursion // would it even be possible to eclipse our current maximum? // if not - then this branch is dead if (bs.geodes + (bs.geodeRobots * bs.timeRemaining) + TRIANGLE_NUMBERS[bs.timeRemaining] <= maxGeodesSoFar) return 0 // since `eventually` we'll be able to build the robot we're after // we can keep track of how many minutes have passed as existing // robots mine up their resources var minutesPassed = 0 while (bs.currentTime(minutesPassed) > 0) { val currentOre = bs.currentOre(minutesPassed) val currentClay = bs.currentClay(minutesPassed) val currentObsidian = bs.currentObsidian(minutesPassed) when (bs.robotToMake) { ORE -> if (currentOre >= bp.oreRobotOreCost) { return entries.maxOf { robot -> makeRobot( bs.advanceState( minutesPassed, robot, newOreRobots = bs.oreRobots + 1, newOre = currentOre + bs.oreRobots - bp.oreRobotOreCost ) ) }.also { maxGeodesSoFar = max(maxGeodesSoFar, it) } } CLAY -> if (currentOre >= bp.clayRobotOreCost) { return entries.maxOf { robot -> makeRobot( bs.advanceState( minutesPassed, robot, newClayRobots = bs.clayRobots + 1, newOre = currentOre + bs.oreRobots - bp.clayRobotOreCost ) ) }.also { maxGeodesSoFar = max(maxGeodesSoFar, it) } } OBSIDIAN -> if (currentOre >= bp.obsidianRobotOreCost && currentClay >= bp.obsidianRobotClayCost) { return entries.maxOf { robot -> makeRobot( bs.advanceState( minutesPassed, robot, newObsidianRobots = bs.obsidianRobots + 1, newOre = currentOre + bs.oreRobots - bp.obsidianRobotOreCost, newClay = currentClay + bs.clayRobots - bp.obsidianRobotClayCost ) ) }.also { maxGeodesSoFar = max(maxGeodesSoFar, it) } } GEODE -> if (currentOre >= bp.geodeRobotOreCost && currentObsidian >= bp.geodeRobotObsidianCost) { return entries.maxOf { robot -> makeRobot( bs.advanceState( minutesPassed, robot, newGeodeRobots = bs.geodeRobots + 1, newOre = currentOre + bs.oreRobots - bp.geodeRobotOreCost, newObsidian = currentObsidian + bs.obsidianRobots - bp.geodeRobotObsidianCost ) ) }.also { maxGeodesSoFar = max(maxGeodesSoFar, it) } } } minutesPassed++ } return bs.geodes + (minutesPassed * bs.geodeRobots) } return entries.maxOf { robot -> makeRobot(BeachState(minutes, robot, 1, 0, 0, 0, 0, 0, 0, 0)) } } private fun blueprint(line: String): Blueprint { val parts = line.split(" ") val id = parts[1].dropLast(1).toInt() val oreRobotOreCost = parts[6].toInt() val clayRobotOreCost = parts[12].toInt() val obsidianRobotOreCost = parts[18].toInt() val obsidianRobotClayCost = parts[21].toInt() val geodeRobotOreCost = parts[27].toInt() val geodeRobotObsidianCost = parts[30].toInt() return Blueprint( id, oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost ) } data class Blueprint( val id: Int, val oreRobotOreCost: Int, val clayRobotOreCost: Int, val obsidianRobotOreCost: Int, val obsidianRobotClayCost: Int, val geodeRobotOreCost: Int, val geodeRobotObsidianCost: Int ) { val maxOre = maxOf(oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost) } enum class Robot { ORE, CLAY, OBSIDIAN, GEODE } data class BeachState( val timeRemaining: Int, val robotToMake: Robot, val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int, val ore: Int, val clay: Int, val obsidian: Int, val geodes: Int ) { fun advanceState( minutesSpent: Int, newRobotToMake: Robot, newOreRobots: Int = oreRobots, newClayRobots: Int = clayRobots, newObsidianRobots: Int = obsidianRobots, newGeodeRobots: Int = geodeRobots, newOre: Int = oreRobots + currentOre(minutesSpent), newClay: Int = clayRobots + currentClay(minutesSpent), newObsidian: Int = obsidianRobots + currentObsidian(minutesSpent), newGeodes: Int = geodeRobots + currentGeodes(minutesSpent), ) = BeachState( currentTime(minutesSpent) - 1, newRobotToMake, newOreRobots, newClayRobots, newObsidianRobots, newGeodeRobots, newOre, newClay, newObsidian, newGeodes, ) fun currentTime(minutesPassed: Int) = timeRemaining - minutesPassed fun currentOre(minutesPassed: Int) = ore + (minutesPassed * oreRobots) fun currentClay(minutesPassed: Int) = clay + (minutesPassed * clayRobots) fun currentObsidian(minutesPassed: Int) = obsidian + (minutesPassed * obsidianRobots) fun currentGeodes(minutesPassed: Int) = geodes + (minutesPassed * geodeRobots) } companion object { private val TRIANGLE_NUMBERS = (0..32).map { previousTriangleNumber(it) } private fun previousTriangleNumber(n: Int) = ((n - 1) * n) / 2 } }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
13,893
advent-of-code
MIT License
src/2022/Day17.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import common.* import common.Linearizer import common.Offset import java.io.File import java.math.BigInteger import java.util.* import kotlin.collections.List fun main() { Day17().solve() } class Day17 { val input1 = """ >>><<><>><<<>><>>><<<>>><<<><<<>><>><<>> """.trimIndent() // 3 // 2 // 1 // x 012345 // y class Shape(number: Int, val l: Linearizer) { val offsets: List<Offset> val top: Int init { offsets = when (number % 5) { 0 -> listOf( l.offset(0, 0), l.offset(1, 0), l.offset(2, 0), l.offset(3, 0), ) 1 -> listOf( l.offset(1, 0), l.offset(0, 1), l.offset(1, 1), l.offset(2, 1), l.offset(1, 2), ) 2 -> listOf( l.offset(0, 0), l.offset(1, 0), l.offset(2, 0), l.offset(2, 1), l.offset(2, 2), ) 3 -> listOf( l.offset(0, 0), l.offset(0, 1), l.offset(0, 2), l.offset(0, 3) ) else -> listOf( l.offset(0, 0), l.offset(0, 1), l.offset(1, 0), l.offset(1, 1) ) } } init { top = when (number % 5) { 0 -> 0 1 -> 2 2 -> 2 3 -> 3 else -> 1 } } } data class Rock( val cave: Cave, val number: Int, val x: Int, val y: Int, val nextMove: RockState = RockState.HORIZONTAL_MOVE, val shape: Shape = Shape(number, cave.l)) { fun tiles(): Iterable<Int> { return shape.offsets.around(cave.l.toIndex(x, y)) } fun move(wind: Wind): Rock { var x1 = x var y1 = y var nextMove1 = nextMove if (nextMove == RockState.HORIZONTAL_MOVE) { nextMove1 = RockState.VERTICAL_MOVE if (wind.next() == Move.LEFT) { --x1 } else { ++x1 } } else if (nextMove == RockState.VERTICAL_MOVE) { nextMove1 = RockState.HORIZONTAL_MOVE --y1 } return Rock(cave, number, x1, y1, nextMove1, shape) } fun noMove(): Rock { val nextMove1 = if (nextMove == RockState.HORIZONTAL_MOVE) { RockState.VERTICAL_MOVE } else { RockState.STILL } return Rock(cave, number, x, y, nextMove1, shape) } fun isStill(): Boolean { return nextMove == RockState.STILL } fun top() = shape.top + y fun bottom() = y } class Wind(val windStr: String) { var counter = 0 val l = windStr.length fun next(): Move { if (windStr[counter++%l] == '<') { return Move.LEFT } return Move.RIGHT } fun ix() = counter%l } enum class Move { DOWN, LEFT, RIGHT } enum class RockState { VERTICAL_MOVE, HORIZONTAL_MOVE, STILL } class Cave(windStr: String, val width: Int, size: Int = 100000) { val wind = Wind(windStr) var rockCounter = 0 val widthWithWalls = width + 2 val l = Linearizer(widthWithWalls, size) var bottom = 0 var top = bottom val bits = (0 until widthWithWalls).map { 0b1 shl it } val innerMask = bits.subList(1, widthWithWalls-1).fold(0){acc, it1 -> acc or it1} val windStr1 = StringBuilder() var lastWind = 100000 fun topCode(n: Int) = (n and innerMask) shr 1 var tiles = MutableList(l.dimensions[1]) { if (it == 0) { // println(bits.fold(0){acc, it1 -> acc or it1}) bits.fold(0){acc, it1 -> acc or it1} } else { // println(bits[0] or bits[width-1]) bits[0] or bits[widthWithWalls-1] } } var rock: Rock = newRock() fun newRock(): Rock { rock = Rock(this, rockCounter++, 3, top+4) add(rock, true) return rock } fun evenTop(i: Int): Int? { if (i<bottom+2) { return null } // println(render(10)) // val t1 = topCode(tiles[i]) // val t2 = topCode(tiles[i-1]) // val t3 = (topCode(tiles[i]) or topCode(tiles[i-1])) // innerMask if ((topCode(tiles[i]) or topCode(tiles[i-1])) == topCode(innerMask)) { return topCode(tiles[i]) } return null } fun moveUntil(number: Int) { while (rockCounter < number || !rock.isStill()) { // if (rockCounter % 1000 == 0) { // println("$rockCounter/$number") // } // println(render(10)) move() } newTop(rock) } fun move() { if (rock.isStill()) { newTop(rock) rock = newRock() } else { rock = move(rock) } } fun get(x: Int, y: Int): Boolean { return tiles[y] and bits[x] != 0b0 } fun set(x: Int, y: Int, v: Boolean) { if (v != get(x, y)) { tiles[y] = tiles[y] xor bits[x] } } fun get(ix: Int): Boolean { val c = l.toCoordinates(ix) return get(c[0], c[1]) } fun set(ix: Int, v: Boolean) { val c = l.toCoordinates(ix) return set(c[0], c[1], v) } fun newTop(rock: Rock) { // for (i in rock.bottom() .. rock.top()) { // val t = evenTop(i) // if (t != null) { // println("$i $t") // println(render(5)) // } // } // val t = evenTop(top) // if (t != null) { // println("$top $t") // println(render(5)) // } top = maxOf(top, rock.top()) val ix = wind.ix() // if (rockCounter % 5 == 2 && wind.ix() <= lastWind) { // windStr1.append("${wind.ix()} ") // } if (wind.ix() <= lastWind) { windStr1.append("${rockCounter % 5}: ${wind.ix()}, ") println("$top - $rockCounter ${rockCounter % 5}: ${wind.ix()}, ") println(render(20)) } lastWind = wind.ix() // val width = l.dimensions[0] // val height = l.dimensions[1] // if (top - bottom + 10 > height) { // val newBottom = height/2 // for (y in top downTo newBottom+1) { // for (x in 1 .. width) { // tiles[l.toIndex(x, y-newBottom)] = tiles[l.toIndex(x, y)] // tiles[l.toIndex(x, y)] = 0 // } // } // bottom += newBottom // } } fun move(rock: Rock): Rock { val rock1 = rock.move(wind) remove(rock, true) if (!add(rock1)) { add(rock, true) return rock.noMove() } return rock1 } fun add(rock: Rock, force: Boolean = false): Boolean { if (rock.tiles().any {get(it)}) { if (force) { println(rock.tiles().toList()) println(rock.tiles().toList().map{l.toCoordinates(it).joinToString ()}) println(render(10)) throw RuntimeException() } return false } rock.tiles().forEach { set(it, true) } return true } fun remove(rock: Rock, force: Boolean = false): Boolean { if (rock.tiles().any { !get(it) }) { if (force) { println(rock.tiles().toList()) println(rock.tiles().toList().map{l.toCoordinates(it).joinToString ()}) println(render(10)) throw RuntimeException() } return false } rock.tiles().forEach { set(it, false) } return true } fun render(h: Int): String { return render(maxOf(0, top-h), top+1) } fun render(bottom: Int, top: Int): String { val s = StringBuilder() s.appendLine("$bottom .. $top") for (y in top downTo bottom) { for (x in 0 until l.dimensions[0]) { s.append( if (get(x ,y)) { '#' } else { '.' }) } s.appendLine() } return s.toString() } } fun solve() { val f = File("src/2022/inputs/day17.in") val s = Scanner(f) // val s = Scanner(input1) val winds0 = StringBuilder() while (s.hasNextLine()) { val line = s.nextLine().trim() winds0.append(line) } val winds = winds0.toString() val width = 7 val c = Cave(winds, width) // c.moveUntil(1) // println(c.render(0, 20)) // println("${winds}") // c.moveUntil(12200) // println("${c.top}") // println(c.windStr1) // println(c.windStr.toString().takeLast(1000)) val targetRocks = BigInteger("1000000000000") val rockBase = BigInteger("1724") val topBase = BigInteger("2617") val rockPeriod = BigInteger("1705") val topPeriod = BigInteger("2618") val numOfFullPeriods = targetRocks.minus(rockBase).divide(rockPeriod) val newRockBase = targetRocks.minus(rockPeriod.times(numOfFullPeriods)).toInt() // 3290 c.moveUntil(1724) val top0 = c.top c.moveUntil(3290) val top1 = c.top println("$top0 $top1 ${top1 - top0}") // 2617 5008 2391 println(newRockBase) val r = numOfFullPeriods.times(topPeriod).plus(topBase).plus(BigInteger("2391")) println(r) // println("${winds.length}") // // val period1 = 5 * winds.length // val period2 = 10 * winds.length // // var lastTop = 0 // for (i in 1..20) { // c.moveUntil(period1 * i) // println("$i ${c.top() - lastTop} ${c.rockCounter}") // lastTop = c.top() // println(c.render(20)) // } // c.moveUntil(period1) // val top1 = c.top().toLong() // val firstPeriodTop = top1 // c.moveUntil(period2) // val top2 = c.top().toLong() // val middlePeriodTopDiff = top2 - top1 // // val rockCount = 1000000000000L // // val lastRocks = rockCount % period1 // val period3 = (period2 + lastRocks).toInt() // c.moveUntil(period3) // val top3 = c.top().toLong() // val lastPeriodTopDiff = top3 - top2 // // val middlePeriodNum = rockCount / period1 - 1 // // val h = firstPeriodTop + middlePeriodTopDiff * middlePeriodNum + lastPeriodTopDiff // // println("$period1 $top1 $period2 $top2 $period3 $top3") // println("$h = $firstPeriodTop + $middlePeriodTopDiff * $middlePeriodNum + $lastPeriodTopDiff") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
12,132
advent-of-code
Apache License 2.0
src/day05/day05.kt
jimsaidov
572,881,855
false
{"Kotlin": 10629}
package day05 class Day05(private val input: List<String>) { private data class MoveInstruction(val amount: Int, val fromIndex: Int, val toIndex: Int) private val moveInstructions: List<MoveInstruction> = input.drop(input.indexOf("") + 1) .map { row -> row.split(" ").let { parts -> MoveInstruction(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1) } } private val crateStacks: List<MutableList<Char>> by lazy { val crateStackRows = input.takeWhile { it.contains('[') } (1..crateStackRows.last().length step 4).map { index -> crateStackRows .mapNotNull { it.getOrNull(index) } .filter { it.isUpperCase() } .toMutableList() } } private fun moveCrates(isOneByOne: Boolean){ moveInstructions.forEach { (amount, fromIndex, toIndex) -> val toMoveCrates = crateStacks[fromIndex].take(amount) repeat(amount) { crateStacks[fromIndex].removeFirst() } crateStacks[toIndex].addAll(0, if (isOneByOne) toMoveCrates.reversed() else toMoveCrates) } } private fun moveAndGetTop(isOneByOne: Boolean): String { moveCrates(isOneByOne) return crateStacks.map { it.first() }.joinToString("") } fun part1(): String = moveAndGetTop(true) fun part2(): String = moveAndGetTop(false) } fun main() { val day: String = "05" check(Day05(InputReader.testFileAsList(day)).part1() == "CMZ") println(Day05(InputReader.asList(day)).part1()) check(Day05(InputReader.testFileAsList(day)).part2() == "MCD") println(Day05(InputReader.asList(day)).part2()) }
0
Kotlin
0
0
d4eb926b57460d4ba4acced14658f211e1ccc12c
1,740
aoc2022
Apache License 2.0
src/main/kotlin/Day08.kt
arosenf
726,114,493
false
{"Kotlin": 40487}
import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.isEmpty() or (args.size < 2)) { println("Hands not specified") exitProcess(1) } val fileName = args.first() println("Reading $fileName") val lines = readLines(fileName) val result = if (args[1] == "part1") { Day08().navigate(lines) } else { Day08().navigateGhost(lines) } println("Result: $result") } class Day08 { fun navigate(input: Sequence<String>): Long { val inputList = input.toList() val instructions = parseInstructions(inputList.first()) val network = parseNetwork(inputList) val startNode = network["AAA"] ?: error(NOT_POSSIBLE) return findPathLength(startNode, "ZZZ", instructions, network) } fun navigateGhost(input: Sequence<String>): Long { val inputList = input.toList() val network = parseNetwork(inputList) val startNodes = findStartingNodesForGhost(network) val results = startNodes.map { findPathLength( it, "Z", parseInstructions(inputList.first()), network ) }.toList() return lcm(results) } private fun parseInstructions(input: String): Sequence<Char> { val instruction = input.toCharArray().toList() //.take() as many as you want, this is an infinitely looping sequence return generateSequence { instruction }.flatten() } private fun parseNetwork(input: List<String>): Map<String, Node> { val network = mutableMapOf<String, Node>() input.drop(2) .forEach { val node = parseNode(it) network[node.first] = node.second } return network } private fun parseNode(node: String): Pair<String, Node> { val key = parseKey(node) val rawNode = node.substringAfter('=') .trim() .substringAfter('(') .substringBefore(')') .split(',') .map { s -> s.trim() } return key to Node(key, rawNode.first(), rawNode.last()) } private fun parseKey(node: String): String { return node.substringBefore('=').trim() } private fun findStartingNodesForGhost(network: Map<String, Node>): List<Node> { return network.keys .filter { it.endsWith('A') } .map { network[it] ?: error(NOT_POSSIBLE) } .toList() } // We assume the path will eventually come to an end private fun findPathLength( startNode: Node, endCondition: String, instructions: Sequence<Char>, network: Map<String, Node> ): Long { var result = 0L var currentNode = startNode run breaking@{ instructions.forEach { result += 1 val newNode = when (it) { 'L' -> currentNode.left 'R' -> currentNode.right else -> endCondition } currentNode = network[newNode] ?: error(NOT_POSSIBLE) if (newNode.endsWith(endCondition)) { return@breaking } } } return result } private fun lcm(numbers: List<Long>): Long { var result = numbers[0] for (i in 1..<numbers.size) { result = lcm(result, numbers[i]) } return result } private fun lcm(a: Long, b: Long): Long { val larger = if (a > b) a else b val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return maxLcm } data class Node(val name: String, val left: String, val right: String) }
0
Kotlin
0
0
d9ce83ee89db7081cf7c14bcad09e1348d9059cb
3,992
adventofcode2023
MIT License
src/Day06.kt
ajesh-n
573,125,760
false
{"Kotlin": 8882}
fun main() { fun part1(input: List<String>): Int { val markerStart = input[0].windowed(4, 1).find { it.toCharArray().distinct().count() == 4 } return input[0].indexOf(markerStart!!) + 4 } fun part2(input: List<String>): Int { val markerStart = input[0].windowed(14, 1).find { it.toCharArray().distinct().count() == 14 } return input[0].indexOf(markerStart!!) + 14 } val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2545773d7118da20abbc4243c4ccbf9330c4a187
657
kotlin-aoc-2022
Apache License 2.0
app/src/main/java/com/themobilecoder/adventofcode/day8/DayEightUtils.kt
themobilecoder
726,690,255
false
{"Kotlin": 323477}
package com.themobilecoder.adventofcode.day8 import com.themobilecoder.adventofcode.splitByNewLine fun String.buildMapDirections(): Map<String, Pair<String, String>> { val lines = splitByNewLine().filter { it.isNotBlank() }.drop(1) val map = mutableMapOf<String, Pair<String, String>>() lines.forEach { line -> val key = line.split("=")[0].trim() val left = line.split("=")[1].split(",")[0].trim().filter { it.isLetterOrDigit() } val right = line.split("=")[1].split(",")[1].trim().filter { it.isLetterOrDigit() } map[key] = left to right } return map } fun String.getInstructions(): String { return splitByNewLine()[0].trim() } fun String.buildQueueOfStartingPoints(): List<String> { val keys = mutableListOf<String>() val lines = splitByNewLine().filter { it.isNotBlank() }.drop(1) lines.forEach { line -> val key = line.split("=")[0].trim() if (key.endsWith('A')) { keys.add(key) } } return keys } fun List<Long>.getLCM(): Long { var result = this[0] for (i in 1 until size) { result = getLCM(result, this[i]) } return result } private fun getLCM(a: Long, b: Long): Long { val largerValue = if (a > b) a else b val maxLcm = a * b var lcm = largerValue while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += largerValue } return maxLcm }
0
Kotlin
0
0
b7770e1f912f52d7a6b0d13871f934096cf8e1aa
1,468
Advent-of-Code-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ConsecutiveCharacters.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 ConsecutiveCharactersStrategy { operator fun invoke(s: String): Int } class MaxPower1 : ConsecutiveCharactersStrategy { override operator fun invoke(s: String): Int { val n = s.length var start = 0 var end = 0 var max = 0 while (end < n) { while (end < n && s[end] == s[start]) { max = max.coerceAtLeast(end - start + 1) end++ } if (end == n) return max start = end } return max } } class MaxPower2 : ConsecutiveCharactersStrategy { override operator fun invoke(s: String): Int { var res = 0 val n = s.length var i = 0 while (i < n) { val j = i while (i + 1 < n && s[i] == s[i + 1]) { i++ } res = kotlin.math.max(i - j + 1, res) i++ } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,588
kotlab
Apache License 2.0
src/main/kotlin/com/sherepenko/leetcode/data/TreeNode.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.data import kotlin.math.max const val TREE_INDENTATION = 10 enum class Traversal { PRE_ORDER, IN_ORDER, POST_ORDER, LEVEL_ORDER } data class TreeNode( val value: Int, var left: TreeNode? = null, var right: TreeNode? = null ) { override fun toString(): String = value.toString() } fun TreeNode?.height(): Int { if (this == null) { return 0 } return max(left.height(), right.height()) + 1 } fun TreeNode?.size(): Int { if (this == null) { return 0 } return left.size() + right.size() + 1 } fun TreeNode?.prettifyPrint(space: Int = 0) { if (this == null) { return } val indentation = space + TREE_INDENTATION right?.prettifyPrint(indentation) println() for (i in TREE_INDENTATION until indentation) { print(" ") } println(this) left?.prettifyPrint(indentation) } fun TreeNode.joinToString(separator: String = ", ", prefix: String = "", postfix: String = "", traversal: Traversal = Traversal.PRE_ORDER): String { val builder = StringBuilder() builder.append(prefix) when (traversal) { Traversal.PRE_ORDER -> { preOrderTraversal(this, builder, separator) } Traversal.IN_ORDER -> { inOrderTraversal(this, builder, separator) } Traversal.POST_ORDER -> { postOrderTraversal(this, builder, separator) } Traversal.LEVEL_ORDER -> { for (i in 1..this.height()) { levelOrderTraversal(this, i, builder, separator) } } } builder.setLength(builder.length - separator.length) builder.append(postfix) return builder.toString() } private fun preOrderTraversal(node: TreeNode?, builder: StringBuilder, separator: String) { if (node == null) { return } builder.append(node.value).append(separator) preOrderTraversal(node.left, builder, separator) preOrderTraversal(node.right, builder, separator) } private fun inOrderTraversal(node: TreeNode?, builder: StringBuilder, separator: String) { if (node == null) { return } inOrderTraversal(node.left, builder, separator) builder.append(node.value).append(separator) inOrderTraversal(node.right, builder, separator) } private fun postOrderTraversal(node: TreeNode?, builder: StringBuilder, separator: String) { if (node == null) { return } postOrderTraversal(node.left, builder, separator) postOrderTraversal(node.right, builder, separator) builder.append(node.value).append(separator) } private fun levelOrderTraversal(node: TreeNode?, level: Int, builder: StringBuilder, separator: String) { if (node == null) { return } if (level == 1) { builder.append(node.value).append(separator) } else if (level > 1) { levelOrderTraversal(node.left, level - 1, builder, separator) levelOrderTraversal(node.right, level - 1, builder, separator) } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
3,059
leetcode
The Unlicense
AoC2021day10-SintaxScoring/src/main/kotlin/Main.kt
mcrispim
533,770,397
false
{"Kotlin": 29888}
import java.io.File val closeChar = mapOf(')' to '(', ']' to '[', '}' to '{', '>' to '<') val openChar = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val openings = closeChar.values enum class LineType { CORRUPTED, INCOMPLETE, CORRECT, } class Line(val type: LineType, val problemChars: List<Char>) fun main() { val inputData = File("data.txt") val data = inputData.readLines() val linesCorrupted = mutableListOf<Line>() val linesIncomplete = mutableListOf<Line>() val linesCorrect = mutableListOf<Line>() for (line in data) { val myLine = processLine(line) when (myLine.type) { LineType.CORRUPTED -> linesCorrupted.add(myLine) LineType.INCOMPLETE -> linesIncomplete.add(myLine) LineType.CORRECT -> linesCorrect.add(myLine) } } println("From ${data.size} lines, ${linesCorrupted.size} were CORRUPTED, ${linesIncomplete.size} were INCOMPLETE and ${linesCorrect.size} where ok.") var corruptionScore = 0L for (line in linesCorrupted) { val c = line.problemChars.first() corruptionScore += wrongCharValue(c) } println("The score is $corruptionScore.") val incompleteScores = mutableListOf<Long>() for (line in linesIncomplete) { var score = 0L for (c in line.problemChars.asReversed()) { score = score * 5 + missingCharValue(openChar[c]!!) } incompleteScores.add(score) } val middleScore = incompleteScores.sorted()[incompleteScores.size / 2] println("The middle incomplete score is $middleScore.") } fun processLine(line: String): Line { val stack = mutableListOf<Char>() for (c in line) { if (c in openings) { stack.add(c) } else { // it's a closing if (stack.isNotEmpty() && stack.last() == closeChar[c]) { stack.removeLast() } else { // corrupted Line return Line(LineType.CORRUPTED, listOf(c)) } } } return if (stack.isNotEmpty()) Line(LineType.INCOMPLETE, stack) else Line(LineType.CORRECT, emptyList()) } fun wrongCharValue(c: Char): Int { return when(c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } fun missingCharValue(c: Char): Int { return when(c) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> 0 } }
0
Kotlin
0
0
ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523
2,479
AoC2021
MIT License
src/day21/Day21.kt
crmitchelmore
576,065,911
false
{"Kotlin": 115199}
package day21 import helpers.ReadFile import java.math.BigDecimal class Day21 { val tlines = listOf( "root: pppw + sjmn", "dbpl: 5", "cczh: sllz + lgvd", "zczc: 2", "ptdq: humn - dvpt", "dvpt: 3", "lfqf: 4", "humn: 5", "ljgn: 2", "sjmn: drzm * dbpl", "sllz: 4", "pppw: cczh / lfqf", "lgvd: ljgn * ptdq", "drzm: hmdt - zczc", "hmdt: 32" ) val rlines = ReadFile.named("src/day21/input.txt") class Calc { val name: String var num: BigDecimal? = null var op: String? = null var refA: String? = null var refB: String? = null constructor(name: String) { this.name = name } } val lines = rlines var nums = mutableMapOf<String, Calc>() fun aopb(a: BigDecimal, b: BigDecimal, op: String): BigDecimal { return when (op) { "+" -> a + b "-" -> a - b "*" -> a * b "/" -> a / b else -> throw Exception("Unknown op $op") } } fun recurse(c: Calc): BigDecimal { if (c.num != null) { return c.num!! } val lhs = if (nums[c.refA]?.num != null) nums[c.refA]!!.num!! else recurse(nums[c.refA]!!) val rhs = if (nums[c.refB]?.num != null) nums[c.refB]!!.num!! else recurse(nums[c.refB]!!) return aopb(lhs, rhs, c.op!!) } fun isLower(i: Long) : Boolean { val a = nums[nums["root"]!!.refA]!! val b = "13751780524553".toBigDecimal() val human = nums["humn"]!! human.num = BigDecimal(i) val result = recurse(a) if (i % 1000 == 0L) { println("$i $result") } if (result == b) { println("Win : $i") throw Exception("Win") } return result < b } fun result1() { lines.forEach { line -> val parts = line.split(": ") var calc = Calc(parts[0]) calc.num = parts[1].toBigDecimalOrNull() if (calc.num == null) { val refs = parts[1].split(" ") calc.op = refs[1] calc.refA = refs[0] calc.refB = refs[2] } nums[calc.name] = calc } val a = nums[nums["root"]!!.refA]!! val b = "13751780524553".toBigDecimal() 24440927425391 28105437225723 28068793716397 24440928000721 //nums[nums["root"]!!.refB]!! val human = nums["humn"]!! println(recurse(a)) var range = 1000000000000L..10000000000000L while (true) { val mid = (range.first + range.last) / 2 if (isLower(mid)) { println("lower") range = range.first..mid } else { println("higher") range = mid..range.last } } } }
0
Kotlin
0
0
fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470
3,104
adventofcode2022
MIT License
src/main/kotlin/test1/task2.kt
IgorFilimonov
342,322,388
false
null
package test1 fun displayHints() { println("What do you want to do?\n" + "1. Add element\n" + "2. Find out if there is an element\n" + "3. Remove element\n" + "4. Find out the number of elements\n" + "5. Find out the number of elements starting with a given prefix\n" + "0. Shut down\n" + "To select, enter the command number:") } enum class Commands { ADD, CONTAINS, REMOVE, SIZE, HOW_MANY_START_WITH_PREFIX } fun stringInput(message: String): String { println(message) return readLine().toString() } fun executeCommand(typeOfCommand: Int, trie: Trie) { when (typeOfCommand - 1) { Commands.ADD.ordinal -> { if (trie.add(stringInput("Enter the string:"))) { println("This element already exists") } } Commands.CONTAINS.ordinal -> { if (trie.contains(stringInput("Enter the string:"))) { println("This element is") } else { println("This element is missing") } } Commands.REMOVE.ordinal -> { if (!trie.remove(stringInput("Enter the string:"))) { println("This element is missing") } } Commands.SIZE.ordinal -> println("Size:\n${trie.size()}") Commands.HOW_MANY_START_WITH_PREFIX.ordinal -> { println("How many start with prefix:\n${trie.howManyStartWithPrefix("Enter a prefix:")}") } else -> throw IllegalArgumentException("Invalid command") } } fun main() { var command: Int? = -1 val trie = Trie(Node()) while (command != 0) { displayHints() command = readLine()?.toIntOrNull() ?: throw IllegalArgumentException("This is not an integer") if (command != 0) { executeCommand(command, trie) } } }
1
Kotlin
0
0
bb8c6e54e738ac403062e8f62caea846d7efb1f9
1,924
spbu_2020_kotlin_homeworks
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/PalindromeNumberKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/palindrome-number/description/ * * Determine whether an integer is a palindrome. Do this without extra space. */ class PalindromeNumberKt { class Solution { /** Assumption: "Do this without extra space" => no other classes or arrays but primative variables allowed Algo0: use start and end; walk to middle comparing values p q n0 n1 ... n(m/2-1) n(m/2)? n(m/2+1)... n(m-1) n(m) p at begining q at end special?: negative numbers?; zero p && q are not null-ish while (p != q) { if (x[p] != x[q]) { return false } p++ q-- } return true */ fun powerOfTen(exponent: Int): Long { // 10^0 = 1 // 10^1 = 10 // 10^2 = 100 var power: Long = 1 var index = 0 while (index < exponent) { index++ power *= 10 } return power } fun digitAtPlace(place: Int, x: Int): Long { // place => 3210 // x => abcd // return (x / (Math.pow(10.0, place.toDouble())).toLong()) % 10 return (x / powerOfTen(place)) % 10L } fun placeOfMostSignificantBit(x: Int): Int { // place => 3210 // x => abcd if (x < 10) { return 0 } else { var p = 0 // while ((Math.pow(10.0, p)).toLong() <= x) { while (powerOfTen(p) <= x) { p++ } p-- return p } } // Place is based upon index numbering fun isPalindrome(x: Int): Boolean { if (x < 0) { return false } var p = placeOfMostSignificantBit(x) var q = 0 // make q == least significant bit while (p > q) { if (digitAtPlace(p, x) != digitAtPlace(q, x)) { return false } p-- q++ } return true } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
2,395
cloud-dqn-leetcode
No Limit Public License
src/test/kotlin/br/com/colman/kaucasus/DoubleStatisticsTest.kt
LeoColman
364,760,768
true
{"Kotlin": 110184}
package br.com.colman.kaucasus import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.maps.shouldContainAll import io.kotest.matchers.shouldBe class DoubleStatisticsTest : FunSpec({ val doubleVector = sequenceOf(0.0, 1.0, 3.0, 5.0, 11.0) val groups = sequenceOf("A", "B", "B", "C", "C") test("Sum by") { val r = mapOf("A" to 0.0, "B" to 4.0, "C" to 16.0) groups.zip(doubleVector).sumBy() shouldContainAll mapOf("A" to r["A"], "B" to r["B"], "C" to r["C"]) groups.zip(doubleVector) .sumBy(keySelector = { it.first }, doubleSelector = { it.second }) shouldContainAll mapOf( "A" to r["A"], "B" to r["B"] ) } test("Average By") { val r = mapOf("A" to 0.0, "B" to 2.0, "C" to 8.0) groups.zip(doubleVector).averageBy( keySelector = { it.first }, doubleSelector = { it.second } ) shouldBe r } test("Bin test") { val binned = sequenceOf( doubleVector, doubleVector.map { it + 100.0 }, doubleVector.map { it + 200.0 } ).flatMap { it } .zip(groups.repeat()) .binByDouble( binSize = 100.0, valueSelector = { it.first }, rangeStart = 0.0 ) binned.bins shouldHaveSize 3 binned[5.0]!!.range.let { it.lowerBound shouldBe 0.0; it.upperBound shouldBe 100.0 } binned[105.0]!!.range.let { it.lowerBound shouldBe 100.0; it.upperBound shouldBe 200.0 } binned[205.0]!!.range.let { it.lowerBound shouldBe 200.0; it.upperBound shouldBe 300.0 } } }) private fun <T> Sequence<T>.repeat(): Sequence<T> = sequence { while (true) yieldAll(this@repeat) }
3
Kotlin
0
3
08187a786cf34002e2c65022d39e44250db5e253
1,821
Kaucasus
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/KokoEatingBananas.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 /** * 875. Koko Eating Bananas * @see <a href="https://leetcode.com/problems/koko-eating-bananas/">Source</a> */ fun interface KokoEatingBananas { fun minEatingSpeed(piles: IntArray, h: Int): Int } class KokoEatingBananasBS : KokoEatingBananas { override fun minEatingSpeed(piles: IntArray, h: Int): Int { var l = 1 var r = LIMIT while (l < r) { val m = (l + r) / 2 var total = 0 for (p in piles) { total += (p + m - 1) / m } if (total > h) { l = m + 1 } else { r = m } } return l } companion object { private const val LIMIT = 1000000000 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,390
kotlab
Apache License 2.0
Kotlin/src/SearchInRotatedSortedArrayII.kt
TonnyL
106,459,115
false
null
import java.util.Arrays /** * Follow up for "Search in Rotated Sorted Array": * What if duplicates are allowed? * * Would this affect the run-time complexity? How and why? * * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. * * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). * * Write nums function to determine if nums given target is in the array. * * The array may contain duplicates. * * Accepted. */ class SearchInRotatedSortedArrayII { fun search(nums: IntArray, target: Int): Boolean { if (nums.isEmpty()) { return false } var start = 0 var end = nums.size - 1 while (start <= end) { val mid = start + (end - start) / 2 if (nums[mid] == target) { return true } if (nums[mid] < nums[end]) { // right half sorted if (target > nums[mid] && target <= nums[end]) { return Arrays.binarySearch(nums, mid, end + 1, target) >= 0 } else { end = mid - 1 } } else if (nums[mid] > nums[end]) { // left half sorted if (target >= nums[start] && target < nums[mid]) { return Arrays.binarySearch(nums, start, mid + 1, target) >= 0 } else { start = mid + 1 } } else { end-- } } return false } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,522
Windary
MIT License
src/main/kotlin/g2201_2300/s2212_maximum_points_in_an_archery_competition/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2212_maximum_points_in_an_archery_competition // #Medium #Array #Bit_Manipulation #Recursion #Enumeration // #2023_06_27_Time_210_ms_(100.00%)_Space_34.4_MB_(100.00%) class Solution { private val ans = IntArray(12) private val ans1 = IntArray(12) private var max = 0 fun maximumBobPoints(numArrows: Int, aliceArrows: IntArray): IntArray { solve(numArrows, aliceArrows, 11, 0) return ans1 } private fun solve(numArrows: Int, aliceArrows: IntArray, index: Int, sum: Int) { if (numArrows <= 0 || index < 0) { if (max < sum) { max = sum ans1[0] = Math.max(ans[0], ans[0] + numArrows) System.arraycopy(ans, 1, ans1, 1, 11) } return } if (aliceArrows[index] + 1 <= numArrows) { ans[index] = aliceArrows[index] + 1 solve(numArrows - (aliceArrows[index] + 1), aliceArrows, index - 1, sum + index) ans[index] = 0 } solve(numArrows, aliceArrows, index - 1, sum) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,083
LeetCode-in-Kotlin
MIT License
src/main/kotlin/bk65/Problem1.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package bk65 import kotlin.math.abs fun main() { // "aaaa" // "bccb" val resul = Problem1().checkAlmostEquivalent("aaaa", "bccb") println(resul) } class Problem1 { fun checkAlmostEquivalent(word1: String, word2: String): Boolean { val map1 = word1.toCharArray().toList().groupingBy { it }.eachCount() val map2 = word2.toCharArray().toList().groupingBy { it }.eachCount() val bigger = if (map1.size > map2.size) map1 else map2 val smaller = if (map1.size <= map2.size) map1 else map2 for (entry: Map.Entry<Char, Int> in bigger) { val char1 = entry.key val char1Count = entry.value val char2Count = smaller[char1] ?: 0 if (abs(char1Count - char2Count) > 3) return false } for (entry: Map.Entry<Char, Int> in smaller) { val char1 = entry.key val char1Count = entry.value val char2Count = bigger[char1] ?: 0 if (abs(char1Count - char2Count) > 3) return false } return true } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
1,067
leetcode-kotlin
MIT License
advent/src/test/kotlin/org/elwaxoro/advent/y2022/Dec19.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2022 import org.elwaxoro.advent.PuzzleDayTester /** * Give up hope looking at this. was refactoring for smarter solvers but didn't keep the original working solver :( */ class Dec19 : PuzzleDayTester(19, 2022) { override fun part1(): Any = "lost" override fun part2(): Any = "lost" // loader().map { factory -> // val sim = Simulation(factory, 24) // val states = (0..24).fold(listOf(sim)) { sims, ctr -> // sims.flatMap { it.cycle() } // .also { println("after rep $ctr the raw size is ${it.size}") } // .filter { sim -> // when { //// sim.timeLeft < 2 -> (sim.resources[Resource.GEODE]!! > 0)//.also { println("time left is zero, no geodes") } //// sim.timeLeft < 5 -> (sim.robots[Robot.GEODE_ROBOT]!! > 0)//.also { println("5 mins to go, no geode robot") } // sim.timeLeft < 4 -> (sim.robots[Robot.OBSIDIAN_ROBOT]!! > 0)//.also {println("8 mins to go, no obsidian robot")} // sim.timeLeft < 15 -> (sim.robots[Robot.CLAY_ROBOT]!! > 0)//.also{println("9 mins to go, no clay")} // sim.timeLeft < 16 -> (sim.robots[Robot.ORE_ROBOT]!! > 1)//.also { println("10 mins to go, only 1 ore") } // else -> true // } // }.also { println("after rep $ctr the filtered size is ${it.size}") } // .toSet().also { println("after going down to set size: ${it.size}") } // .sortedByDescending { it.potential() }.take(100000) // } // val best = states.maxBy { it.resources[Resource.GEODE] ?: 0 } // val mostGeodes = states.maxOf { it.resources[Resource.GEODE] ?: 0 } // println("Max costs: ${factory.maxCostMap}") // println("After all reps, states: ${states.size} best: $mostGeodes : $best") // factory.name * mostGeodes // }.sum() private fun loader() = load().map { settings -> val (fullName, costs) = settings.split(":") val name = fullName.replace("Blueprint ", "").toInt() val costMap = costs.split(".").filter { it.isNotBlank() }.associate { cost -> Robot.fromString(cost) to cost.substringAfter("costs ").split(" and ").associate { it.resourceCost() } } RobotFactory(name, costMap) } data class Simulation( val factory: RobotFactory, val timeLeft: Int, val resources: Map<Resource, Int> = mapOf( Resource.ORE to 0, Resource.CLAY to 0, Resource.OBSIDIAN to 0, Resource.GEODE to 0 ), val robots: Map<Robot, Int> = mapOf( Robot.ORE_ROBOT to 1, Robot.CLAY_ROBOT to 0, Robot.OBSIDIAN_ROBOT to 0, Robot.GEODE_ROBOT to 0 ), ) { fun potential(): Int = (resources[Resource.GEODE] ?: 0) + ((robots[Robot.GEODE_ROBOT] ?: 0) * timeLeft)// + (robots[Robot.OBSIDIAN_ROBOT] ?: 0) fun isFinished() = timeLeft == 0 fun cycle(): List<Simulation> = if (isFinished()) { listOf(this) } else { // get resources val newResources = robots.map { (t, u) -> t.produces to (resources[t.produces] ?: 0) + u }.toMap() val hasClay = (robots[Robot.CLAY_ROBOT] ?: 0) > 0 val hasObsidian = (robots[Robot.OBSIDIAN_ROBOT] ?: 0) > 0 val hasGeode = (robots[Robot.GEODE_ROBOT] ?: 0) > 0 val buildableRobots = factory.costMap.filter { (robot, cost) -> // can we afford this robot? cost.all { rc -> (resources[rc.key] ?: 0) >= rc.value } } val futurePossibleRobots = if((robots[Robot.OBSIDIAN_ROBOT] ?: 0) > 0) { } else if ((robots[Robot.CLAY_ROBOT] ?: 0) > 0) { } else { } // mark possible robots to build (use resource amounts from before new resources appear) // fan out with new robots (can only build up to one a minute) val possibleRobots = factory.costMap.filter { (robot, cost) -> // can we afford this robot? cost.all { rc -> (resources[rc.key] ?: 0) >= rc.value } } // drop everything for a geode robot if (possibleRobots.containsKey(Robot.GEODE_ROBOT)) { val newRobots = robots.map { (r, t) -> r to ((t + 1).takeIf { r == Robot.GEODE_ROBOT } ?: t) }.toMap() val updatedResources = newResources.map { (r, c) -> r to (c - (factory.costMap[Robot.GEODE_ROBOT]!![r] ?: 0)) }.toMap() listOf(Simulation(factory, timeLeft - 1, updatedResources, newRobots)) } else { factory.costMap.filter { (robot, cost) -> // can we afford this robot? cost.all { rc -> (resources[rc.key] ?: 0) >= rc.value } }.filter { (robot, cost) -> (robots[robot] ?: 0) < 10 && (robots[robot] ?: 0) < (factory.maxCostMap[robot.produces] ?: 0) // true }.map { (robot, cost) -> val newRobots = robots.map { (r, t) -> r to ((t + 1).takeIf { r == robot } ?: t) }.toMap() val updatedResources = newResources.map { (r, c) -> r to (c - (cost[r] ?: 0)) }.toMap() Simulation(factory, timeLeft - 1, updatedResources, newRobots) }.plus(Simulation(factory, timeLeft - 1, newResources, robots)) } } } data class RobotFactory( val name: Int, val costMap: Map<Robot, Map<Resource, Int>>, ) { val maxCostMap: Map<Resource, Int> init { maxCostMap = maxCosts() } fun maxCosts() = costMap.values.flatMap { it.map { it.key to it.value } }.groupBy { it.first }.map { it.key to it.value.maxOf { it.second } }.toMap() } private fun String.resourceCost(): Pair<Resource, Int> = Resource.values().single { contains(it.text) } to replace("\\D".toRegex(), "").toInt() enum class Robot(val text: String, val produces: Resource) { ORE_ROBOT("ore robot", Resource.ORE), CLAY_ROBOT("clay robot", Resource.CLAY), OBSIDIAN_ROBOT("obsidian robot", Resource.OBSIDIAN), GEODE_ROBOT("geode robot", Resource.GEODE); companion object { fun fromString(str: String): Robot = values().single { robot -> str.contains(robot.text) } } } enum class Resource(val text: String) { ORE("ore"), CLAY("clay"), OBSIDIAN("obsidian"), GEODE("geode"); } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
7,103
advent-of-code
MIT License
src/main/kotlin/day25/Day25.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day25 import execute import readAllText fun part1(input: String) = input.lineSequence() .sumOf(::decode) .let(::encode) private const val DIGITS = "=-012" private fun decode(line: String) = line.fold(0L) { acc, c -> acc * 5 + DIGITS.indexOf(c) - 2 } private fun encode(number: Long) = buildString { var b = number while (b > 0) { append(DIGITS[((b + 2) % 5).toInt()]) b = (b + 2) / 5 } }.reversed().ifEmpty { "0" } fun part2(input: String) = 0 fun main() { val input = readAllText("local/day25_input.txt") val test = """ 1=-0-2 12111 2=0= 21 2=01 111 20012 112 1=-1= 1-12 12 1= 122 """.trimIndent() execute(::part1, test, "2=-1=0") execute(::part1, input, "122-0==-=211==-2-200") }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
863
advent-of-code-2022
MIT License
aoc_2023/src/main/kotlin/problems/day25/GroupDividider.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day25 class GroupDividider(val snowMachine: SnowMachine, val disconnectWires: Int) { fun divideIn2Groups(): List<Set<Component>> { val group1 = mutableSetOf<Component>() val group2 = mutableSetOf<Component>() val visitedPairs = mutableSetOf<ComponentPair>() val visitedComponents = mutableSetOf<Component>() val openedComponents = mutableListOf(snowMachine.components.values.first()) group1.add(snowMachine.components.values.first()) while (openedComponents.isNotEmpty()) { val component = openedComponents.removeLast() if (visitedComponents.contains(component)) continue visitedComponents.add(component) for (connectedComponent in component.otherComponents) { if (group1.contains(connectedComponent) || group2.contains(connectedComponent)) continue val pair = ComponentPair(component, connectedComponent) if (visitedPairs.contains(pair)) continue visitedPairs.add(pair) val visitedCount = djistraIndirectReturn(connectedComponent, component) if (visitedCount > disconnectWires) { group1.add(connectedComponent) openedComponents.add(connectedComponent) } else { group2.add(connectedComponent) } } } val group2ByDifference = this.snowMachine.components.values - group1 return listOf(group1, group2ByDifference.toSet()) } fun djistraIndirectReturn(from: Component, to: Component): Int { var count = 0 // val visitedComponents = mutableSetOf<Component>() val visitedPairs = mutableSetOf<ComponentPair>() val openedNodes = mutableListOf(ComponentNode(from, null)) val solutions = mutableListOf<ComponentNode>() while (openedNodes.isNotEmpty()) { val componentNode = openedNodes.removeFirst() val component = componentNode.component val newSolPairs = componentNode.pairs() if (solutions.any { it.pairs().intersect(newSolPairs).isNotEmpty() }) { val removePairs = newSolPairs - solutions.map { it.pairs() }.flatten() visitedPairs.removeAll(removePairs) continue } if (component == to) { count++ solutions.add(componentNode) continue } for (connectedComponent in component.otherComponents) { val pair = ComponentPair(component, connectedComponent) // if(newSolPairs.contains(pair)) continue if (visitedPairs.contains(pair)) continue // if (visitedComponents.contains(connectedComponent)) continue visitedPairs.add(pair) // visitedComponents.add(connectedComponent) openedNodes.add(ComponentNode(connectedComponent, componentNode)) } } return count } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
3,104
advent-of-code-2023
MIT License
src/main/kotlin/aoc2019/day22_slam_shuffle/Op.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2019.day22_slam_shuffle import util.modularInverse as modInv import util.modularMultiply as modMult internal interface Op { fun forward(card: Long): Long fun reverse(card: Long): Long } internal data class Cut(val deckSize: Long, val n: Long) : Op { override fun forward(card: Long) = (card + deckSize - n) % deckSize override fun reverse(card: Long) = (card + deckSize + n) % deckSize } internal data class Deal(val deckSize: Long, val n: Long) : Op { private val inverse: Long by lazy { modInv(n, deckSize) } override fun forward(card: Long) = modMult(card, n, deckSize) override fun reverse(card: Long) = modMult(card, inverse, deckSize) } internal data class NewStack(val deckSize: Long) : Op { override fun forward(card: Long) = deckSize - card - 1 override fun reverse(card: Long) = deckSize - card - 1 } internal fun String.toOp(deckSize: Long): Op { val s = this.trim() return when { s.startsWith("cut") -> Cut(deckSize, s.words().last().toLong()) s.startsWith("deal with increment") -> Deal(deckSize, s.words().last().toLong()) s == "deal into new stack" -> NewStack(deckSize) else -> throw UnsupportedOperationException("Can't parse '$this' to an Op") } } internal fun String.toOps(deckSize: Long) = lines() .filter(String::isNotBlank) .map { it.toOp(deckSize) } internal fun reduceOps(ops: List<Op>): List<Op> { @Suppress("NAME_SHADOWING") var ops = ops var i = 0 while (i < ops.size) { val op = ops[i] if (op is NewStack) { ops = ops.subList(0, i) + listOf( Deal(op.deckSize, op.deckSize - 1), Cut(op.deckSize, 1), ) + ops.subList(i + 1, ops.size) continue // redo the newly-expanded index } if (i == 0) { i += 1 continue // the rest require a prev op to work with } val prev = ops[i - 1] if (prev is Cut && op is Cut) { ops = ops.subList(0, i - 1) + Cut(op.deckSize, (prev.n + op.n) % op.deckSize) + ops.subList(i + 1, ops.size) i -= 1 } else if (prev is Deal && op is Deal) { ops = ops.subList(0, i - 1) + Deal(op.deckSize, modMult(prev.n, op.n, op.deckSize)) + ops.subList(i + 1, ops.size) i -= 1 } else if (prev is Cut && op is Deal) { // move the cut to the other side ops = ops.subList(0, i - 1) + listOf( op, Cut(op.deckSize, modMult(prev.n, op.n, op.deckSize)), ) + ops.subList(i + 1, ops.size) i -= 1 } else { i += 1 } } return ops }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
3,032
aoc-2021
MIT License
src/main/kotlin/g2501_2600/s2573_find_the_string_with_lcp/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2573_find_the_string_with_lcp // #Hard #String #Dynamic_Programming #Greedy #Union_Find // #2023_07_10_Time_853_ms_(100.00%)_Space_147.3_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun findTheString(lcp: Array<IntArray>): String { val n = lcp.size val parent = IntArray(n) val rank = IntArray(n) val chars = IntArray(n) val str = IntArray(n) for (i in 0 until n) { parent[i] = i rank[i] = 1 } for (i in 0 until n) { for (j in i + 1 until n) { if (lcp[i][j] > 0) { union(parent, rank, i, j) } } } var c = 0 var par: Int for (i in 0 until n) { par = find(parent, i) if (chars[par] == 0) { chars[par] = ++c } if (c > 26) return "" str[i] = chars[par] } var `val`: Int val lcpNew = Array(n) { IntArray(n) } for (i in n - 1 downTo 0) { for (j in n - 1 downTo 0) { `val` = if (i + 1 < n && j + 1 < n) lcpNew[i + 1][j + 1] else 0 `val` = if (str[i] == str[j]) 1 + `val` else 0 lcpNew[i][j] = `val` if (lcpNew[i][j] != lcp[i][j]) return "" } } val sb = StringBuilder() for (e in str) { sb.append((e + 'a'.code - 1).toChar()) } return sb.toString() } private fun find(parent: IntArray, x: Int): Int { return if (x == parent[x]) x else find(parent, parent[x]).also { parent[x] = it } } private fun union(parent: IntArray, rank: IntArray, u: Int, v: Int) { var u = u var v = v u = find(parent, u) v = find(parent, v) if (u == v) return if (rank[u] >= rank[v]) { parent[v] = u rank[u] += rank[v] } else { parent[u] = v rank[v] += rank[u] } return } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,073
LeetCode-in-Kotlin
MIT License
src/main/kotlin/utils/utils.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package utils import java.io.File import java.math.BigInteger /** * Reads lines from the given input txt file. * @param name The name of the file to read */ fun readFile(name: String) = File("src/main/resources", "$name.txt").readLines() /** * Reads whole file into a text string * @param name The name of the file to read */ fun readFileToString(name: String) = File("src/main/resources", "$name.txt").readText() /** * Read file into lines and group after condition is met place following lines into new list * @param name The name of the file to read * @param condition A lambda to evaluate to determine the grouping condition. The line will be excluded from the output. The default will be a blank line */ fun readFileGroup(name: String, condition: (String) -> Boolean = { it.isBlank() }): List<List<String>> { val input = File("src/main/resources", "$name.txt").readLines() return groupLines(input) } /** * Parses input text as lines and removes trailing whitespace like \r * @param text This is typically text that has been declared between """ or has embedded \n */ fun readLines(text: String) = text.split("\n").map { it.trimEnd() }.toList() /** * Parse text into lines and group after condition is met place following lines into new list * @param text The text to parse * @param condition A lambda to evaluate to determine the grouping condition. The line will be excluded from the output. The default will be a blank line */ fun readLinesGroup(text: String, condition: (String) -> Boolean = { it.isBlank() }): List<List<String>> { val input = readLines(text) return groupLines(input, condition) } fun groupLines( input: List<String>, condition: (String) -> Boolean = { it.isBlank() } ): List<List<String>> { val result = mutableListOf<List<String>>() val list = mutableListOf<String>() input.forEach { if (condition(it)) { result.add(list.toList()) list.clear() } else { list.add(it) } } if (list.isNotEmpty()) { result.add(list.toList()) } return result.toList() } fun separator() { (1..50).forEach { _ -> print('=') } println() } // found on https://rosettacode.org/wiki/Permutations#Kotlin fun <T> permute(input: List<T>): List<List<T>> { if (input.isEmpty()) return emptyList() if (input.size == 1) return listOf(input) val perms = mutableListOf<List<T>>() val toInsert = input[0] for (perm in permute(input.drop(1))) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(newPerm) } } return perms } fun permutationsBI(n: BigInteger): BigInteger = n * if (n > BigInteger.ONE) permutationsBI(n - BigInteger.ONE) else BigInteger.ONE fun permutations(n: Int): BigInteger = permutationsBI(n.toBigInteger()) fun <T> permuteInvoke(input: List<T>, handlePermutation: (List<T>) -> Unit) { if (input.size == 1) { handlePermutation(input) } else { val toInsert = input[0] permuteInvoke(input.drop(1)) { perm -> for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) handlePermutation(newPerm) } } } } fun <T> permuteArray(input: Array<T>, makeArray: (Collection<T>) -> Array<T>): List<Array<T>> { if (input.isEmpty()) return emptyList() if (input.size == 1) return listOf(input) val perms = mutableListOf<Array<T>>() val toInsert = input[0] for (perm in permuteArray(makeArray(input.drop(1)), makeArray)) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(makeArray(newPerm)) } } return perms } class Combinations(val m: Int, val n: Int) { private val combination = IntArray(m) val combinations: MutableList<IntArray> = mutableListOf() init { generate(0) } private fun generate(k: Int) { if (k >= m) { combinations.add(combination.toList().toIntArray()) } else { for (j in 0 until n) if (k == 0 || j > combination[k - 1]) { combination[k] = j generate(k + 1) } } } } class ProcessingState(val registers: List<Char>, val processing: ProcessingState.() -> Unit) { var clock = 0 private set private val register = registers.associateWith { 0 }.toMutableMap() fun tick() { clock += 1 processing(this) } operator fun get(reg: Char): Int = register[reg] ?: error("Invalid register $reg") operator fun set(reg: Char, value: Int) { register[reg] = value } var regX: Int get() = get('X') set(value: Int) { register['X'] = value } } data class Triple<F, S, T>(val first: F, val second: S, val third: T)
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
4,689
aoc-2022-in-kotlin
Apache License 2.0
KVServer/src/main/kotlin/com/arist/Trie.kt
ArisPoz
354,646,175
false
null
package com.arist import java.lang.StringBuilder /** * @author arist */ data class Trie(val root: TrieNode = TrieNode(), val fin: Boolean = false) { data class TrieNode (var fin: Boolean = false, var subNodes: MutableMap<Char, TrieNode> = HashMap()) fun put(key: String) { var currentNode = root key.forEach { var node = currentNode.subNodes[it] if (node == null) { node = TrieNode() currentNode.subNodes[it] = node } currentNode = node } currentNode.fin = true } fun get(key: String): Pair<Type, String> { val currentNode = exists(key) if (currentNode == null || !currentNode.fin) { return Pair(Type.NOT_FOUND, Type.NOT_FOUND.msg) } return Pair(Type.OK, buildString(key, currentNode)) } fun query(key: String): Pair<Type, String> { if (exists(key.split(".")[0]) == null || !exists(key.split(".")[0])?.fin!!) { return Pair(Type.NOT_FOUND, Type.NOT_FOUND.msg) } val currentNode = exists(key.replace('.', '-')) if (currentNode == null || !currentNode.fin) { return Pair(Type.NOT_FOUND, Type.NOT_FOUND.msg) } return Pair(Type.OK, buildString(key, currentNode, true)) } fun delete(key: String): Pair<Type, String> { val node = exists(key) return if (node != null && node.fin) { delete(root, key, 0) Pair(Type.OK, Type.OK.msg) } else { Pair(Type.NOT_FOUND, Type.NOT_FOUND.msg) } } private fun delete(node: TrieNode, key: String, index: Int): Boolean { val currentChar = key[index] val currentNode = node.subNodes[currentChar] if (currentNode!!.subNodes.size > 1 && key.length < index) { delete(currentNode, key, index = index + 1) return false } if (index == key.length - 1) { return if (currentNode.subNodes.isNotEmpty()) { currentNode.fin = false currentNode.subNodes.remove('-') false } else { node.subNodes.remove(currentChar) true } } if (currentNode.fin) { delete(currentNode, key, index = index + 1) return false } val isDeletable = delete(currentNode, key, index = index + 1) return if (isDeletable) { root.subNodes.remove(currentChar) true } else false } private fun buildString(key: String, node: TrieNode, isQuery: Boolean = false): String { val builder = StringBuilder().append(key).append(" : { ") val separatorNode = node.subNodes['-'] ?: node.subNodes['='] if (isQuery) { key.replace('.', '-') } separatorNode?.subNodes?.forEach { builder.append(getSubKeys(it.value, it.key, 0)) builder.append(" ; ") } return "${builder.trimEnd().dropLast(2)} }" } private fun getSubKeys(currentNode: TrieNode, char: Char, level: Int): String { val builder = StringBuilder() currentNode.subNodes.forEach { when (char) { '-' -> builder.append(" : { ").append(getSubKeys(it.value, it.key, level + 1)) '=' -> builder.append(" : ").append(getSubKeys(it.value, it.key, level)) else -> builder.append(char).append(getSubKeys(it.value, it.key, level)) } } if (currentNode.subNodes.isEmpty()) { builder.append(char) for (i in 0 until level) { builder.append(" } ") } } return builder.toString() } private fun exists(key: String): TrieNode? { var currentNode = root key.forEach { val node = currentNode.subNodes[it] ?: return null currentNode = node } return currentNode } }
0
Kotlin
0
1
0e9b97c35f8bb73cb7e8a4bc1c97f36bc2a08578
4,053
KVStore
MIT License
src/main/kotlin/d1/d1.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d1 import readInput fun part1(input: List<String>): Int { val elves = ArrayList<Int>() var sum = 0 for (line in input) { if (line.isBlank()) { if (sum > 0) elves += sum sum = 0 } else { sum += line.toInt() } } if (sum > 0) elves += sum return elves.max() } fun part2(input: List<String>): Int { val elves = ArrayList<Int>() var sum = 0 for (line in input) { if (line.isBlank()) { if (sum > 0) elves += sum sum = 0 } else { sum += line.toInt() } } if (sum > 0) elves += sum elves.sortDescending() return elves[0] + elves[1] + elves[2] } fun main() { val input = readInput("d1/input1") println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
850
aoc2022
Creative Commons Zero v1.0 Universal
src/aoc2022/Day02.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList fun main() { val part1results = mapOf( "A X" to 3+1, "A Y" to 6+2, "A Z" to 0+3, "B X" to 0+1, "B Y" to 3+2, "B Z" to 6+3, "C X" to 6+1, "C Y" to 0+2, "C Z" to 3+3 ) val part2results = mapOf( "A X" to 0+3, "A Y" to 3+1, "A Z" to 6+2, "B X" to 0+1, "B Y" to 3+2, "B Z" to 6+3, "C X" to 0+2, "C Y" to 3+3, "C Z" to 6+1 ) fun part1(input : List<String>) : Int { var score = 0 for(round in input) { score += part1results[round]!! } return score } fun part2(input : List<String>) : Int { var score = 0 for(round in input) { score += part2results[round]!! } return score } val input = readInputAsList("Day02", "2022") println(part1(input)) println(part2(input)) // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day02_test", "2022") check(part1(testInput) == 31) check(part2(testInput) == 32) }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
1,185
AOC-2022-Kotlin
Apache License 2.0
src/day14/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day14 import Coords import below import day14.PointType.ABYSS import day14.PointType.AIR import day14.PointType.ROCK import day14.PointType.SAND import day14.PointType.SOURCE import get import leftDown import readInput import rightDown import splitEach import toPair fun main() { fun part1(input: List<String>): Int { return PathScanner.of(input) .drawMap() .drawSand(Mode.ABYSS) .sandCapacity() } fun part2(input: List<String>): Int { return PathScanner.of(input) .drawMap() .drawSand(Mode.FLOOR) .sandCapacity() } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) } fun String.toCoords(): List<Coords> { return split(" -> ") .splitEach(",") .map { it.toPair(String::toInt) } .map(::Coords) } enum class PointType { ROCK, AIR, SOURCE, SAND, ABYSS } data class Tile(val coords: Coords, var type: PointType) { fun isBlocked() = isRock() || isSand() fun isRock() = type == ROCK fun isSand() = type == SAND fun print() = when (type) { ROCK -> "#" AIR -> "." SOURCE -> "+" SAND -> "o" ABYSS -> "x" } } enum class Mode { ABYSS, FLOOR } class PathScanner( private val linesCoords: List<List<Coords>> = mutableListOf() ) { private val map: MutableList<MutableList<Tile>> = mutableListOf() private val sourceCoords = Coords(500, 0) private val minX = linesCoords.minOf { it.minOf { it.x } } private val maxX = linesCoords.maxOf { it.maxOf { it.x } } private val maxY = linesCoords.maxOf { it.maxOf { it.y } } private var sands: Int = 0 private var floorSand = mutableSetOf<Coords>() private var finished = false fun drawMap(): PathScanner { drawAir() drawSource() drawRock() return this } private fun drawAir() { for (i in 0..maxX - minX) { val yList = mutableListOf<Tile>() map.add(yList) for (j in 0..maxY) { yList.add(Tile(Coords(i, j), AIR)) } } } private fun drawSource() { map[sourceCoords.adjust().x][sourceCoords.y] = Tile(sourceCoords.adjust(), SOURCE) } private fun drawRock() { linesCoords.forEach { lineCoords -> lineCoords .map { it.adjust() } .zipWithNext { (x, y), (b, c) -> if (x == b) { if (y > c) { (y downTo c).forEach { i -> map[x][i] = Tile(Coords(x, i), ROCK) } } else { (y..c).forEach { i -> map[x][i] = Tile(Coords(x, i), ROCK) } } } else if (y == c) { if (x > b) { (x downTo b).forEach { i -> map[i][y] = Tile(Coords(i, y), ROCK) } } else { (x..b).forEach { i -> map[i][y] = Tile(Coords(i, y), ROCK) } } } } } } private fun Coords.adjust(): Coords { return copy(x = x - minX) } fun drawSand(mode: Mode): PathScanner { val coords = sourceCoords.adjust() while (!finished) { stepTo(coords, mode) } return this } private fun stepTo(coords: Coords, mode: Mode) { var current = coords while (!finished) { val belowTile = getTile(current.below(), mode) when (belowTile.type) { ROCK, SAND -> { val diagonalLeft = getTile(current.leftDown(), mode) val diagonalRight = getTile(current.rightDown(), mode) if (diagonalLeft.isSand() && diagonalRight.isSand()) { if (sourceCoords.adjust() == current) { finished = true } } current = when { !diagonalLeft.isBlocked() -> diagonalLeft.coords !diagonalRight.isBlocked() -> diagonalRight.coords else -> { setSand(current, mode) sands++ break } } } AIR, SOURCE -> current = current.below() ABYSS -> { finished = true break } } } } private fun setSand(current: Coords, mode: Mode) { getTile(current, mode).type = SAND floorSand.add(current) } private fun getTile(coords: Coords, mode: Mode) = when (mode) { Mode.ABYSS -> map[coords] ?: Tile(coords, ABYSS) Mode.FLOOR -> map[coords] ?: when { isFloor(coords) -> Tile(coords, ROCK) isSand(coords) -> Tile(coords, SAND) else -> Tile(coords, AIR) } } private fun isFloor(coords: Coords) = coords.y >= maxY + 2 private fun isSand(coords: Coords) = floorSand.contains(coords) fun sandCapacity(): Int { return sands } companion object { fun of(input: List<String>): PathScanner { return PathScanner(input.map { it.toCoords() }) } } }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
5,493
AoC-2022
Apache License 2.0
src/main/kotlin/day5/day5.kt
lavong
317,978,236
false
null
/* --- Day 5: Binary Boarding --- You board your plane only to discover a new problem: you dropped your boarding pass! You aren't sure which seat is yours, and all of the flight attendants are busy with the flood of people that suddenly made it through passport control. You write a quick program to use your phone's camera to scan all of the nearby boarding passes (your puzzle input); perhaps you can find your seat through process of elimination. Instead of zones or groups, this airline uses binary space partitioning to seat people. A seat might be specified like FBFBBFFRLR, where F means "front", B means "back", L means "left", and R means "right". The first 7 characters will either be F or B; these specify exactly one of the 128 rows on the plane (numbered 0 through 127). Each letter tells you which half of a region the given seat is in. Start with the whole list of rows; the first letter indicates whether the seat is in the front (0 through 63) or the back (64 through 127). The next letter indicates which half of that region the seat is in, and so on until you're left with exactly one row. For example, consider just the first seven characters of FBFBBFFRLR: Start by considering the whole range, rows 0 through 127. F means to take the lower half, keeping rows 0 through 63. B means to take the upper half, keeping rows 32 through 63. F means to take the lower half, keeping rows 32 through 47. B means to take the upper half, keeping rows 40 through 47. B keeps rows 44 through 47. F keeps rows 44 through 45. The final F keeps the lower of the two, row 44. The last three characters will be either L or R; these specify exactly one of the 8 columns of seats on the plane (numbered 0 through 7). The same process as above proceeds again, this time with only three steps. L means to keep the lower half, while R means to keep the upper half. For example, consider just the last 3 characters of FBFBBFFRLR: Start by considering the whole range, columns 0 through 7. R means to take the upper half, keeping columns 4 through 7. L means to take the lower half, keeping columns 4 through 5. The final R keeps the upper of the two, column 5. So, decoding FBFBBFFRLR reveals that it is the seat at row 44, column 5. Every seat also has a unique seat ID: multiply the row by 8, then add the column. In this example, the seat has ID 44 * 8 + 5 = 357. Here are some other boarding passes: BFFFBBFRRR: row 70, column 7, seat ID 567. FFFBBBFRRR: row 14, column 7, seat ID 119. BBFFBBFRLL: row 102, column 4, seat ID 820. As a sanity check, look through your list of boarding passes. What is the highest seat ID on a boarding pass? --- Part Two --- Ding! The "fasten seat belt" signs have turned on. Time to find your seat. It's a completely full flight, so your seat should be the only missing boarding pass in your list. However, there's a catch: some of the seats at the very front and back of the plane don't exist on this aircraft, so they'll be missing from your list as well. Your seat wasn't at the very front or back, though; the seats with IDs +1 and -1 from yours will be in your list. What is the ID of your seat? */ package day5 import AdventOfCode fun main() { val input = AdventOfCode.file("day5/input") .lines() .filter { it.isNotEmpty() } val seatIds = input.map { calculateSeatId(it) } val highestSeatId = seatIds.maxOrNull()!! println("solution part1: $highestSeatId") (8..highestSeatId).filterNot { seatIds.contains(it) } .also { println("remaining seats: $it") } .also { println("solution part2: ${it.first()}") } } fun calculateSeatId(seat: String): Int { val row = seat.dropLast(3) val col = seat.drop(7) return row.toBinaryString().toInt(radix = 2) * 8 + col.toBinaryString().toInt(radix = 2) } fun String.toBinaryString(): String { return replace("F", "0") .replace("B", "1") .replace("R", "1") .replace("L", "0") }
0
Kotlin
0
1
a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f
4,030
adventofcode-2020
MIT License
src/main/kotlin/de/niemeyer/aoc2022/Day07.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
package de.niemeyer.aoc2022 /** * Advent of Code 2022, Day 7: No Space Left On Device * Problem Description: https://adventofcode.com/2022/day/7 */ import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName fun main() { fun part1(input: List<String>): Long = Computer(input).run { runUntilTerminate() result } fun part2(input: List<String>): Long = Computer(input).run { runUntilTerminate() toDelete } val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(part1(testInput) == 95_437L) println(part1(puzzleInput)) check(part1(puzzleInput) == 1_490_523L) check(part2(testInput) == 24_933_642L) println(part2(puzzleInput)) check(part2(puzzleInput) == 12_390_492L) } enum class Command { CD, LS, DIR } typealias Folder = List<String> interface ProgramLine data class Instruction(val cmd: Command, val arg: String) : ProgramLine data class FileInfo(val folder: Folder, val name: String, val size: Long) : ProgramLine data class DirInfo(val folder: Folder, val name: String) : ProgramLine data class Computer(val pgm: List<String>) { enum class ExecutionState { HALTED, RUNNING } private val PROMPT = "$ " private val DIR_ENTRY = "dir " private val ROOT_DIR = "/" private val PARENT_DIR = ".." private val TOTAL_DISK_CAPACITY = 70_000_000L private val NEEDED_SPACE = 30_000_000L private var instructionPointer: Int = 0 private val files = mutableMapOf<Pair<String, String>, Long>() private val cwd = mutableListOf<String>() var result = 0L var toDelete = 0L fun parseInput(input: String): ProgramLine = if (input.startsWith(PROMPT)) { input.substringAfter(PROMPT).split(" ").run { val instruction = Instruction(Command.valueOf(this.first().uppercase()), this.getOrNull(1) ?: "") if (instruction.cmd == Command.CD) { when (instruction.arg) { ROOT_DIR -> cwd.clear() PARENT_DIR -> cwd.removeAt(cwd.size - 1) else -> cwd.add(instruction.arg) } } instruction } } else if (input.startsWith(DIR_ENTRY)) { input.split(" ").run { DirInfo(cwd.toList(), this.last()) } } else if (input[0].isDigit()) { input.split(" ").run { FileInfo(cwd.toList(), this.last(), this.first().toLong()) } } else throw IllegalArgumentException(input) fun runUntilTerminate(): ExecutionState = generateSequence { executeStep() }.first { it != ExecutionState.RUNNING } private fun executeStep(): ExecutionState = when (instructionPointer) { !in pgm.indices -> { val dirs = files.keys .groupBy(keySelector = { it.first }, valueTransform = { files[it] }) val sumDirs = dirs.mapValues { (it.value as List<Long>).sum() } val sumInklSubDirs = sumDirs.mapValues { val dirAndSubs = sumDirs.filter { sub -> sub.key.startsWith(it.key) } val sums = dirAndSubs.values.sum() sums } val smallDirs = sumInklSubDirs.filter { it.value <= 100_000 } result = smallDirs.values.sum() val spaceUsed = sumInklSubDirs[ROOT_DIR] ?: 0 val spaceUnused = TOTAL_DISK_CAPACITY - spaceUsed val spaceNeeded = NEEDED_SPACE - spaceUnused val candidates = sumInklSubDirs.entries.filter { it.value >= spaceNeeded } toDelete = candidates.map { it.value }.sorted().first() ExecutionState.HALTED } else -> { val inst = parseInput(pgm[instructionPointer]) when (inst) { is FileInfo -> { val absFilename = inst.folder.joinToString(prefix = "/", separator = "/") files[absFilename to inst.name] = inst.size } is DirInfo -> { val absFilename = inst.folder.joinToString(prefix = "/", separator = "/") files[absFilename to inst.name] = 0 } } instructionPointer += 1 ExecutionState.RUNNING } } }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
4,699
AoC-2022
Apache License 2.0
src/main/kotlin/days/Day17.kt
TheMrMilchmann
725,205,189
false
{"Kotlin": 61669}
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* import utils.Direction.* import java.util.HashSet import java.util.PriorityQueue fun main() { val grid = readInput().map { it.toList().map(Char::digitToInt) }.toGrid() data class Momentum(val pos: GridPos, val dir: Direction, val steps: Int) data class HeatState(val heat: Int, val momentum: Momentum) fun part1(): Int { val queue = PriorityQueue(compareBy(HeatState::heat)) queue += HeatState(heat = 0, momentum = Momentum(pos = GridPos(0.hPos, 0.vPos), dir = E, steps = 0)) val visited = HashSet<Momentum>() while (queue.isNotEmpty()) { val (heat, momentum) = queue.remove() if (!visited.add(momentum)) continue if (momentum.pos == grid.positions.last()) return heat for (dir in Direction.entries) { if (dir == -momentum.dir) continue val steps = if (dir == momentum.dir) momentum.steps + 1 else 1 if (steps == 4) continue val position = when (dir) { N -> grid::shiftUp E -> grid::shiftRight S -> grid::shiftDown W -> grid::shiftLeft }(momentum.pos) ?: continue queue += HeatState(heat = heat + grid[position], Momentum(pos = position, dir = dir, steps = steps)) } } error("End never reached") } fun part2(): Int { val queue = PriorityQueue(compareBy(HeatState::heat)) queue += HeatState(heat = 0, momentum = Momentum(pos = GridPos(0.hPos, 0.vPos), dir = E, steps = 0)) val visited = HashSet<Momentum>() while (queue.isNotEmpty()) { val (heat, momentum) = queue.remove() if (!visited.add(momentum)) continue if (momentum.pos == grid.positions.last()) return heat for (dir in Direction.entries) { if (dir == -momentum.dir) continue if (momentum.steps < 4 && dir != momentum.dir) continue val steps = if (dir == momentum.dir) momentum.steps + 1 else 1 if (steps == 11) continue val position = when (dir) { N -> grid::shiftUp E -> grid::shiftRight S -> grid::shiftDown W -> grid::shiftLeft }(momentum.pos) ?: continue queue += HeatState(heat = heat + grid[position], Momentum(pos = position, dir = dir, steps = steps)) } } error("End never reached") } println("Part 1: ${part1()}") println("Part 2: ${part2()}") }
0
Kotlin
0
1
f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152
3,798
AdventOfCode2023
MIT License
src/day01/Day01.kt
chskela
574,228,146
false
{"Kotlin": 9406}
package day01 import java.io.File import java.util.PriorityQueue fun main() { fun parseInput(input: String) = input.split("\n\n").map { str -> str.lines().map { it.toInt() } } fun List<List<Int>>.topNElves(n: Int): Int { val best = PriorityQueue<Int>() for (calories in map { it.sum() }) { best.add(calories) if (best.size > n) { best.poll() } } return best.sum() } fun part1(input: String): Int { val data = parseInput(input) return data.topNElves(1) } fun part2(input: String): Int { val data = parseInput(input) return data.topNElves(3) } // test if implementation meets criteria from the description, like: val testInput = File("src/day01//Day01_test.txt").readText() check(part1(testInput) == 24000) println(part1(testInput)) println(part2(testInput)) val input = File("src/day01/Day01.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
951d38a894dcf0109fd0847eef9ff3ed3293fca0
1,049
adventofcode-2022-kotlin
Apache License 2.0
src/main/kotlin/recur/WeightedMedian.kt
yx-z
106,589,674
false
null
package recur import util.* import kotlin.math.floor // given an unsorted array S[1..n] of (value, weight) // find weighted median S[i] : total weight of elements that has value < S[i]_1 // is less than half of the total weight of S // similarly, total weight of elements that has value > S[i]_1 is also less than // half of the total weight of S fun OneArray<Tuple2<Int, Int>>.weightedMedian(targetWeight: Int = map { it.second }.sum() / 2): Tuple2<Int, Int> { val S = this val n = size if (n == 1) { return S[1] } val m = floor(n / 2.0).toInt() partitionTuple(1) val leftW = (1 until m).map { S[it].second }.sum() return if (leftW > targetWeight) { S[1..m].weightedMedian(targetWeight) } else { S[m + 1..n].weightedMedian(targetWeight - leftW) } } // similar partition method to the one in QuickSelect fun OneArray<Tuple2<Int, Int>>.partitionTuple(idx: Int) { val A = this val n = size swap(idx, n) var i = 0 var j = n while (i < j) { do { i++ } while (i < j && A[i].first < A[n].first) do { j-- } while (i < j && A[j].first > A[n].first) if (i < j) { swap(i, j) } } // now idx >= j swap(i, n) } fun main(args: Array<String>) { val S = oneArrayOf( 1 tu 20, 2 tu 15, 1 tu 16, 3 tu 23, 2 tu 40, 4 tu 33, 5 tu 30) println(S.weightedMedian()) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,322
AlgoKt
MIT License
kotlinx-collections-experimental/src/main/kotlin/kotlinx.collections.experimental/grouping/groupFold.kt
ilya-g
62,652,856
false
null
package kotlinx.collections.experimental.grouping public inline fun <T, K, R> Iterable<T>.groupAggregateBy(keySelector: (T) -> K, operation: (key: K, value: R?, element: T, first: Boolean) -> R): Map<K, R> { val result = mutableMapOf<K, R>() for (e in this) { val key = keySelector(e) val value = result[key] result[key] = operation(key, value, e, value == null && !result.containsKey(key)) } return result } public inline fun <T, K, R> Iterable<T>.groupFoldBy1(keySelector: (T) -> K, initialValueSelector: (K, T) -> R, operation: (K, R, T) -> R): Map<K, R> = groupAggregateBy(keySelector) { key, value, e, first -> operation(key, if (first) initialValueSelector(key, e) else value as R, e) } public inline fun <T, K, R> Iterable<T>.groupFoldBy(crossinline keySelector: (T) -> K): ((key: K, value: R?, element: T, first: Boolean) -> R) -> Map<K, R> = { operation -> groupAggregateBy(keySelector, operation) } public inline fun <T, K, R> Iterable<T>.groupFoldBy(keySelector: (T) -> K, initialValue: R, operation: (R, T) -> R): Map<K, R> = groupAggregateBy<T, K, R>(keySelector, { k, v, e, first -> operation(if (first) initialValue else v as R, e) }) public inline fun <T, K, R> Iterable<T>.groupReduceBy(keySelector: (T) -> K, reducer: Reducer<R, T>): Map<K, R> = groupAggregateBy(keySelector, { k, v, e, first -> if (first) reducer.initial(e) else reducer(v as R, e) }) public inline fun <T, K> Iterable<T>.groupCountBy(keySelector: (T) -> K): Map<K, Int> = groupFoldBy(keySelector, 0, { acc, e -> acc + 1 }) public inline fun <K> IntArray.groupCountBy(keySelector: (Int) -> K): Map<K, Int> { val result = mutableMapOf<K, Int>() for (e in this) { val key = keySelector(e) val value = result[key] result[key] = (value ?: 0) + 1 } return result } public inline fun <S, T : S, K> Iterable<T>.groupReduceBy(keySelector: (T) -> K, operation: (K, S, T) -> S): Map<K, S> { return groupAggregateBy(keySelector) { key, value, e, first -> if (first) e else operation(key, value as S, e) } } public inline fun <K> Iterable<Int>.groupBySum(keySelector: (Int) -> K): Map<K, Int> = groupReduceBy(keySelector, { k, sum, e -> sum + e }) public inline fun <T, K> Iterable<T>.groupBySumBy(keySelector: (T) -> K, valueSelector: (T) -> Int): Map<K, Int> = groupFoldBy(keySelector, 0, { acc, e -> acc + valueSelector(e)}) fun <T, K> Iterable<T>.countBy(keySelector: (T) -> K) = groupBy(keySelector).mapValues { it.value.fold(0) { acc, e -> acc + 1 } } fun main(args: Array<String>) { val values = listOf("apple", "fooz", "bisquit", "abc", "far", "bar", "foo") val keySelector = { s: String -> s[0] } val countByChar = values.groupFoldBy(keySelector, 0, { acc, e -> acc + 1 }) val sumLengthByChar: Map<Char, Int> = values.groupAggregateBy({ it[0] }) { k, v, e, first -> v ?: 0 + e.length } val sumLengthByChar2 = values.groupBySumBy( keySelector, { it.length } ) println(sumLengthByChar2) val countByChar2 = values.groupCountBy { it.first() } println(countByChar2) println(values.groupReduceBy(keySelector, Count)) println(values.groupReduceBy(keySelector, Sum.by { it.length })) }
0
Kotlin
3
1
41f2385b3921977329b0216ebcecc81d85ec7cb5
3,285
kotlinx.collections.experimental
Apache License 2.0
src/main/kotlin/g2001_2100/s2097_valid_arrangement_of_pairs/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2097_valid_arrangement_of_pairs // #Hard #Depth_First_Search #Graph #Eulerian_Circuit // #2023_06_28_Time_2120_ms_(100.00%)_Space_143.1_MB_(100.00%) import java.util.LinkedList import java.util.Queue @Suppress("NAME_SHADOWING") class Solution { fun validArrangement(pairs: Array<IntArray>): Array<IntArray> { val inOutedge = HashMap<Int, IntArray>() val adList = getAdList(pairs, inOutedge) val start = getStart(inOutedge) val res = Array(pairs.size) { IntArray(2) } getRes(start, adList, res, pairs.size - 1) return res } private fun getAdList( pairs: Array<IntArray>, inOutEdge: HashMap<Int, IntArray> ): HashMap<Int, Queue<Int>> { val adList = HashMap<Int, Queue<Int>>() for (pair in pairs) { val s = pair[0] val d = pair[1] val set = adList.computeIfAbsent(s) { _: Int? -> LinkedList() } set.add(d) val sEdgeCnt = inOutEdge.computeIfAbsent(s) { _: Int? -> IntArray(2) } val dEdgeCnt = inOutEdge.computeIfAbsent(d) { _: Int? -> IntArray(2) } sEdgeCnt[1]++ dEdgeCnt[0]++ } return adList } private fun getRes(k: Int, adList: HashMap<Int, Queue<Int>>, res: Array<IntArray>, idx: Int): Int { var idx = idx val edges = adList[k] ?: return idx while (edges.isNotEmpty()) { val edge = edges.poll() idx = getRes(edge, adList, res, idx) res[idx--] = intArrayOf(k, edge) } return idx } private fun getStart(map: HashMap<Int, IntArray>): Int { var start = -1 for ((k, value) in map) { val inEdge = value[0] val outEdge = value[1] start = k if (outEdge - inEdge == 1) { return k } } return start } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,929
LeetCode-in-Kotlin
MIT License
src/main/kotlin/Day17.kt
i-redbyte
433,743,675
false
{"Kotlin": 49932}
fun main() { val data = readInputFile("day17") val (xr, yr) = data.first().removePrefix("target area: ").split(", ") val (x1, x2) = xr.removePrefix("x=").split("..").map { it.toInt() } val (y1, y2) = yr.removePrefix("y=").split("..").map { it.toInt() } fun part1(): Int { var result = 0 for (vx0 in 1..1000) for (vy0 in 0..1000) { var vx = vx0 var vy = vy0 var x = 0 var y = 0 var maxY = 0 var ok = false while (x <= x2 && y >= y1) { x += vx y += vy maxY = maxOf(maxY, y) if (x in x1..x2 && y in y1..y2) { ok = true break } if (vx > 0){ vx-- } vy-- } if (ok) result = maxOf(result, maxY) } return result } fun part2(): Int { var result = 0 for (wX0 in 1..1000) { for (wY0 in -1000..1000) { var wX = wX0 var wY = wY0 var x = 0 var y = 0 var ok = false while (x <= x2 && y >= y1) { x += wX y += wY if (x in x1..x2 && y in y1..y2) { ok = true break } if (wX > 0){ wX-- } wY-- } if (ok) { result++ } } } return result } println("Result part1: ${part1()}") println("Result part2: ${part2()}") }
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
1,791
AOC2021
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day7.kt
EmRe-One
434,793,519
false
{"Kotlin": 44202}
package tr.emreone.adventofcode.days @OptIn(ExperimentalUnsignedTypes::class) object Day7 { class Instruction(val variable: String, val operation: (vars: UShortArray) -> UShort, vararg val parameter: String) { var value: UShort? = null fun execute(vars: UShortArray): UShort { if (value == null) { value = operation(vars) } return value!! } } private fun parseInstruction(instruction: String): Instruction { if (instruction.startsWith("NOT")) { val regex = """NOT (\w+) -> (\w+)""".toRegex() val (var1, variable) = regex.matchEntire(instruction)!!.destructured return Instruction(variable, { it[0].inv() }, var1) } else { val regex0 = """(\d+) -> (\w+)""".toRegex() val regex1 = """(\w+) (AND|OR|LSHIFT|RSHIFT) (\w+) -> (\w+)""".toRegex() val regex2 = """(\w+) -> (\w+)""".toRegex() if (regex0.matches(instruction)) { val (value, variable) = regex0.matchEntire(instruction)!!.destructured return Instruction(variable, { it[0] }, value) } else if (regex1.matches(instruction)) { val (var1, operation, var2, variable) = regex1.find(instruction)!!.destructured return Instruction(variable, { when (operation) { "AND" -> it[0] and it[1] "OR" -> it[0] or it[1] "LSHIFT" -> (it[0].toInt() shl it[1].toInt()).toUShort() "RSHIFT" -> (it[0].toInt() shr it[1].toInt()).toUShort() else -> throw IllegalArgumentException("Unknown operation: $operation") } }, var1, var2) } else if (regex2.matches(instruction)){ val (var1, variable) = regex2.find(instruction)!!.destructured return Instruction(variable, { it[0] }, var1) } else { throw IllegalArgumentException("Unknown instruction: $instruction") } } } fun parseVariables(input: List<String>): Map<String, UShort> { val map = mutableMapOf<String, UShort>() val instructions = input.map { line -> parseInstruction(line) } while (instructions.any { it.value == null }) { instructions.forEach { inst -> if (inst.value == null) { val parameter = inst.parameter.map { if (it[0].isDigit()) { it.toUShort() } else { val nullableValue = map[it] nullableValue } } if (! parameter.any { it == null }) { map[inst.variable] = inst.execute(parameter.map { it!! }.toUShortArray()) } } } } return map } fun part1(input: List<String>): UShort { val map = parseVariables(input) return (map["a"] ?: 0) as UShort } fun part2(input: List<String>): UShort { val map = parseVariables(input) val valueForA = map["a"] ?: 0 val index = input.indexOfLast { it.contains("-> b") } val mutableList = input.toMutableList() mutableList[index] = "$valueForA -> b" val map2 = parseVariables(mutableList) return (map2["a"] ?: 0) as UShort } }
0
Kotlin
0
0
57f6dea222f4f3e97b697b3b0c7af58f01fc4f53
3,755
advent-of-code-2015
Apache License 2.0
src/main/kotlin/sschr15/aocsolutions/Day1.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import sschr15.aocsolutions.util.Challenge import sschr15.aocsolutions.util.ReflectivelyUsed import sschr15.aocsolutions.util.challenge import sschr15.aocsolutions.util.ints import sschr15.aocsolutions.util.watched.sum /** * AOC 2023 [Day 1](https://adventofcode.com/2023/day/1) * Challenge: Find the first and last number, make them into a two digit number, and add them all together. */ object Day1 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 1) { // test() part1 { inputLines.map { s -> "${s.first { it.isDigit() }}${s.last { it.isDigit() }}" }.ints().sum() } part2 { val nums = mapOf( "zero" to 0, "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, ) val searchValues = nums.entries.flatMap { (name, num) -> listOf(name, num.toString()) } inputLines.sumOf { s -> val first = s.findAnyOf(searchValues)!!.let { (_, result) -> nums[result] ?: result.toInt() } val second = s.findLastAnyOf(searchValues)!!.let { (_, result) -> nums[result] ?: result.toInt() } first * 10 + second } } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
1,555
advent-of-code
MIT License
2022/src/test/kotlin/Day03.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class Day03 : StringSpec({ "puzzle part 01" { val sumOfPriorities = getPuzzleInput("day03-input.txt") .map { it.duplicated() } .sumOf { it.priority() } sumOfPriorities shouldBe 7446 } "puzzle part 02" { val sumOfPriorities = getPuzzleInput("day03-input.txt") .map { rucksack -> rucksack.filterNot { it == rucksack.duplicated() } } .chunked(3) .map { it[0].toSet() intersect it[1].toSet() intersect it[2].toSet() } .sumOf { it.single().priority() } sumOfPriorities shouldBe 2646 } }) private fun String.duplicated() = this .map { chunked(length / 2) } .map { it[0].toSet() intersect it[1].toSet() } .first().single() private fun Char.priority() = if (isLowerCase()) code - 97 + 1 else code - 65 + 27
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
916
adventofcode
MIT License
src/main/kotlin/day6/Day6.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day6 class Day6(val input: String) { private val listOfWindows = (0..input.length-4).map { input.substring(it, it+4) } private val messageMarkerWindows = (0..input.length-14).map { input.substring(it, it+14) } fun startOfPacket(): Int { return listOfWindows.indexOfFirst { !it.containsDuplicates() } + 4 } fun startOfMessage(): Int { return messageMarkerWindows.indexOfFirst { !it.containsDuplicates() } + 14 } override fun toString(): String { return input } } fun String.containsDuplicates(): Boolean { return this.toCharArray().distinct().size != this.toCharArray().size } fun main() { val test1 = Day6("mjqjpqmgbljsphdztnvjfqwrcgsmlb") val test2 = Day6("bvwbjplbgvbhsrlpgdmjqwftvncz") val test3 = Day6("nppdvjthqldpwncqszvftbrmjlhg") val test4 = Day6("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") val test5 = Day6("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") check(test1.startOfPacket() == 7) check(test2.startOfPacket() == 5) check(test3.startOfPacket() == 6) check(test4.startOfPacket() == 10) check(test5.startOfPacket() == 11) check(test1.startOfMessage() == 19) check(test2.startOfMessage() == 23) check(test3.startOfMessage() == 23) check(test4.startOfMessage() == 29) check(test5.startOfMessage() == 26) val input = Day6::class.java.getResourceAsStream("/day6_input.txt").bufferedReader().readLines().first() val day6 = Day6(input) println("Part1 = ${day6.startOfPacket()}") println("Part2 = ${day6.startOfMessage()}") }
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
1,596
adventofcode2022
Apache License 2.0
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/ints.kt
ca-r0-l
258,232,982
true
{"Kotlin": 2272378, "HTML": 423, "Java": 153}
package io.kotest.property.arbitrary import io.kotest.property.Shrinker import kotlin.math.abs import kotlin.random.nextInt import io.kotest.property.Arb fun Arb.Companion.int(min: Int, max: Int) = int(min..max) /** * Returns an [Arb] where each value is a randomly chosen [Int] in the given range. * The edgecases are: [[Int.MIN_VALUE], [Int.MAX_VALUE], 0, 1, -1] */ fun Arb.Companion.int(range: IntRange = Int.MIN_VALUE..Int.MAX_VALUE) = arb(IntShrinker, listOf(0, Int.MAX_VALUE, Int.MIN_VALUE)) { it.random.nextInt(range) } /** * Returns an [Arb] where each value is a randomly chosen natural integer. * The edge cases are: [Int.MAX_VALUE] */ fun Arb.Companion.nats(max: Int = Int.MAX_VALUE) = int(1..max).filter { it > 0 } /** * Returns an [Arb] where each value is a randomly chosen negative integer. * The edge cases are: [Int.MIN_VALUE] */ fun Arb.Companion.negativeInts(min: Int = Int.MIN_VALUE) = int(min..0).filter { it < 0 } /** * Returns an [Arb] where each value is a randomly chosen positive integer. * The edge cases are: [Int.MAX_VALUE] */ fun Arb.Companion.positiveInts(max: Int = Int.MAX_VALUE) = int(1..max).filter { it > 0 } object IntShrinker : Shrinker<Int> { override fun shrink(value: Int): List<Int> = when (value) { 0 -> emptyList() 1, -1 -> listOf(0) else -> { val a = listOf(abs(value), value / 3, value / 2, value * 2 / 3) val b = (1..5).map { value - it }.reversed().filter { it > 0 } (a + b).distinct() .filterNot { it == value } } } } fun <A, B> Shrinker<A>.bimap(f: (B) -> A, g: (A) -> B): Shrinker<B> = object : Shrinker<B> { override fun shrink(value: B): List<B> = this@bimap.shrink(f(value)).map(g) }
1
null
0
1
e176cc3e14364d74ee593533b50eb9b08df1f5d1
1,766
kotest
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12950.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12950 * * 행렬의 덧셈 * 문제 설명 * 행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. * 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요. * * 제한 조건 * 행렬 arr1, arr2의 행과 열의 길이는 500을 넘지 않습니다. * 입출력 예 * arr1 arr2 return * [[1,2],[2,3]] [[3,4],[5,6]] [[4,6],[7,9]] * [[1],[2]] [[3],[4]] [[4],[6]] */ fun main() { solution(arrayOf(intArrayOf(1,2), intArrayOf(2,3)), arrayOf(intArrayOf(3,4), intArrayOf(5,6))) } private fun solution(arr1: Array<IntArray>, arr2: Array<IntArray>): Array<IntArray> { val rowSize = arr1.size val colSize = arr1[0].size val answer = Array(rowSize) { IntArray(colSize) } for (i in 0 until rowSize) { for (j in 0 until colSize) { answer[i][j] = arr1[i][j] + arr2[i][j] } } return answer }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,136
HoOne
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DeleteAndEarn.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.ln import kotlin.math.max /** * 740. Delete and Earn * @see <a href="https://leetcode.com/problems/delete-and-earn/">Source</a> */ fun interface DeleteAndEarn { operator fun invoke(nums: IntArray): Int } /** * Approach 1: Top-Down Dynamic Programming */ class DeleteAndEarnTopDown : DeleteAndEarn { private val points = HashMap<Int, Int>() private val cache = HashMap<Int, Int>() override operator fun invoke(nums: IntArray): Int { var maxNumber = 0 // Precompute how many points we gain from taking an element for (num in nums) { points[num] = points.getOrDefault(num, 0) + num maxNumber = max(maxNumber, num) } return maxPoints(maxNumber) } private fun maxPoints(num: Int): Int { // Check for base cases if (num == 0) { return 0 } if (num == 1) { return points.getOrDefault(1, 0) } if (cache.containsKey(num)) { return cache[num] ?: -1 } // Apply recurrence relation val gain = points.getOrDefault(num, 0) cache[num] = max(maxPoints(num - 1), maxPoints(num - 2) + gain) return cache[num] ?: -1 } } /** * Approach 2: Bottom-Up Dynamic Programming */ class DeleteAndEarnBottomUp : DeleteAndEarn { override operator fun invoke(nums: IntArray): Int { if (nums.isEmpty()) return 0 val points = HashMap<Int, Int>() var maxNumber = 0 // Precompute how many points we gain from taking an element for (num in nums) { points[num] = points.getOrDefault(num, 0) + num maxNumber = max(maxNumber, num) } // Declare our array along with base cases val maxPoints = IntArray(maxNumber + 1) maxPoints[1] = points.getOrDefault(1, 0) for (num in 2 until maxPoints.size) { // Apply recurrence relation val gain = points.getOrDefault(num, 0) maxPoints[num] = max(maxPoints[num - 1], maxPoints[num - 2] + gain) } return maxPoints[maxNumber] } } /** * Approach 3: Space Optimized Bottom-Up Dynamic Programming */ class DeleteAndEarnBottomUpOpt : DeleteAndEarn { override operator fun invoke(nums: IntArray): Int { var maxNumber = 0 val points = HashMap<Int, Int>() // Precompute how many points we gain from taking an element for (num in nums) { points[num] = points.getOrDefault(num, 0) + num maxNumber = max(maxNumber, num) } // Base cases var twoBack = 0 var oneBack = points.getOrDefault(1, 0) for (num in 2..maxNumber) { val temp = oneBack oneBack = max(oneBack, twoBack + points.getOrDefault(num, 0)) twoBack = temp } return oneBack } } /** * Approach 4: Iterate Over Elements */ class DeleteAndEarnIterative : DeleteAndEarn { override operator fun invoke(nums: IntArray): Int { val points = HashMap<Int, Int>() // Precompute how many points we gain from taking an element for (num in nums) { points[num] = points.getOrDefault(num, 0) + num } val elements: List<Int> = ArrayList(points.keys).sorted() // Base cases var twoBack = 0 var oneBack = points[elements.firstOrNull()] ?: 0 for (i in 1 until elements.size) { val currentElement = elements[i] val temp = oneBack if (currentElement == elements[i - 1] + 1) { // The 2 elements are adjacent, cannot take both - apply normal recurrence oneBack = max(oneBack, twoBack + points.getOrDefault(currentElement, 0)) } else { // Otherwise, we don't need to worry about adjacent deletions oneBack += points[currentElement] ?: 0 } twoBack = temp } return oneBack } } class DeleteAndEarnBest : DeleteAndEarn { override operator fun invoke(nums: IntArray): Int { var maxNumber = 0 val points = HashMap<Int, Int>() for (num in nums) { points[num] = points.getOrDefault(num, 0) + num maxNumber = max(maxNumber, num) } var twoBack = 0 var oneBack: Int val n = points.size if (maxNumber < n + n * ln(n.toDouble()) / ln(2.0)) { oneBack = points.getOrDefault(1, 0) for (num in 2..maxNumber) { val temp = oneBack oneBack = max(oneBack, twoBack + points.getOrDefault(num, 0)) twoBack = temp } } else { val elements: List<Int> = ArrayList(points.keys).sorted() oneBack = points[elements.firstOrNull()] ?: 0 for (i in 1 until elements.size) { val currentElement = elements[i] val temp = oneBack if (currentElement == elements[i - 1] + 1) { oneBack = max(oneBack, twoBack + points.getOrDefault(currentElement, 0)) } else { oneBack += points.getOrDefault(currentElement, 0) } twoBack = temp } } return oneBack } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,995
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/UnequalTriplets.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 2475. Number of Unequal Triplets in Array * @see <a href="https://leetcode.com/problems/number-of-unequal-triplets-in-array/">Source</a> */ fun interface UnequalTriplets { operator fun invoke(nums: IntArray): Int } class UnequalTripletsOnePass : UnequalTriplets { override operator fun invoke(nums: IntArray): Int { var trips = 0 var pairs = 0 val count = IntArray(LIMIT) for (i in nums.indices) { trips += pairs - count[nums[i]] * (i - count[nums[i]]) pairs += i - count[nums[i]] count[nums[i]] += 1 } return trips } companion object { private const val LIMIT = 1001 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,337
kotlab
Apache License 2.0
src/Day02.kt
guilherme
574,434,377
false
{"Kotlin": 7468}
import java.lang.RuntimeException enum class RoundResult(val score: Int) { LOST(0), DRAW(3), WIN(6); companion object { fun fromString(input: String): RoundResult { // X means you need to lose, // Y means you need to end the round in a draw, // and Z means you need to win. return when (input) { "X" -> LOST "Y" -> DRAW "Z" -> WIN else -> throw RuntimeException("Invalid round result input: ${input}") } } } } sealed class Hand(val score: Int) { abstract fun versus(opponentHand: Hand): RoundResult abstract fun toEndInResult(resultingScore: RoundResult): Hand object ROCK : Hand(1) { override fun versus(opponentHand: Hand): RoundResult { return when (opponentHand) { PAPER -> RoundResult.LOST ROCK -> RoundResult.DRAW SCISSORS -> RoundResult.WIN } } override fun toEndInResult(resultingScore: RoundResult): Hand { return when (resultingScore) { RoundResult.LOST -> SCISSORS RoundResult.DRAW -> ROCK RoundResult.WIN -> PAPER } } } object PAPER : Hand(2) { override fun versus(opponentHand: Hand): RoundResult { return when (opponentHand) { PAPER -> RoundResult.DRAW ROCK -> RoundResult.WIN SCISSORS -> RoundResult.LOST } } // what is the hand I should oppose so that I can get the given result. override fun toEndInResult(resultingScore: RoundResult): Hand { return when (resultingScore) { RoundResult.LOST -> ROCK RoundResult.DRAW -> PAPER RoundResult.WIN -> SCISSORS } } } object SCISSORS : Hand(3) { override fun versus(opponentHand: Hand): RoundResult { return when (opponentHand) { PAPER -> RoundResult.WIN ROCK -> RoundResult.LOST SCISSORS -> RoundResult.DRAW } } override fun toEndInResult(resultingScore: RoundResult): Hand { return when (resultingScore) { RoundResult.LOST -> PAPER RoundResult.DRAW -> SCISSORS RoundResult.WIN -> ROCK } } } companion object { fun fromMyPlay(input: String): Hand { return when (input) { "X" -> ROCK // paper. rock + paper = win "Y" -> PAPER // scissosr. rock + scissors= lost "Z" -> SCISSORS else -> throw RuntimeException("Invalid hand input: ${input}") } } fun fromOpponentPlay(input: String): Hand { return when (input) { "A" -> ROCK // paper. rock + paper = win "B" -> PAPER // scissosr. rock + scissors= lost "C" -> SCISSORS else -> throw RuntimeException("Invalid opponent play input: ${input}") } } } } fun main() { fun scoreRound(round: String): Int { val (opponent, myPlay) = round.split(" ") val play = Hand.fromMyPlay(myPlay) val opponentHand = Hand.fromOpponentPlay(opponent); return play.versus(opponentHand).score + play.score } fun part1(input: List<String>): Int { return input.map { scoreRound(round = it) }.sum() } fun scoreResultingRound(round: String): Int { val (opponent, myResult) = round.split(" ") val result = RoundResult.fromString(myResult) val opponentHand = Hand.fromOpponentPlay(opponent) val myPlay = opponentHand.toEndInResult(result) return myPlay.score + result.score } fun part2(input: List<String>): Int { return input.map { scoreResultingRound(round = it) }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val result1 = part1(testInput) check(result1 == 15) println("check 1 ok") val result2 = part2(testInput) check(result2 == 12) println("check 2 ok") val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
3
dfc0cee1d023be895f265623bec130386ed12f05
3,904
advent-of-code
Apache License 2.0
src/day8/subarraySumAlgorithm.kt
minielectron
332,678,510
false
{"Java": 127791, "Kotlin": 48336}
package day8 // Problem : Given an datastructure.array of integers, you have find if there are two numbers whose sum is equal to k. // 2 Sum - k=2 class subarraySumAlgorithm { fun findTwoSum(a: IntArray, k: Int): Boolean { var end = a.size - 1 var start = 0 a.sort() while (start < a.size) { val sum = a[start] + a[end] when { sum > k -> { end-- } sum < k -> { start++ } else -> { return true } } } return false } fun findThreeSum(a: IntArray, k: Int): Boolean { var start = 0 val end = a.size - 1 while (start < end){ if (findTwoSum(a.copyOfRange(start+1, end), k -a[start])){ return true } start++ } return false } } fun main() { val twoSumAlgorithm = subarraySumAlgorithm() val a = intArrayOf(2, -1, 0, 3, 2, 1, -1, 2) a.sort() // println(twoSumAlgorithm.findTwoSum(a, 6)) println(twoSumAlgorithm.findThreeSum(a, 0)) println(twoSumAlgorithm.findThreeSum(a, 3)) println(twoSumAlgorithm.findThreeSum(a, 11)) }
0
Java
0
0
f2aaff0a995071d6e188ee19f72b78d07688a672
1,291
data-structure-and-coding-problems
Apache License 2.0
Unprimeable_numbers/Kotlin/src/main/kotlin/UnprimeableNumbers.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
private const val MAX = 10000000 private val primes = BooleanArray(MAX) fun main() { sieve() println("First 35 unprimeable numbers:") displayUnprimeableNumbers(35) val n = 600 println() println("The ${n}th unprimeable number = ${nthUnprimeableNumber(n)}") println() val lowest = genLowest() println("Least unprimeable number that ends in:") for (i in 0..9) { println(" $i is ${lowest[i]}") } } private fun genLowest(): IntArray { val lowest = IntArray(10) var count = 0 var test = 1 while (count < 10) { test++ if (unPrimable(test) && lowest[test % 10] == 0) { lowest[test % 10] = test count++ } } return lowest } private fun nthUnprimeableNumber(maxCount: Int): Int { var test = 1 var count = 0 var result = 0 while (count < maxCount) { test++ if (unPrimable(test)) { count++ result = test } } return result } private fun displayUnprimeableNumbers(maxCount: Int) { var test = 1 var count = 0 while (count < maxCount) { test++ if (unPrimable(test)) { count++ print("$test ") } } println() } private fun unPrimable(test: Int): Boolean { if (primes[test]) { return false } val s = test.toString() + "" for (i in s.indices) { for (j in 0..9) { if (primes[replace(s, i, j).toInt()]) { return false } } } return true } private fun replace(str: String, position: Int, value: Int): String { val sChar = str.toCharArray() sChar[position] = value.toChar() return str.substring(0, position) + value + str.substring(position + 1) } private fun sieve() { // primes for (i in 2 until MAX) { primes[i] = true } for (i in 2 until MAX) { if (primes[i]) { var j = 2 * i while (j < MAX) { primes[j] = false j += i } } } }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
2,088
rosetta
MIT License
libraries/gemoji/src/main/kotlin/io/sweers/catchup/gemoji/EmojiMarkdownConverter.kt
pyricau
224,052,604
false
null
/* * Copyright (C) 2019. <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.gemoji /** * Converts a markdown emoji alias (eg, ":smile:") into an android render-able emoji. */ interface EmojiMarkdownConverter { fun convert(alias: String): String? } internal class GemojiEmojiMarkdownConverter( private val gemojiDao: GemojiDao ) : EmojiMarkdownConverter { override fun convert(alias: String): String? { return gemojiDao.getEmoji(alias) } } fun Sequence<Char>.asString(): String { return buildString { this@asString.forEach { append(it) } } } fun Sequence<Char>.asString(capacity: Int): String { return buildString(capacity) { this@asString.forEach { append(it) } } } /** * Returns a [String] that replaces occurrences of markdown emojis with android render-able emojis. */ fun EmojiMarkdownConverter.replaceMarkdownEmojisIn(markdown: String): String { return replaceMarkdownEmojisIn(markdown.asSequence()).asString(markdown.length) } /** * This is the longest possible alias length, so we can use its length for our aliasBuilder var * below to reuse it and never have to resize it. */ private const val MAX_ALIAS_LENGTH = "south_georgia_south_sandwich_islands".length /** * Returns a [Sequence<Char>][Sequence] that replaces occurrences of markdown emojis with android * render-able emojis. */ fun EmojiMarkdownConverter.replaceMarkdownEmojisIn(markdown: Sequence<Char>): Sequence<Char> { val aliasBuilder = StringBuilder(MAX_ALIAS_LENGTH) var startAlias = false return sequence { markdown.forEach { char -> if (startAlias || aliasBuilder.isNotEmpty()) { if (startAlias && char == ':') { // Double ::, so emit a colon and keep startAlias set yield(':') return@forEach } startAlias = false when (char) { ' ' -> { // Aliases can't have spaces, so bomb out and restart yield(':') yieldAll(aliasBuilder.asSequence()) yield(' ') aliasBuilder.setLength(0) } ':' -> { val potentialAlias = aliasBuilder.toString() val potentialEmoji = convert(potentialAlias) // If we find an emoji append it and reset alias start, if we don't find an emoji // append between the potential start and this index *and* consider this index the new // potential start. if (potentialEmoji != null) { yieldAll(potentialEmoji.asSequence()) } else { yield(':') yieldAll(potentialAlias.asSequence()) // Start a new alias from this colon as we didn't have a match with the existing close startAlias = true } aliasBuilder.setLength(0) } else -> aliasBuilder.append(char) } } else { if (char == ':') { startAlias = true } else { yield(char) } } } // If we started an alias but ran out of characters, flush it if (startAlias) { yield(':') } else if (aliasBuilder.isNotEmpty()) { yield(':') yieldAll(aliasBuilder.asSequence()) } } }
2
Kotlin
3
29
d5629cf6ebdea64099e0f46e5290328c73b54bef
3,760
CatchLeaks
Apache License 2.0
src/day04.kts
miedzinski
434,902,353
false
{"Kotlin": 22560, "Shell": 113}
data class Board(val rows: List<List<Int>>) { val columns: List<List<Int>> by lazy { (0 until rows.size).map { col -> (0 until rows.size).map { row -> rows[row][col] } } } } val boardSize = 5 val allDraws = readLine()!!.split(',').map(String::toInt).toList() var boards = generateSequence(::readLine).chunked(boardSize + 1) { it.asSequence() .drop(1) .map { it.trimStart().split("\\s+".toRegex()).map(String::toInt) } .toList() .let(::Board) }.toList() val wins = sequence { val draws = mutableSetOf<Int>() for (num in allDraws) { draws.add(num) val (winningBoards, others) = boards.partition { (it.rows + it.columns).any(draws::containsAll) } boards = others winningBoards.map { it.rows.flatten().filterNot(draws::contains).sum() * num }.also { yieldAll(it) } } } println("part1: ${wins.first()}") println("part2: ${wins.last()}")
0
Kotlin
0
0
6f32adaba058460f1a9bb6a866ff424912aece2e
972
aoc2021
The Unlicense
src/main/kotlin/days/aoc2021/Day14.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2021 import days.Day class Day14 : Day(2021, 14) { override fun partOne(): Any { return findDeltaBetweenMostAndLeastCommonElements2(inputList, 10) } override fun partTwo(): Any { return findDeltaBetweenMostAndLeastCommonElements2(inputList, 40) } // idiot version fun findDeltaBetweenMostAndLeastCommonElements(inputList: List<String>, steps: Int): Long { var template = inputList.firstOrNull() ?: throw IllegalStateException() val substitutionMap = mutableMapOf<String,String>() inputList.drop(2).forEach { line -> Regex("(\\w+) -> (\\w)").matchEntire(line.trim())?.destructured?.let { (pattern, insertion) -> substitutionMap[pattern] = insertion } } for (step in 1..steps) { template = template.windowed(2).fold("") { acc, string -> acc + string[0] + (substitutionMap[string] ?: "") } + template.last() println(template) } val counts = mutableMapOf<Char,Long>() template.forEach { c -> counts[c] = counts.getOrDefault(c, 0) + 1 } return counts.maxOf { it.value } - counts.minOf { it.value } } // the version where we keep counts of pairs fun findDeltaBetweenMostAndLeastCommonElements2(inputList: List<String>, steps: Int): Long { var template = inputList.firstOrNull() ?: throw IllegalStateException() val substitutionMap = mutableMapOf<String,String>() inputList.drop(2).forEach { line -> Regex("(\\w+) -> (\\w)").matchEntire(line.trim())?.destructured?.let { (pattern, insertion) -> substitutionMap[pattern] = insertion } } var pairCounts = mutableMapOf<String,Long>() var letterCounts = mutableMapOf<Char,Long>() template.windowed(2).forEach { pairCounts[it] = pairCounts.getOrDefault(it, 0L) + 1 } template.forEach { char -> letterCounts[char] = letterCounts.getOrDefault(char, 0L) + 1 } repeat (steps) { val newlyCreatePairCounts = mutableMapOf<String,Long>() // increment the pairs for the substitutions, first letter of pair with sub and sub with last letter of pair. // we're replacing a pair with two "new" pairs, so we're double counting a bit. pairCounts.forEach { (pair, count) -> letterCounts[substitutionMap[pair]!!.first()] = letterCounts.getOrDefault(substitutionMap[pair]!!.first(), 0L) + count ("" + pair[0] + substitutionMap[pair]).let { key -> newlyCreatePairCounts[key] = newlyCreatePairCounts.getOrDefault(key, 0L) + count } ("" + substitutionMap[pair] + pair[1]).let { key -> newlyCreatePairCounts[key] = newlyCreatePairCounts.getOrDefault(key, 0L) + count } } pairCounts = newlyCreatePairCounts } return with(letterCounts) { maxOf { it.value } - minOf { it.value } } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
3,151
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/2020/Day4_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import kotlin.collections.ArrayList import kotlin.text.Regex val fields = listOf("byr","iyr","eyr","hgt","hcl","ecl","pid") val eyes = listOf("amb","blu","brn","gry","grn","hzl","oth") var passportList = ArrayList<String>() var passport = "" File("input/2020/day4").forEachLine { passport = if (!it.isEmpty()) "$passport $it" else { passportList.add(passport.trim()) "" } } fun validateField(name: String, value: String) = when (name) { "byr" -> value.toInt() in 1920..2002 "iyr" -> value.toInt() in 2010..2020 "eyr" -> value.toInt() in 2020..2030 "hgt" -> if (value.endsWith("cm")) { value.replace("cm", "").toInt() in 150..193 } else if (value.endsWith("in")) { value.replace("in", "").toInt() in 59..76 } else false "hcl" -> value.matches(Regex("#[\\da-f]{6}")) "ecl" -> eyes.contains(value) "pid" -> value.matches(Regex("[\\d]{9}")) else -> false } passportList.add(passport) var count = 0 passportList.forEach { p -> if (fields.filter { p.contains(it) }.size == 7) { var validFields = 0 p.split(" ").forEach { field -> if (field.split(":").size == 2) { val (name,value) = field.split(":") if (validateField(name, value)) validFields++ } } if (validFields == 7) count++ } } println(count)
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,390
adventofcode
MIT License
domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/schulze/Schulze.kt
SeanShubin
228,113,855
false
null
package com.seanshubin.kotlin.tryme.domain.schulze import kotlin.math.max import kotlin.math.min object Schulze { fun schulzeTally(candidates: List<String>, rows: List<List<Int>>): List<Pair<String, List<String>>> { val strongestPaths = strongestPaths(rows) val tallied = tally(strongestPaths, emptyList(), emptyList()) val result = mutableListOf<Pair<String, List<String>>>() var place = 1 tallied.forEach { talliedRow -> val candidatesAtPlace = talliedRow.map { candidates[it] } val placeString = placeString(place) result.add(Pair(placeString, candidatesAtPlace)) place += talliedRow.size } return result } fun strongestPaths(rows: List<List<Int>>): List<List<Int>> { val size = rows.size val strongestPaths = mutableList2(size, size) for (i in 0 until size) { for (j in 0 until size) { strongestPaths[i][j] = rows[i][j] } } for (i in 0 until size) { for (j in 0 until size) { if (i != j) { for (k in 0 until size) { if (i != k && j != k) { strongestPaths[j][k] = max(strongestPaths[j][k], min(strongestPaths[j][i], strongestPaths[i][k])) } } } } } return strongestPaths } tailrec fun tally(rows: List<List<Int>>, soFar: List<List<Int>>, indices: List<Int>): List<List<Int>> { val size = rows.size return if (indices.size == size) soFar else { val undefeated = (0 until size).filter { i -> !indices.contains(i) && (0 until size).all { j -> indices.contains(j) || rows[i][j] >= rows[j][i] } } tally(rows, soFar + listOf(undefeated), indices + undefeated) } } private fun mutableList2(rowCount: Int, colCount: Int): MutableList<MutableList<Int>> = mutableListOf(*(0 until rowCount).map { mutableListOf(*(0 until colCount).map { 0 }.toTypedArray()) }.toTypedArray()) private fun placeString(place: Int): String = when (place) { 1 -> "1st" 2 -> "2nd" 3 -> "3rd" else -> "${place}th" } }
0
Kotlin
0
0
abc67c5f43c01bdf55c6d4adcf05b77610c0473a
2,440
kotlin-tryme
The Unlicense
src/iii_conventions/MyDate.kt
dgyordanov
144,988,264
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { return when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } } operator fun plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval, 1) operator fun plus(repeatedTimeInterval: RepeatedTimeInterval) = addTimeIntervals(repeatedTimeInterval.timeInterval, repeatedTimeInterval.times) } operator fun MyDate.rangeTo(other: MyDate) = DateRange(this, other) enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(val start: MyDate, val endInclusive: MyDate) { operator fun contains(d: MyDate): Boolean { return start <= d && d <= endInclusive } operator fun iterator() = DateRangeIterator(this) } class DateRangeIterator(val dateRange: DateRange) : Iterator<MyDate> { private var current = dateRange.start override fun next(): MyDate { val next = current current = current.nextDay() return next } override fun hasNext() : Boolean = current <= dateRange.endInclusive } class RepeatedTimeInterval(val timeInterval: TimeInterval, val times: Int) operator fun TimeInterval.times(times: Int) = RepeatedTimeInterval(this, times)
0
Kotlin
0
0
9e1042c8ca3de4a3ee759d89f5fb23930f836b51
1,425
kotlin-koans
MIT License
src/main/kotlin/novah/data/DAG.kt
stackoverflow
255,379,925
false
null
/** * 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 novah.data import java.util.* import kotlin.collections.HashSet /** * A Direct Acyclic Graph. * It doesn't actually check for cycles while adding nodes and links. */ class DAG<T, D> { private val nodes = mutableListOf<DagNode<T, D>>() fun addNodes(ns: Collection<DagNode<T, D>>) { nodes.addAll(ns) } fun size(): Int = nodes.size /** * Check if this graph has a cycle * and return the first if any. */ fun findCycle(): Set<DagNode<T, D>>? { val whiteSet = HashSet<DagNode<T, D>>(nodes) val graySet = HashSet<DagNode<T, D>>() val blackSet = HashSet<DagNode<T, D>>() val parentage = mutableMapOf<T, DagNode<T, D>?>() // depth-first search fun dfs(current: DagNode<T, D>, parent: DagNode<T, D>? = null): DagNode<T, D>? { whiteSet.remove(current) graySet.add(current) parentage[current.value] = parent for (neighbor in current.getNeighbors()) { if (blackSet.contains(neighbor)) continue // found cycle if (graySet.contains(neighbor)) return current val res = dfs(neighbor, current) if (res != null) return res } graySet.remove(current) blackSet.add(current) return null } while (whiteSet.size > 0) { val current = whiteSet.iterator().next() val cycled = dfs(current) if (cycled != null){ return reportCycle(cycled, parentage) } } return null } /** * Return a topological sorted representation * of this graph. */ fun topoSort(): Deque<DagNode<T, D>> { val visited = HashSet<T>() val stack = ArrayDeque<DagNode<T, D>>(nodes.size) fun helper(node: DagNode<T, D>) { visited += node.value for (neighbor in node.getNeighbors()) { if (visited.contains(neighbor.value)) continue helper(neighbor) } stack.push(node) } for (node in nodes.reversed()) { if (visited.contains(node.value)) continue helper(node) } return stack } private fun reportCycle(node: DagNode<T, D>, parentage: Map<T, DagNode<T, D>?>): Set<DagNode<T, D>> { val cycle = HashSet<DagNode<T, D>>() cycle += node var parent = parentage[node.value] while (parent != null) { cycle += parent parent = parentage[parent.value] } return cycle } } /** * A node in the DAG. * `value` has to be unique for every node. */ class DagNode<T, D>(val value: T, val data: D) { private val neighbors = mutableListOf<DagNode<T, D>>() fun link(other: DagNode<T, D>) { neighbors += other } fun getNeighbors(): List<DagNode<T, D>> = neighbors override fun equals(other: Any?): Boolean { if (this === other) return true val onode = other as? DagNode<*, *> ?: return false return value == onode.value } override fun hashCode(): Int = value.hashCode() override fun toString(): String = "Node($value)" }
0
Kotlin
0
9
f3f2b12e178c5288197f6c6d591e8d304f5baf5d
3,864
novah
Apache License 2.0
src/main/kotlin/g1301_1400/s1363_largest_multiple_of_three/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1363_largest_multiple_of_three // #Hard #Array #Dynamic_Programming #Greedy // #2023_06_06_Time_267_ms_(100.00%)_Space_39.5_MB_(100.00%) class Solution { fun largestMultipleOfThree(digits: IntArray): String { var sum = 0 val count = IntArray(10) // Here we are using the property that any no is divisible by 3 when its sum of digits is // divisible by 3 // get sum of digits and count of each digit for (x in digits) { sum += x count[x]++ } val sb = StringBuilder() var copied = count.copyOf(count.size) // if sum % 3 != 0 then processing required if (sum % 3 != 0) { var rem = sum % 3 var oldRem = rem while (oldRem != 0) { while (rem != 0) { // if the remainder that we are trying to delete and its required digits is not // present // then the value will become -ve at that digit copied[rem % 10]-- // increase the remainder by 3 each time a -ve value is found // and reset the rem and copied from orig count array and break if (copied[rem % 10] < 0) { oldRem += 3 rem = oldRem copied = count.copyOf(count.size) break } rem /= 10 if (rem == 0) { oldRem = 0 } } } } // generate the largest number by considering from the last digit ie 9,8,7,6... for (i in 9 downTo 0) { var `val` = copied[i] while (`val` > 0) { sb.append(i) `val`-- } } // check for any leading zeroes and remove while (sb.length > 1) { if (sb[0] != '0') { break } else { sb.deleteCharAt(0) } } return sb.toString() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,151
LeetCode-in-Kotlin
MIT License
src/model/Grid.kt
NOWUM
358,732,934
false
{"Kotlin": 245354, "TypeScript": 141516, "CSS": 4266, "HTML": 1721, "Dockerfile": 329}
package de.fhac.ewi.model import de.fhac.ewi.exceptions.IllegalGridException import de.fhac.ewi.util.DoubleFunction import de.fhac.ewi.util.repeatEach class Grid { private val _nodes = mutableListOf<Node>() val nodes: List<Node> get() = _nodes.toList() private val _pipes = mutableListOf<Pipe>() val pipes: List<Pipe> get() = _pipes.toList() val input: InputNode by lazy { _nodes.filterIsInstance<InputNode>().single() } // Returns maximum of needed pump power in W val neededPumpPower: Double get() = input.pumpPower.maxOrNull() ?: throw IllegalStateException("Needed pump power could not retrieved from grid.") // Returns energy demand of all outputs in Wh val totalOutputEnergy: Double by lazy { nodes.filterIsInstance<OutputNode>().sumOf { it.annualEnergyDemand } } // Returns total heat loss in all pipes in Wh val totalHeatLoss: Double get() = pipes.sumOf { it.annualHeatLoss } // Returns the node that has the most distance to source. This node is at the end of the longest path val mostDistantNode: Node by lazy { nodes.filterIsInstance<OutputNode>().maxByOrNull { it.pathToSource.sumOf(Pipe::length) }!! } val mostPressureLossNode: Node get() = nodes.filterIsInstance<OutputNode>().maxByOrNull { it.maxPressureLossInPath }!! private fun addNode(node: Node) { if (_nodes.any { it.id.equals(node.id, true) }) throw IllegalArgumentException("There is already an node with id ${node.id}") _nodes += node } fun addInputNode( id: String, groundSeries: TemperatureTimeSeries, flowTemperature: DoubleFunction, returnTemperature: DoubleFunction ) { if (_nodes.filterIsInstance<InputNode>().count() == 1) throw IllegalArgumentException("This grid has already an input node. Only one input node is supported at the moment.") addNode(InputNode(id, groundSeries.temperatures.repeatEach(24), flowTemperature, returnTemperature)) } fun addOutputNode(id: String, thermalEnergyDemand: HeatDemandCurve, pressureLoss: Double, replicas: Int = 1) { if (replicas > 1) addNode(ReplicaOutputNode(id, thermalEnergyDemand, pressureLoss, replicas)) else addNode(OutputNode(id, thermalEnergyDemand, pressureLoss)) } fun addIntermediateNode(id: String) { addNode(IntermediateNode(id)) } fun addPipe(id: String, sourceId: String, targetId: String, length: Double, pipeLayingDepth: Double) { if (_pipes.any { it.id.equals(id, true) }) throw IllegalArgumentException("There is already a pipe with id $id.") // Retrieve nodes effected by connection val source = _nodes.find { it.id == sourceId } ?: throw IllegalArgumentException("Node for source $sourceId not found.") val target = _nodes.find { it.id == targetId } ?: throw IllegalArgumentException("Node for target $targetId not found.") val pipe = if (target is ReplicaOutputNode) ReplicaPipe(id, source, target, length, pipeLayingDepth) else Pipe(id, source, target, length, pipeLayingDepth) source.connectChild(pipe) _pipes += pipe } fun validate() { // All nodes should have a pipe. Otherwise they are useless and should be deleted val pipelessNode = _nodes.firstOrNull { it.connectedChildNodes.size + it.connectedParentNodes.size == 0 } if (pipelessNode != null) throw IllegalGridException("Node ${pipelessNode.id} has no connection to other nodes.") // There must be exactly one input val inputNode = _nodes.filterIsInstance<InputNode>().singleOrNull() ?: throw IllegalGridException("The grid must contain exactly one input node.") // inputNode must have a connection to all output nodes _nodes.filterIsInstance<OutputNode>().forEach { outputNode -> if (!inputNode.isParentOf(outputNode)) throw IllegalGridException("Output node ${outputNode.id} is not connected to input node ${inputNode.id}.") } } }
18
Kotlin
0
4
7c65a8c372df6e3e8b1f2e1c4bc5833ba3dda987
4,183
grid-optimizer
MIT License
src/Day03.kt
becsegal
573,649,289
false
{"Kotlin": 9779}
import java.io.File fun main() { val letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun mispackedCharacter(contents: String): String { val compartmentAContents: CharArray = contents.substring(0, contents.length/2).toCharArray() val compartmentBContents: CharArray = contents.substring(contents.length/2).toCharArray() return compartmentAContents.intersect(compartmentBContents.asIterable()).first().toString() } fun commonCharacter(str1: String, str2: String, str3: String): String { return str1.toCharArray().intersect( str2.toCharArray().asIterable() ).intersect( str3.toCharArray().asIterable() ).first().toString() } fun part1(filename: String): Int? { var priorityTotal: Int = 0; File(filename).forEachLine { val char: String = mispackedCharacter(it) priorityTotal += letters.indexOf(char) + 1 } return priorityTotal; } fun part2(filename: String): Int? { var priorityTotal: Int = 0; var threesie: ArrayList<String> = ArrayList(); File(filename).forEachLine { threesie.add(it) if (threesie.size == 3) { val char: String = commonCharacter(threesie[0], threesie[1], threesie[2]) priorityTotal += letters.indexOf(char) + 1 threesie = ArrayList() } } return priorityTotal; } println("part 1: " + part1("input_day03.txt")) println("part 2: " + part2("input_day03.txt")) }
0
Kotlin
0
0
a4b744a3e3c940c382aaa1d5f5c93ae0df124179
1,611
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/sk/set0/78. Subsets.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set0 import kotlin.math.pow class Solution78 { // Backtracking fun subsets(nums: IntArray): List<List<Int>> { val ans = mutableListOf<List<Int>>() fun backtrack(tmpList: MutableList<Int>, start: Int) { ans.add(tmpList.toList()) // copy it and add it to answer for (i in start..nums.lastIndex) { tmpList.add(nums[i]) backtrack(tmpList, i + 1) tmpList.removeAt(tmpList.lastIndex) } } backtrack(mutableListOf(), 0) return ans } // Iterative fun subsets2(nums: IntArray): List<List<Int>> { val result: MutableList<List<Int>> = ArrayList() result.add(ArrayList()) for (n in nums) { val size = result.size for (i in 0 until size) { val subset: MutableList<Int> = ArrayList(result[i]) subset.add(n) result.add(subset) } } return result } // bit manipulation fun subsets3(nums: IntArray): List<List<Int>> { val output = mutableListOf<MutableList<Int>>() val n = nums.size for (i in 2.0.pow(n).toInt() until 2.0.pow(n + 1).toInt()) { // generate bitmask, from 0..00 to 1..11 val bitmask = Integer.toBinaryString(i).substring(1) // append subset corresponding to that bitmask val curr = mutableListOf<Int>() for (j in 0 until n) { if (bitmask[j] == '1') curr.add(nums[j]) } output.add(curr) } return output } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,636
leetcode-kotlin
Apache License 2.0
src/main/kotlin/solved/p289/InPlaceSolution.kt
mr-nothing
469,475,608
false
{"Kotlin": 162430}
package solved.p289 /** The idea is that we will store in original array: * -1 for dead-alive transition * 0 for dead-dead transition * 1 for alive-alive transition * 2 for alive-dead transition */ class InPlaceSolution { class Solution { fun gameOfLife(board: Array<IntArray>) { for (i in 0..board.lastIndex) { for (j in 0..board[0].lastIndex) { val currentValue = board[i][j] val adjacentValue = adjacentSum(board, i, j) if (currentValue == 1) { if (adjacentValue < 2 || adjacentValue > 3) { board[i][j] = 2 } else { board[i][j] = 1 } } else { if (adjacentValue == 3) { board[i][j] = -1 } } } } for (i in 0..board.lastIndex) { for (j in 0..board[0].lastIndex) { val currentValue = board[i][j] if (currentValue == -1) { board[i][j] = 1 } else if (currentValue == 2) { board[i][j] = 0 } } } } private fun adjacentSum(arr: Array<IntArray>, i: Int, j: Int): Int { return adjValue(arr, i - 1, j - 1) + adjValue(arr, i - 1, j) + adjValue(arr, i - 1, j + 1) + adjValue(arr, i, j - 1) + adjValue(arr, i, j + 1) + adjValue(arr, i + 1, j - 1) + adjValue(arr, i + 1, j) + adjValue(arr, i + 1, j + 1) } private fun adjValue(arr: Array<IntArray>, i: Int, j: Int): Int { if (i >= 0 && i <= arr.lastIndex && j >= 0 && j <= arr[0].lastIndex) { val value = arr[i][j] if (value == 1 || value == 2) { return 1 } } return 0 } } }
0
Kotlin
0
0
0f7418ecc8675d8361ef31cbc1ee26ea51f7708a
2,187
leetcode
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/day14/DockingData.kt
Pkshields
318,658,287
false
null
package dev.paulshields.aoc.day14 import dev.paulshields.aoc.common.readFileAsStringList val valueSetCaptureRegex = Regex("mem\\[(\\d+)] = (\\d+)") fun main() { val program = readFileAsStringList("/day14/InitializationProgram.txt") var memory = runInitializationProgramThroughDecoderChipV1(program) println("The sum of all data in memory is ${memory.values.sum()}!") memory = runInitializationProgramThroughDecoderChipV2(program) println("The sum of all data in memory is ${memory.values.sum()}!") } fun runInitializationProgramThroughDecoderChipV1(program: List<String>): MutableMap<Long, Long> { val memory = mutableMapOf<Long, Long>() var bitmask = Bitmask.zero for (line in program) { if (lineIsBitmaskString(line)) { bitmask = Bitmask.fromString(line.drop(7)) } else { valueSetCaptureRegex .find(line) ?.groupValues ?.let { memory[it.component2().toLong()] = bitmask.mask(it.component3().toLong()) } } } return memory } fun runInitializationProgramThroughDecoderChipV2(program: List<String>): MutableMap<Long, Long> { val memory = mutableMapOf<Long, Long>() var bitmask = AddressBitmask.empty for (line in program) { if (lineIsBitmaskString(line)) { bitmask = AddressBitmask.fromString(line.drop(7)) } else { valueSetCaptureRegex .find(line) ?.groupValues ?.let { loc -> bitmask .mask(loc.component2().toLong()) .forEach { memory[it] = loc.component3().toLong() } } } } return memory } private fun lineIsBitmaskString(input: String) = input.startsWith("mask")
0
Kotlin
0
0
a7bd42ee17fed44766cfdeb04d41459becd95803
1,849
AdventOfCode2020
MIT License
aoc-2023/src/main/kotlin/aoc/util/ListStuff.kt
triathematician
576,590,518
false
{"Kotlin": 615974}
package aoc.util /** get second item in a collection. */ fun <E> Collection<E>.second(): E = drop(1).first() /** get all pairs of elements from a list. */ fun <E> List<E>.pairwise(): List<Set<E>> = flatMapIndexed { i, e -> drop(i + 1).map { setOf(e, it) } } /** get all triples of elements from a list. */ fun <E> List<E>.triples(): Sequence<Set<E>> = indices.asSequence().flatMap { i1 -> indices.drop(i1 + 1).flatMap { i2 -> indices.drop(i2 + 1).map { i3 -> setOf(get(i1), get(i2), get(i3)) } } } /** divide into [n] lists, giving one to each in order. */ fun <E> List<E>.splitInto(n: Int): List<List<E>> = (0 until n).map { i -> indices.filter { it % n == i }.map { get(it) } } /** get permutations of a list. */ fun <E> List<E>.permutations(): List<List<E>> = when (size) { 0 -> listOf(emptyList()) 1 -> listOf(this) else -> flatMap { e -> (this - e).permutations().map { listOf(e) + it } } } /** looks up content in a list of strings, mapping to first result object found. */ fun <X> List<String>.lookup(vararg lookup: Pair<String, X>) = lookup.firstOrNull { it.first in this }?.second ?: throw IllegalStateException("None of ${lookup.map { it.first } } found in $this")
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
1,244
advent-of-code
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day288/day288.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day288 // day288.kt // By <NAME>, 2020. // Make sure we have four digits by prepending. private fun Int.to4digits(): Int = (toString().toList() + List(4 - toString().length){"0"}).joinToString("").toInt() // At least two digits. Must treat as a string to avoid removing leading 0s. private fun Int.atLeastTwo(): Boolean = !(toString().toList() + List(4 - toString().length){"0"}).groupBy { it }.values.any{ it.size == 4 } // Size of digits must be between 0 and 4 inclusive, and not have triply repeated digits. fun Int.legal(): Boolean = toString().length <= 4 && atLeastTwo() // Sorts private fun Int.sortDecreasing(): Int = to4digits().toString().toList().sorted().joinToString("").toInt() private fun Int.sortIncreasing(): Int = to4digits().toString().toList().sorted().joinToString("").reversed().toInt() fun Int.checkKaprekar(): Int? { tailrec fun aux(value: Int = this, steps: Int = 0): Int? = when { !legal() -> null value == 6174 -> steps else -> { val higher = value.sortIncreasing() val lower = value.sortDecreasing() aux(higher - lower, steps + 1) } } return aux() } fun main() { for (i in 1 until 10000) { if (i.legal()) println("$i -> ${i.checkKaprekar()}") } }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,380
daily-coding-problem
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day06.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.PuzzleSet fun PuzzleSet.day6() = puzzle(day = 6) { // Part one val fish = input.split(",").groupingBy { it.trim().toInt() }.eachCount() .mapValues { it.value.toLong() } val cyclePopulation = { map: Map<Int, Long>, count: Int -> var result = map for (day in 1..count) { val newResult = mutableMapOf<Int, Long>() for ((i, cnt) in result) { if (i == 0) { newResult[6] = newResult.getOrDefault(6, 0) + cnt newResult[8] = newResult.getOrDefault(8, 0) + cnt } else { val newKey = i - 1 newResult[newKey] = newResult.getOrDefault(newKey, 0) + cnt } } result = newResult } result } val popPartOne = cyclePopulation(fish, 80) partOne = popPartOne.values.sum().s() // Part two partTwo = cyclePopulation(popPartOne, 256 - 80).values.sum().s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,055
advent-of-code
The Unlicense
src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0894_all_possible_full_binary_trees // #Medium #Dynamic_Programming #Tree #Binary_Tree #Recursion #Memoization // #2023_04_11_Time_257_ms_(100.00%)_Space_46.5_MB_(90.00%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun allPossibleFBT(n: Int): List<TreeNode> { if (n % 2 == 0) { // no complete binary tree possible return ArrayList() } val dp: Array<ArrayList<TreeNode>?> = arrayOfNulls(n + 1) // form left to right var i = 1 while (i <= n) { helper(i, dp) i += 2 } return dp[n]!! } // Using tabulation private fun helper(n: Int, dp: Array<ArrayList<TreeNode>?>) { if (n <= 0) { return } if (n == 1) { dp[1] = ArrayList() dp[1]!!.add(TreeNode(0)) return } dp[n] = ArrayList() var i = 1 while (i < n) { // left for (nodeL in dp[i]!!) { // right for (nodeR in dp[n - i - 1]!!) { // 1 node used here val root = TreeNode(0) root.left = nodeL root.right = nodeR dp[n]!!.add(root) } } i += 2 } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,575
LeetCode-in-Kotlin
MIT License
kotlin/1958-check-if-move-is-legal.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// recursive solution class Solution { fun checkMove(board: Array<CharArray>, rMove: Int, cMove: Int, color: Char): Boolean { board[rMove][cMove] = color val rowColumDirections = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(1, 1), intArrayOf(-1, -1), intArrayOf(1, -1), intArrayOf(-1, 1) ) fun isValidCell(row: Int, column: Int) = row in board.indices && column in board[row].indices && board[row][column] != EMPTY_CELL && board[row][column] != VISITED_CELL fun dfs( startRow: Int, startColumn: Int, rowDir: Int, columnDir: Int, cellsInCurrentPath: Int ): Boolean { if (board[startRow][startColumn] == color) { board[startRow][startColumn] = VISITED_CELL return cellsInCurrentPath >= 2 // there must be 2 other nodes, not including the current node } board[startRow][startColumn] = VISITED_CELL val newRow = startRow + rowDir val newColumn = startColumn + columnDir if (!isValidCell(newRow, newColumn)) return false return dfs(newRow, newColumn, rowDir, columnDir, cellsInCurrentPath + 1) } for ((rowDir, colDir) in rowColumDirections) { val newRow = rMove + rowDir val newColumn = cMove + colDir if (!isValidCell(newRow, newColumn)) continue if (dfs(newRow, newColumn, rowDir, colDir, 1)) return true } return false } companion object { private const val VISITED_CELL = '|' private const val EMPTY_CELL = '.' } } // Iterative Solution class Solution { fun checkMove(board: Array<CharArray>, rMove: Int, cMove: Int, color: Char): Boolean { val rowColumDirections = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(1, 1), intArrayOf(-1, -1), intArrayOf(1, -1), intArrayOf(-1, 1) ) fun isValidCell(row: Int, column: Int) = row in board.indices && column in board[row].indices && board[row][column] != EMPTY_CELL fun checkIfValidInDirection(rowDir: Int, colDir: Int): Boolean { var currentRow = rMove + rowDir var currentColumn = cMove + colDir var numberOfCellsInPath = 1 while (isValidCell(currentRow, currentColumn) && board[currentRow][currentColumn] != color) { numberOfCellsInPath++ currentRow += rowDir currentColumn += colDir } return isValidCell(currentRow, currentColumn) && numberOfCellsInPath >= 2 } for ((rowDir, colDir) in rowColumDirections) { if (checkIfValidInDirection(rowDir, colDir)) return true } return false } companion object { private const val EMPTY_CELL = '.' } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
3,220
leetcode
MIT License
src/day01/Day01.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day01 import readInput import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var calories = 0 input.forEach { calory -> if (calory.isEmpty()) { maxCalories = max(maxCalories, calories) calories = 0 } else { calories += calory.toInt() } } return maxCalories } fun part2(input: List<String>): Int { val caloriesList = mutableListOf<Int>() var calories = 0 input.forEach { calory -> if (calory.isEmpty()) { caloriesList.add(calories) calories = 0 } else { calories += calory.toInt() } } caloriesList.add(calories) return caloriesList.sorted().takeLast(3).sum() } val testInput = readInput("day01/Day01_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
1,000
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2017/2017-08.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2017 import kotlin.math.max fun main() { println("Part1+2:") println(solve(testInput1)) println(solve(input)) } private fun solve(input: String): Pair<Int, Int> { val registers = mutableMapOf<String, Int>() var max = 0 input.lines().forEach { val (register, dir, jump, other, comparison, value) = regex.matchEntire(it)!!.destructured if (comparison.compare(registers.getOrDefault(other, 0), value.toInt())) { val offset = if (dir == "inc") jump.toInt() else jump.toInt() * -1 val new = registers.getOrDefault(register, 0) + offset registers[register] = new max = max(max, new) } } return registers.maxOf { it.value } to max } private fun String.compare(a: Int, b: Int) = when (this) { ">" -> a > b "<" -> a < b ">=" -> a >= b "<=" -> a <= b "!=" -> a != b "==" -> a == b else -> error("bad comparison: $this") } private val regex = """(\w+) (inc|dec) (-?\d+) if (\w+) ([!=<>]+) (-?\d+)""".toRegex() private const val testInput1 = """b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10""" private const val input = """yxr inc 119 if nev != 6 piw dec -346 if tl != 4 cli inc 165 if nev >= -5 nev dec 283 if xuu > -2 tem inc 745 if qym >= -9 xuu dec -104 if cli == 165 h dec 192 if u <= 5 ln dec -616 if ej > -7 tem dec -555 if ar > -5 tem dec 687 if tl > -8 h inc 120 if re < -8 bq dec -410 if ej > -4 re dec 476 if tem == 613 ej dec 686 if cli != 163 ar dec 676 if tl > -6 nfo inc 633 if s == 0 tl inc -471 if tem > 607 bb inc 157 if piw > 342 cli inc -830 if piw != 342 piw inc -645 if ar >= -674 bq dec 304 if piw != 356 u inc -274 if bb != 147 yxr inc -520 if ec >= 1 ec dec 631 if bb > 147 ar dec 732 if s >= 0 foz inc -617 if bb == 157 qym dec -197 if ej == -686 bb dec 111 if h <= -199 ln dec -585 if re != -476 foz dec -181 if nev < -280 foz dec 989 if xuu != 106 ec inc -930 if ec <= -626 foz dec 862 if s >= 5 tem inc 241 if xuu == 104 ar dec -460 if h >= -201 cli inc -317 if cli == -665 bb dec -483 if h > -194 tem inc -718 if tl <= -466 ln dec 362 if hb == 0 qym inc 95 if hb > 3 piw dec -463 if ln < 246 xuu inc 159 if s <= 5 ec inc -710 if cli < -977 bb inc -98 if xuu >= 260 qym inc 159 if bb >= 540 acc inc 610 if fe <= 9 ar dec 381 if ej < -695 acc dec 807 if nev > -284 foz dec 926 if h < -188 tl inc 279 if ar != -957 ec dec -39 if acc < -191 u dec -110 if piw == 346 ej dec 980 if ar == -948 ln dec -165 if hb < 2 nfo inc -370 if tem > 128 ar dec -886 if ar < -947 bb dec 624 if ej == -1666 tl inc 36 if ec > -2227 yxr dec 320 if cli <= -976 tem inc -808 if ar >= -52 cli dec 213 if h >= -198 ej inc -141 if nev < -281 bq inc -736 if yxr > -211 u dec -742 if nfo > 258 bq dec -727 if ar >= -64 u dec -248 if bq > 89 xuu inc 431 if yxr > -203 hb dec -407 if hb >= -7 ar inc 789 if acc >= -197 yxr inc -753 if piw <= 350 piw dec -973 if yxr >= -956 xuu dec 457 if ec <= -2228 bq inc -201 if bq >= 97 bq dec -923 if ar == 727 cli inc -560 if piw < 1329 ej dec -150 if ar != 733 h inc -198 if nev == -283 u inc -388 if piw == 1319 hb inc -212 if s < 8 xuu inc -988 if ej < -1653 ec inc 58 if re >= -485 hb inc -126 if xuu < -741 ar inc 534 if nev == -273 fe inc 668 if s <= 7 tem dec 25 if h >= -390 u inc -632 if tl > -198 u dec 721 if bq > 813 piw dec -299 if foz >= -2348 hb inc -407 if ej > -1663 h dec 563 if foz == -2351 bb dec 362 if fe != 670 nev inc -512 if bb != -437 fe dec -419 if yxr < -948 tl dec 576 if ej > -1665 acc dec -510 if xuu > -759 s dec -108 if u < -906 xuu dec -407 if xuu < -748 yxr dec 771 if bb > -454 u dec -879 if tem != 110 bq inc -759 if u < -27 s dec -295 if qym < 364 qym inc 807 if xuu == -344 h inc 545 if hb == -338 ej inc -896 if s != 394 s dec -961 if yxr > -1723 s dec -142 if nev != -799 s inc -692 if ln != 427 ar dec 152 if tl == -763 acc dec 304 if piw != 1328 ar inc -532 if piw != 1324 bq inc 124 if tem < 109 h inc 480 if nfo == 268 xuu dec -291 if ej >= -2556 hb inc -56 if nfo >= 257 ar dec -656 if bb > -447 tl dec -458 if ec <= -2167 xuu inc -100 if hb <= -397 nev dec 384 if foz <= -2344 acc dec -779 if acc == 9 u inc 949 if h != -416 xuu inc -865 if nev < -1182 nev dec 317 if bb < -434 foz inc -786 if bq > 51 xuu inc -901 if ej >= -2557 nev dec 750 if h != -398 qym dec 783 if re != -480 bb dec 54 if cli < -1752 tl dec -803 if yxr < -1724 s inc 690 if xuu != -954 piw inc -667 if s != -151 foz dec -946 if cli <= -1757 h dec -885 if re == -486 ar inc -765 if re < -468 h dec 340 if ec != -2170 fe dec 440 if tl > 492 re dec 398 if hb != -384 xuu inc -49 if fe > 641 s dec 623 if qym != 375 piw inc 429 if ec == -2174 ej inc 747 if hb != -394 xuu inc 761 if nfo > 255 re inc 519 if yxr != -1716 nev inc 863 if tl <= 499 qym inc -357 if foz > -3138 tl dec 186 if u < 915 s dec -442 if nev < -1373 bq inc -999 if ec == -2174 cli inc 735 if acc > 781 ar dec -983 if nev >= -1389 cli inc 285 if u < 917 xuu inc -970 if h >= -747 bq inc 716 if tl < 310 xuu dec 984 if bb > -503 h inc -881 if ej >= -2546 u inc 719 if fe >= 646 u inc 396 if hb > -393 ej inc 734 if acc != 784 fe inc 581 if re <= -350 piw dec -69 if hb < -384 ec dec 540 if acc < 798 cli dec -615 if foz <= -3130 ln inc 261 if foz <= -3130 acc dec 739 if ar > 1065 ln dec -520 if qym > 19 re inc -260 if bq != -230 ln inc -28 if h > -750 hb dec -794 if s == -325 nfo inc 79 if ln < 1176 acc inc 173 if ec == -2714 yxr inc 756 if re > -616 re inc 415 if fe >= 1219 hb dec -701 if u < 1638 xuu dec -325 if re != -200 ln dec -552 if piw != 1157 yxr inc -568 if qym >= 17 tl dec 756 if ec <= -2712 nev dec 430 if xuu <= -1219 bq dec -580 if yxr >= -1533 ej dec -357 if bb >= -493 ec inc 722 if ej >= -1822 tl dec 168 if nev == -1813 bb dec -393 if foz >= -3130 cli inc -298 if s == -328 h inc 885 if yxr != -1536 nev dec -188 if cli < -427 yxr dec 41 if cli > -416 qym inc 748 if u == 1632 re inc 457 if nfo > 339 yxr inc 781 if piw < 1153 qym inc 628 if cli != -417 bq inc -476 if piw < 1142 bb dec 547 if nfo >= 341 s dec 590 if piw == 1150 piw inc -804 if nfo != 342 ar dec -838 if xuu == -1226 ec inc 224 if h > 132 ec dec -963 if ln >= 1731 xuu inc 109 if u <= 1638 s dec -191 if fe >= 1220 ln dec -718 if h >= 133 u dec 46 if nev >= -1811 nfo inc -56 if s < -718 nev dec -346 if ar != 1905 h dec -501 if hb != 306 acc dec 651 if bb >= -1039 xuu dec 714 if ar > 1905 qym dec 304 if piw <= 1157 tl dec -62 if foz < -3138 h inc 448 if qym != 1095 hb inc 780 if tem != 112 hb dec 332 if tem <= 114 s dec -447 if acc != 226 s dec -560 if ej > -1829 nev dec -435 if piw == 1150 nev dec 259 if piw < 1155 tem inc 293 if nfo == 286 hb dec 656 if s < 284 hb inc -484 if acc < 213 ln inc 831 if s < 280 hb dec -394 if ec != -1771 nfo inc 124 if h != 628 ln dec -675 if yxr < -754 bb dec -69 if hb == 494 ln inc -139 if re <= 261 nev inc 325 if yxr >= -753 tl inc 551 if foz != -3137 bb dec -598 if nfo != 413 qym inc 771 if s >= 271 tl inc 903 if ej != -1820 fe inc -388 if re != 250 ln dec -163 if ej != -1827 nev dec -209 if re <= 261 bq inc -59 if h == 638 ej inc 793 if yxr < -749 ec inc -224 if s >= 276 ln inc 895 if foz <= -3132 acc dec -681 if ec < -1989 tem dec -161 if hb == 493 ar dec -436 if nfo >= 408 u dec -56 if re != 250 nfo inc -497 if hb < 495 ec dec -874 if acc > 911 bb dec 988 if xuu == -1838 nfo dec -257 if fe > 836 ec inc -332 if foz >= -3146 u inc 697 if u <= 1691 ej dec 777 if bb <= -440 nfo dec -99 if bq > -277 acc dec 552 if tem <= 573 fe dec 74 if ec == -2317 qym dec 829 if foz >= -3146 bq dec -149 if ec <= -2324 u dec -99 if hb == 493 yxr dec -546 if tl > 288 u inc 261 if cli >= -412 ej inc -341 if tem < 574 ec inc -83 if ar <= 2346 ec inc 847 if xuu <= -1830 re dec -364 if xuu < -1839 yxr inc -483 if ln <= 4033 tl dec 965 if tl == 286 re inc -63 if tl >= -674 cli inc 708 if acc < 352 xuu dec 494 if ej > -2154 tl inc 8 if foz > -3131 ec inc 983 if nfo == 170 bb inc 486 if cli < 292 ar dec -461 if ec >= -586 yxr dec -852 if hb < 500 u inc -874 if acc < 355 xuu inc 883 if re > 266 xuu dec 809 if ec == -577 tl dec 144 if ej > -2145 u inc -363 if fe >= 839 bb inc -194 if piw >= 1150 ln inc 780 if fe != 835 cli inc 213 if re >= 256 xuu dec -718 if hb >= 491 yxr dec -730 if u < 1251 nfo dec 1 if hb > 491 ar inc -556 if nev > -1085 ej dec -275 if bq < -128 nev dec -578 if foz != -3137 h inc -391 if h == 638 foz inc -291 if bq >= -134 bb inc -123 if fe == 840 tl dec 72 if bq == -133 qym dec -155 if yxr < 831 re inc 515 if s < 289 nfo dec -313 if ar >= 2242 cli dec 486 if tl < -904 bb dec -844 if ln >= 4810 hb inc -551 if tem == 565 ec inc -28 if yxr <= 828 cli inc -673 if h >= 241 re dec -937 if bb > 562 ec inc 214 if bb != 571 piw inc -142 if ar > 2240 ar dec 750 if tl < -898 re dec -844 if ej != -1877 bq inc -17 if qym <= 1200 acc dec -154 if foz > -3429 piw inc -13 if cli > -175 cli inc -374 if acc > 497 acc dec -751 if ln != 4821 xuu dec 821 if bq < -142 nev dec 867 if bb < 565 qym dec -883 if hb != -65 h inc -289 if ln <= 4818 hb dec 839 if s <= 282 cli dec 662 if ar > 2253 nev inc 975 if acc < 1249 foz inc -459 if nfo != 479 tem inc 721 if ar < 2244 hb dec 645 if bb >= 561 cli dec 973 if bq <= -148 qym inc 937 if piw <= 1003 bq inc -548 if tem != 561 nfo dec 98 if nev != -1082 u dec 789 if bq >= -688 u dec 389 if acc <= 1258 bq inc 818 if qym <= 3020 acc inc 224 if nfo < 492 ln inc -739 if re >= 2547 re dec -364 if fe != 843 piw dec -836 if piw > 991 foz inc 484 if cli < -1519 ln inc 869 if hb < -1533 piw dec 872 if yxr <= 834 bq inc -1 if bq >= 113 tl inc -649 if u >= 854 ec dec -447 if bb == 566 ar dec -702 if u < 861 s inc -445 if bb <= 574 xuu dec 323 if cli <= -1523 foz dec 589 if ln <= 4947 s inc -399 if nfo != 484 cli inc -704 if acc < 1481 yxr dec 712 if hb != -1534 nev dec -347 if nev <= -1087 ln dec -801 if foz > -4480 xuu dec -549 if h >= -47 re dec 127 if xuu > -2692 hb inc 96 if fe <= 845 acc dec 159 if hb >= -1451 bq inc 754 if u >= 865 u inc 23 if yxr > 106 re dec 940 if nfo <= 489 qym dec -599 if ar >= 2948 qym dec -481 if nfo == 482 nfo inc 767 if cli <= -2225 bb inc -174 if ec == 56 tem inc 615 if ec <= 55 tem inc 845 if re > 1848 hb inc 940 if tl > -1543 bq dec -892 if xuu >= -2686 bq inc 996 if bq >= 117 re dec 456 if u < 885 ln inc 879 if s < -568 s dec 605 if ar >= 2941 foz dec 585 if hb > -1449 ej inc 980 if ej <= -1866 re dec -409 if foz <= -5059 tem dec -394 if nfo != 476 yxr dec -765 if ej <= -888 ec inc -540 if fe < 843 cli dec 758 if foz != -5056 nfo inc 846 if re > 1802 re inc 800 if nev < -1078 nev dec 2 if yxr < 883 piw inc 282 if acc >= 1313 h inc -993 if ln <= 5741 ar inc 594 if tem <= 1804 h inc 502 if h >= -45 xuu inc -73 if acc <= 1326 re dec 116 if piw >= 1243 bq inc 62 if u <= 880 acc dec 166 if fe <= 846 ec dec -441 if re > 2612 re inc 214 if re != 2602 u dec 410 if s < -1160 ln dec -701 if piw <= 1244 tl inc -126 if nfo <= 1330 fe inc -861 if tl <= -1669 ar dec -998 if yxr <= 882 fe inc 629 if ln > 6445 hb dec -407 if foz <= -5071 s dec 654 if acc <= 1161 bb inc 304 if fe <= 615 xuu inc 979 if cli == -2969 cli inc -973 if fe == 607 cli inc 859 if tl <= -1665 tl dec 257 if foz > -5064 bq dec -253 if hb != -1446 s inc 82 if fe == 611 h inc -462 if xuu == -2761 nev dec 231 if bq <= 1123 fe inc -719 if re == 2817 nfo inc 553 if ec != -484 nev inc -457 if nfo != 1318 fe inc -936 if piw <= 1247 nev inc -615 if ar > 4539 fe inc -267 if ec >= -475 qym dec 336 if tem > 1802 ej inc 442 if foz > -5064 qym inc 864 if h < 0 nev inc 565 if foz >= -5057 tem inc 257 if ej <= -457 hb dec -202 if piw > 1243 bq dec -192 if ar != 4550 foz dec 374 if ln >= 6454 tem inc 381 if ej != -454 ec dec -630 if ej == -438 foz dec -821 if acc > 1161 nev dec 903 if bq != 1315 re inc -677 if ej > -448 re inc 588 if u < 473 xuu dec 114 if foz > -5062 acc inc -804 if ec > -492 nfo inc 728 if cli == -2120 xuu dec -258 if foz > -5064 tem dec -370 if ln < 6450 acc dec -717 if ej != -442 ec dec 262 if qym > 4613 nev inc 31 if u >= 468 xuu dec 84 if re == 2728 u inc 457 if xuu != -2697 acc dec 251 if acc != 1068 tem dec -745 if acc <= 1076 tl dec 581 if tem <= 3304 s dec -730 if hb <= -1444 ec dec 409 if tem < 3293 acc dec -884 if acc >= 1077 acc inc 160 if bb < 706 ar dec 110 if nfo != 2058 ej dec -349 if fe < -1038 s inc 681 if s >= -1096 cli inc -712 if fe < -1043 nfo dec 693 if u != 924 ln inc 170 if xuu != -2702 bb inc 759 if tl > -2518 ln inc 647 if tem > 3296 ej inc -35 if re >= 2734 qym inc 710 if nev < -3258 xuu inc 304 if fe == -1052 piw dec 237 if xuu >= -2707 tem dec -683 if hb <= -1441 piw inc -297 if re >= 2733 nfo dec -836 if bb == 1455 s inc 901 if u <= 921 bb inc 780 if bq == 1307 xuu dec 467 if yxr >= 878 acc dec -24 if h < 6 ec dec 412 if foz >= -5054 ec inc -990 if fe == -1047 nev dec -940 if nfo != 2208 ar dec -670 if qym == 5339 foz inc 391 if hb != -1438 yxr inc -86 if acc <= 1260 qym dec -36 if piw < 1008 nev inc -21 if yxr == 788 piw inc 581 if hb == -1446 bb inc -355 if bb != 2232 yxr dec 238 if ar < 4441 tem dec -974 if cli < -2826 xuu inc -237 if s <= -406 ej dec 51 if foz <= -4661 cli inc -416 if h < 6 fe inc 23 if s < -407 bq dec 598 if ej <= -152 cli inc -15 if piw > 1584 foz dec -781 if nfo < 2209 u inc 17 if bb < 1883 xuu dec 799 if ej >= -157 bb inc 914 if tem != 4960 foz dec 853 if fe != -1024 piw dec 628 if nfo != 2199 qym dec 303 if xuu >= -4207 bq dec 854 if yxr >= 549 hb inc -123 if xuu >= -4211 bb inc 767 if nev <= -2318 s inc 482 if nfo > 2196 yxr inc 185 if bb < 3570 yxr dec 683 if bq != 444 fe dec -316 if ec >= -1733 bb inc 368 if s < 78 tl dec 132 if yxr != 63 yxr dec 357 if bq == 453 fe inc -256 if ec > -1744 xuu inc -193 if ej <= -142 xuu dec -605 if cli != -3263 ar dec 571 if u != 945 nfo inc -430 if nfo < 2209 hb inc 236 if hb > -1564 ar dec -460 if fe < -1278 tl dec -127 if bq > 449 s inc -343 if nfo > 1764 fe inc 761 if nev < -2326 piw dec -136 if xuu != -4391 cli dec 639 if yxr >= -301 tl dec -524 if ar != 4890 ln dec -75 if ln < 7269 ln dec -376 if tem > 4956 yxr inc -317 if yxr >= -297 tem inc 593 if ej == -149 cli dec 297 if ar < 4894 ej dec -576 if xuu <= -4395 bq dec -681 if s >= -277 ec dec -404 if u >= 939 xuu dec -82 if yxr >= -292 nev inc -661 if u <= 954 yxr inc 941 if foz > -3896 ar dec 559 if ar < 4895 re inc 470 if tl <= -1981 qym inc 423 if hb <= -1564 ec inc -353 if cli >= -4208 qym inc 166 if nfo < 1770 ln inc 110 if h > -4 bb dec 459 if nfo < 1776 tem inc -466 if ej > 418 tem inc -223 if fe < -1271 bb inc 361 if qym > 5650 fe dec 698 if nfo <= 1768 h inc -761 if acc >= 1258 tl dec 307 if cli < -4195 ec dec -428 if bq == 1134 ec inc 200 if u == 945 fe dec 999 if re >= 3198 ej dec -150 if ej != 429 ar inc -19 if bb < 3822 cli inc -271 if piw == 1721 piw inc -317 if nev <= -2985 xuu dec 732 if xuu == -4393 ar dec -738 if bq != 1133 cli dec -925 if xuu >= -4400 tem dec -336 if acc == 1261 xuu dec -396 if tl < -2291 tem inc -726 if xuu < -3995 xuu inc 586 if yxr < 643 nfo inc 554 if re >= 3194 ln dec 425 if s < -276 s inc -678 if h >= -2 acc inc -669 if u == 945 nfo inc 136 if re <= 3207 nev inc -486 if fe > -2272 acc inc 146 if yxr < 650 bq inc 637 if u != 945 bq inc -562 if u < 949 fe dec -164 if tem >= 4128 ej inc -868 if ec > -1058 foz inc -646 if ej < -295 u inc 960 if bb < 3825 ln dec -6 if ln > 7826 bq dec 972 if acc > 723 piw inc 958 if fe != -2115 ln inc 179 if ln <= 7830 foz inc 206 if bb <= 3828 u inc -789 if bb > 3826 nev inc -597 if ln <= 8005 nev dec -112 if yxr <= 642 ej inc 670 if s <= -942 ec dec 623 if qym >= 5652 bb inc 35 if nev != -3470 u dec -50 if ej != 379 ar dec 952 if tl != -2306 tem inc -92 if re == 3192 yxr dec 866 if qym == 5652 nfo inc -457 if bb != 3876 tem inc 395 if fe != -2125 acc inc -37 if piw > 1711 tem dec -647 if fe <= -2113 tem dec -546 if xuu > -3422 piw dec 219 if acc < 699 ar dec -392 if piw == 1502 s inc 330 if bq > -407 bq inc -508 if nev <= -3473 ln dec -333 if cli != -3545 ln dec 42 if ec > -1683 acc inc -247 if ln <= 7966 foz inc 563 if tl <= -2287 ej inc -390 if ej <= 384 acc dec 659 if acc != 443 xuu dec -293 if ej >= -18 qym dec -169 if yxr > -217 cli inc 778 if ln >= 7960 xuu dec -179 if u != 163 nfo dec 600 if ej == -11 ar dec 261 if piw > 1492 re inc -889 if yxr > -228 h inc 37 if xuu != -2943 ln inc 148 if tem > 5731 bq dec 564 if piw == 1502 piw dec 822 if ar != 4242 xuu inc -35 if nfo != 1402 u dec -284 if cli > -2777 ar dec -521 if yxr >= -225 bb dec 412 if yxr <= -222 piw inc -199 if tem != 5715 bb inc 331 if qym < 5653 bq dec -359 if ec > -1687 acc inc 298 if bq == -605 bq inc -69 if tl < -2305 h inc -626 if h == 8 qym dec 609 if s <= -619 fe inc 165 if nev < -3456 xuu inc 690 if ej != -15 ec dec -280 if tl < -2294 qym dec 829 if bq != -610 xuu dec 888 if piw > 489 u inc 81 if acc > 80 qym dec 247 if h > -9 tl dec -558 if bq < -604 nfo dec 692 if ln == 7963 acc inc -23 if tl > -1735 xuu dec 478 if fe == -1950 s dec 551 if tl < -1736 ec inc -479 if fe == -1950 s dec -17 if foz > -3328 piw dec 351 if acc == 84 bq dec -437 if re == 2309 qym dec -808 if cli > -2774 h dec -390 if tl == -1738 foz dec 676 if ej >= -4 re dec 891 if bq != -167 bb dec -191 if re != 1418 nfo inc 380 if s == -1155 ec inc 69 if u < 531 nev dec -690 if s >= -1164 s dec 571 if bb >= 3776 re dec -224 if hb <= -1563 bq inc -252 if piw < 131 yxr dec -488 if tl == -1741 re inc 755 if re > 1638 bq inc -208 if qym != 4769 qym inc 695 if hb == -1563 fe inc -157 if piw < 121 xuu dec 579 if acc != 79 ln dec -262 if nfo > 1086 ec dec 235 if tl >= -1739 hb inc 188 if ej >= -13 s inc 124 if cli >= -2760 ec dec -643 if nfo != 1088 re dec -934 if fe > -1959 ej inc -58 if s == -1727 qym dec -558 if tl >= -1746 ln inc -555 if ec != -1402 foz inc -833 if cli != -2774 ln dec -589 if cli == -2775 tl inc -906 if re < 3334 tl inc 552 if fe < -1940 cli inc 976 if re >= 3322 bq inc -101 if xuu >= -3301 nev dec -217 if tl < -2087 ej dec 945 if u > 519 piw inc 447 if fe >= -1957 h inc 905 if piw <= 586 hb inc -995 if u == 521 acc inc 713 if tl >= -2100 ar inc -936 if ec <= -1400 tl inc 199 if u < 530 u dec 584 if ar != 3829 tl inc 787 if fe > -1954 ar inc 631 if qym >= 5325 tl inc -993 if ln < 8232 bq dec 900 if yxr > -231 u dec -226 if ln < 8235 yxr inc -966 if bq <= -1520 ar inc -83 if bq < -1520 bq dec 439 if bq == -1528 ej inc 608 if h < 1294 yxr inc 140 if nev >= -2567 qym dec 685 if nev >= -2566 re dec 957 if hb > -2378 tem dec -851 if bq <= -1966 nfo dec 421 if qym < 4649 acc inc 473 if ar == 4383 tem inc -407 if qym >= 4642 s dec -949 if tl >= -2103 h inc 549 if s >= -784 qym dec -311 if xuu >= -3308 s dec 751 if yxr > -1060 s inc -438 if ar != 4386 fe dec 734 if s <= -1965 ej inc 989 if hb == -2376 tl dec 84 if yxr > -1055 re dec 919 if ar < 4393 ec dec 314 if qym >= 4657 acc dec 572 if piw <= 579 bq dec -742 if tem >= 6166 ln inc 891 if qym < 4651 piw inc 125 if s >= -1956 nev inc 530 if piw != 577 ln inc 703 if nfo <= 670 bb inc 741 if foz >= -4155 ln inc -429 if u >= 163 ln dec -47 if nfo > 678 cli dec 217 if bq < -1222 tl dec -485 if fe >= -2690 tl dec -948 if fe == -2684 nfo inc 786 if qym != 4642 bb inc 336 if re != 1455 tl inc -8 if nfo != 1455 hb inc 173 if bq == -1225 s dec -53 if piw < 581 bq inc 905 if h == 1842 acc inc -450 if nev < -2551 ar dec 241 if s != -1914 bb inc 671 if ec <= -1400 acc inc 895 if fe <= -2691 fe dec 776 if s == -1913 foz inc -104 if nev >= -2558 nfo dec 629 if hb <= -2201 u dec 531 if ec < -1404 hb dec -37 if yxr < -1049 foz dec -586 if h <= 1848 nev inc -895 if acc == 248 qym dec 475 if bb <= 4461 piw inc 773 if fe < -3459 nfo dec -142 if cli == -2008 hb inc 103 if cli != -1999 bq inc 795 if ln == 9390 re dec 82 if nfo <= 975 u inc -275 if u != 163 xuu inc -599 if acc == 248 ln inc -642 if hb < -2069 hb dec 874 if nfo == 968 bb inc -283 if ej != 640 bq inc -999 if fe == -3460 tem dec 670 if tem != 6174 bb inc 890 if re > 1369 xuu dec 880 if foz >= -3678 ar dec -702 if ej == 641 h inc -43 if nev != -3453 tl inc -803 if qym >= 4166 ej inc 583 if foz > -3687 piw inc -517 if qym != 4173 nev dec -258 if tl >= -1552 tem inc -18 if ln >= 9398 qym inc -463 if tem == 5497 nfo inc -279 if ln >= 9392 nfo dec 627 if ln > 9388 acc inc -544 if ej >= 1219 xuu dec 201 if foz < -3667 qym inc -353 if s >= -1905 xuu inc -927 if tem <= 5506 cli dec -347 if bb != 5065 tl dec -339 if hb == -2937 s dec 503 if fe > -3470 s dec -187 if acc > -306 hb inc 77 if ej > 1214 u dec 103 if acc > -296 s dec 620 if bb < 5072 fe dec -752 if bb == 5063 u dec 930 if ec == -1410 ec inc -235 if cli != -1661 bq inc -361 if cli < -1664 xuu inc -582 if s <= -2849 re dec 812 if acc <= -292 h inc -938 if cli != -1652 ec inc -830 if re > 560 ec dec -888 if ln < 9385 cli inc -520 if tem < 5506 qym inc -224 if acc >= -302 tl inc -399 if nfo >= 342 tem dec 154 if foz == -3671 qym inc 500 if nev < -3443 tem dec 603 if acc != -295 nev inc 227 if ar == 4844 fe dec 658 if s > -2857 bb dec 327 if xuu < -6498 s inc -204 if acc <= -294 s inc 393 if s <= -3051 foz dec -71 if ec == -2232 piw inc 247 if acc != -306 tl dec 749 if cli >= -2189 bb dec -17 if qym != 3996 acc inc 890 if bq != -524 ar dec -532 if re == 561 ej dec -406 if ej >= 1224 ar dec -82 if hb < -2857 ej inc -685 if u <= 163 nfo dec -354 if yxr < -1053 ar dec -346 if yxr >= -1048 ej dec -575 if hb > -2864 bq inc 220 if bq != -521 fe dec -843 if cli <= -2185 ej inc -819 if ln > 9390 cli inc 105 if acc != -290 bb inc -828 if hb > -2866 s dec -508 if tem != 4900 re inc 153 if re <= 566 piw dec 370 if foz <= -3602 nfo inc 987 if bb >= 3922 fe inc -10 if foz > -3607 nfo inc -687 if yxr > -1060 nfo inc -580 if nev == -3226 fe inc -661 if s <= -2149 tl inc -521 if h == 896 nev dec 891 if tem > 4891 hb inc -162 if cli != -2076 yxr dec 696 if nev == -4112 tl inc 754 if s <= -2145 bq inc -457 if re >= 706 re dec -926 if acc >= -286 u inc 630 if re <= 719 ej dec -635 if u > 791 ln dec 631 if ln != 9400 qym inc 470 if re >= 722 ej dec 419 if cli == -2076 foz dec -108 if tl < -1201 fe inc -162 if cli <= -2078 ar dec 385 if yxr == -1059 ec inc 695 if hb < -2852 re dec 535 if cli > -2071 ej dec 135 if bb < 3926 ej dec 13 if hb != -2860 ec inc 967 if ec < -1540 ar dec 713 if ar >= 5453 piw inc -38 if tem >= 4887 piw inc 664 if bq == -761 ar dec 767 if hb > -2863 ej dec 908 if re > 715 nev inc 905 if acc <= -291 nev inc 395 if hb < -2854 piw inc 850 if yxr > -1050 tl dec 290 if nfo == 61 re inc -770 if xuu < -6496 fe inc 828 if ar == 3978 fe dec -295 if ar != 3980 fe dec 431 if foz >= -3506 nfo inc -433 if piw == 1853 tl dec -744 if acc > -299 s dec -609 if bb <= 3919 ar inc 390 if ec != -1547 acc inc 404 if hb == -2860 nfo inc -17 if s < -2152 u inc 338 if h != 910 s inc 921 if s >= -2159 ec inc -49 if hb > -2863 tem inc -144 if tem >= 4893 nev dec -847 if qym > 3985 yxr dec -885 if ln < 8762 cli dec 10 if u == 1131 tem dec -592 if yxr != -159 ec dec -594 if re >= -57 tem inc 66 if u == 1131 foz inc -810 if u == 1131 tem dec 880 if u > 1126 bq inc -604 if acc == 108 tem inc 344 if acc < 114 foz dec -550 if ej != 1594 ar inc 849 if s != -1233 nfo dec -903 if u == 1123 nev dec -945 if ec <= -987 re dec 715 if nev < -1019 ar dec -879 if hb == -2860 tl inc 432 if bb != 3926 s dec 474 if re <= -767 ej inc 356 if h >= 896 ec dec -229 if hb != -2863 bq inc 121 if ec <= -756 xuu inc 428 if u == 1131 ej inc 796 if xuu >= -6070 fe inc 889 if fe < -3341 cli dec 524 if acc > 102 piw dec -360 if acc != 117 fe dec 907 if h >= 907 piw dec -184 if ar != 6092 u dec 189 if hb >= -2866 nev dec -381 if nfo < -362 hb inc -568 if re == -771 hb inc -365 if xuu != -6079 nev dec 490 if qym == 3995 u dec 311 if u >= 933 hb inc 692 if yxr == -166 ej dec -524 if re > -767 ln dec 5 if h > 896 u dec 801 if u >= 628 ar dec -861 if s < -1695 nfo inc -921 if tem > 4862 ej inc -57 if bq == -1244 re dec 726 if ar == 6957 yxr dec -344 if s == -1705 ln dec -300 if foz != -3764 bb dec -372 if bq >= -1251 h inc 630 if tl <= -321 ln inc -586 if u != -161 ec dec -356 if ar != 6959 u dec -225 if piw >= 2399 ln inc -715 if tl < -321 nev inc -649 if u < -164 h inc 232 if ec != -407 bq dec 689 if piw <= 2399 bb inc 52 if xuu == -6071 foz inc 8 if s == -1705 fe inc 80 if nfo > -1299 ec inc 686 if u <= -166 foz inc 579 if bb < 4347 piw dec -551 if nev <= -1288 fe dec -271 if foz < -3743 nev dec -386 if qym <= 3993 nfo inc 791 if hb == -3101 xuu inc -206 if xuu != -6081 qym inc 53 if h > 1532 hb inc -238 if piw != 2955 h inc 947 if yxr < 181 re inc 668 if h < 2484 cli dec -989 if foz > -3754 tl inc -495 if h <= 2486 tl dec 884 if tl < -810 s inc 405 if fe >= -2107 ec dec 842 if yxr >= 174 h inc -451 if yxr < 180 yxr inc 364 if hb < -3331 nfo dec -736 if xuu < -6272 ec inc 37 if piw <= 2957 cli inc 839 if piw <= 2955 foz dec 787 if cli <= -777 ar inc 343 if hb == -3339 piw dec 939 if ej != 1892 piw inc -36 if bq != -1927 ej dec -684 if tl != -1710 acc inc 882 if h == 2030 re dec 372 if acc == 990 h inc 23 if qym <= 4041 ej dec 446 if u >= -169 foz dec 293 if yxr <= 539 tl dec -526 if fe > -2110 ar inc 35 if ec <= -521 ej dec -839 if s != -1295 bq inc -816 if ec > -534 tl dec -913 if fe >= -2108 bb dec 888 if acc >= 983 tem inc -951 if hb == -3339 ec dec -562 if qym < 4046 nfo dec -696 if h >= 2049 u dec -376 if yxr == 542 tem dec 130 if ej <= 3429 nev inc -484 if h >= 2046 nev dec -902 if yxr >= 539 qym inc 306 if nev >= -498 bq inc -306 if hb <= -3334 tl dec -807 if fe > -2113 nev inc -47 if nev <= -483 u dec -228 if xuu == -6277 hb dec 925 if s < -1297 acc dec 236 if cli > -786 h inc 684 if u >= 429 nfo dec 912 if u < 440 xuu inc 529 if bb < 3464 tl inc 143 if qym != 4354 ec dec 694 if tem == 3791 fe dec -542 if u < 441 piw dec 433 if yxr >= 540 ln dec -537 if hb > -4272 acc dec 419 if acc > 744 xuu dec 31 if fe == -1557 ej dec -297 if yxr < 533 foz inc -281 if ec <= -656 cli dec 712 if tl > 677 bq dec -871 if foz >= -4817 bb inc 381 if ln < 8294 nev inc -670 if tem > 3783 yxr inc 860 if nfo < 14 foz inc -120 if nfo > 25 ec inc 793 if fe >= -1563 qym dec -827 if qym < 4351 ar inc 687 if cli >= -1495 bq inc 975 if re < -1191 xuu inc 177 if u != 442 tem inc 363 if nev != -1207 acc inc 707 if cli < -1491 nfo dec -381 if tem > 4148 ec inc -347 if tl != 697 ej dec 995 if s > -1303 acc dec 452 if bq == -2080 u dec -851 if piw > 1539 ln inc -993 if re != -1211 nfo dec -591 if tl >= 692 s dec -410 if yxr != 549 yxr dec -54 if u >= 1288 bb dec -733 if re <= -1193 piw inc -984 if re < -1193 ln dec 133 if ec >= -211 acc dec -218 if fe < -1561 tem inc 792 if fe > -1567 bb dec 359 if yxr != 541 tem inc 273 if h != 2735 ec inc -714 if nfo < 401 hb dec -555 if bb <= 4206 nfo inc -151 if ln > 7294 hb dec -635 if yxr <= 550 acc inc -603 if u < 1282 nev inc 705 if cli >= -1488 cli inc 568 if ej < 2435 nfo dec 795 if nfo >= 246 s dec -996 if ln != 7289 u inc -530 if nfo > -550 tl dec -431 if qym >= 5171 fe inc -998 if ec < -920"""
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
26,809
advent-of-code
MIT License
30 Days of Code (Kotlin)/day20-sorting.kt
swapnanildutta
259,629,657
false
null
/* Question Today, we're discussing a simple sorting algorithm called Bubble Sort. Check out the Tutorial tab for learning materials and an instructional video! Consider the following version of Bubble Sort: for (int i = 0; i < n; i++) { // Track number of elements swapped during a single array traversal int numberOfSwaps = 0; for (int j = 0; j < n - 1; j++) { // Swap adjacent elements if they are in decreasing order if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); numberOfSwaps++; } } // If no elements were swapped during a traversal, array is sorted if (numberOfSwaps == 0) { break; } } Task Given an array, , of size distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following lines: Array is sorted in numSwaps swaps. where is the number of swaps that took place. First Element: firstElement where is the first element in the sorted array. Last Element: lastElement where is the last element in the sorted array. Hint: To complete this challenge, you will need to add a variable that keeps a running tally of all swaps that occur during execution. Input Format The first line contains an integer, , denoting the number of elements in array . The second line contains space-separated integers describing the respective values of . Constraints , where . Output Format Print the following three lines of output: Array is sorted in numSwaps swaps. where is the number of swaps that took place. First Element: firstElement where is the first element in the sorted array. Last Element: lastElement where is the last element in the sorted array. Sample Input 0 3 1 2 3 Sample Output 0 Array is sorted in 0 swaps. First Element: 1 Last Element: 3 Explanation 0 The array is already sorted, so swaps take place and we print the necessary lines of output shown above. Sample Input 1 3 3 2 1 Sample Output 1 Array is sorted in 3 swaps. First Element: 1 Last Element: 3 Explanation 1 The array is not sorted, so we perform the following swaps: At this point the array is sorted and we print the necessary lines of output shown above. */ fun main(args: Array<String>) { val n:Int=readInt(); var inputArray=readInts().toTypedArray(); var ans=0; for(i in 0..n-1){ for(j in 0..n-2){ if(inputArray[j]>inputArray[j+1]){ inputArray[j]=inputArray[j+1].also( { inputArray[j+1]=inputArray[j]}); //swap ans++; } } if(ans==0) break; } println("Array is sorted in $ans swaps."); println("First Element: ${inputArray[0]}\nLast Element: ${inputArray[n-1]}"); } private fun readLn() = readLine()!! ; private fun readInt() = readLn().toInt(); private fun readStrings() = readLn().split(" ") ; private fun readInts() = readStrings().map { it.toInt() }
41
Python
202
65
01b04ee56f1e4b151ff5b98094accfeb09b55a95
2,998
Hackerrank-Codes
MIT License
src/main/kotlin/days/Day2.kt
wmichaelshirk
315,495,224
false
null
package days class Day2 : Day(2) { // Each line gives the password policy and then the password. The password policy indicates the // lowest and highest number of times a given letter must appear for the password to be valid. // For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. override fun partOne(): Int { return inputList .filter { val (range, letter, password) = it.split(" ", ": ") val (min, max) = range.split('-').map(String::toInt) val letterChar = letter.single() password.count { l -> l == letterChar } in min..max }.count() } override fun partTwo(): Int { return inputList .filter { val (indices, letter, password) = it.split(" ", ": ") val (i1, i2) = indices.split('-').map(String::toInt).map(Int::dec) val letterChar = letter.single() (password[i1] == letterChar) xor (password[i2] == letterChar) }.count() } }
0
Kotlin
0
0
b36e5236f81e5368f9f6dbed09a9e4a8d3da8e30
1,095
2020-Advent-of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/hildan/hashcode/Main.kt
joffrey-bion
341,976,407
false
null
package org.hildan.hashcode import kotlinx.coroutines.runBlocking import org.hildan.hashcode.utils.reader.HCReader import org.hildan.hashcode.utils.solveHCFilesInParallel import kotlin.math.ceil fun main(args: Array<String>) = runBlocking { solveHCFilesInParallel(*args) { readProblem().solve() } } @OptIn(ExperimentalStdlibApi::class) data class Problem( val duration: Int, val nIntersections: Int, val nStreets: Int, val nCars: Int, val nPointsByCar: Int, val streets: List<Street>, val cars: List<Car>, ) { val streetPopularityByIntersection: Map<Int, MutableMap<String, Int>> = buildMap { val mainMap = this cars.forEach { c -> c.streets.forEach { s -> mainMap.computeIfAbsent(s.end) { HashMap() }.merge(s.name, 1, Int::plus) } } } fun solve(): List<String> { val intersections = streetPopularityByIntersection.mapValues { (_, popularityMap) -> val totalCars = popularityMap.values.sum() val timesByStreet = popularityMap.mapValues { (_, qty) -> ceil(15.0 * qty / totalCars).toInt().coerceAtMost(duration) } timesByStreet.filterValues { it > 0 }.toMap(LinkedHashMap()) } var filteredIntersections = intersections.filterValues { it.isNotEmpty() } println("Initial solution built") var solution = Solution(filteredIntersections) repeat(5) { println("Simulation $it") val result = solution.simulate(this) filteredIntersections = filteredIntersections.mapValues { (id, popularityMap) -> val maxQueuesByStreet = result.intersectionMaxQueues[id]!! val totalMaxCars = maxQueuesByStreet.values.sum() val avgMaxCars = maxQueuesByStreet.values.average() popularityMap.mapValuesTo(LinkedHashMap()) { (street, time) -> val maxQueue = maxQueuesByStreet[street] ?: 0 val diffWithAvg = maxQueue - avgMaxCars val scale = (totalMaxCars + diffWithAvg) / totalMaxCars ceil(time * scale).toInt().coerceAtLeast(1).coerceAtMost(duration) } } solution = Solution(filteredIntersections) } return solution.toLines() } } typealias StreetName = String typealias CarID = Int typealias IntersectionID = Int typealias Time = Int @OptIn(ExperimentalStdlibApi::class) data class Solution( val schedules: Map<IntersectionID, LinkedHashMap<StreetName, Time>>, ) { fun toLines(): List<String> = buildList { add(schedules.size.toString()) schedules.forEach { (id, popularityMap) -> add(id.toString()) add(popularityMap.size.toString()) popularityMap.forEach { (s, time) -> add("$s $time") } } } fun simulate(problem: Problem): SimulationResult { val carStates: MutableList<CarState> = problem.cars.mapTo(ArrayList()) { CarState(it) } val intersectionStates = (0 until problem.nIntersections).associateWith { IntersectionState(schedule = Schedule(schedules[it] ?: LinkedHashMap())) } problem.cars.forEach { car -> val initialStreet = car.streets.first() val initialIntersectionId = initialStreet.end val initialIntersectionState = intersectionStates[initialIntersectionId]!! initialIntersectionState.enqueueCar(initialStreet.name, car.id) } var score = 0 for (t in 0 until problem.duration) { intersectionStates.forEach { (_, state) -> state.step() } val carsToRemove = mutableSetOf<CarID>() carStates.forEach { state -> state.step(intersectionStates) if (state.reachedEndOfPath()) { score += problem.nPointsByCar carsToRemove.add(state.car.id) } } carStates.removeIf { it.car.id in carsToRemove } } val intersectionMaxQueues = intersectionStates.mapValues { (_, state) -> state.maxQueueByStreet } return SimulationResult(intersectionMaxQueues, score) } } data class CarState( val car: Car, /** Index in the list of streets */ var streetIndex: Int = 0, /** Position within the street */ var posInStreet: Int = car.streets.first().length - 1, ) { val street: Street get() = car.streets[streetIndex] fun step(intersectionStates: Map<IntersectionID, IntersectionState>) { if (endOfStreet()) { val inter = intersectionStates[street.end]!! if (inter.didCarLeave(car.id)) { streetIndex++ } } else { posInStreet++ } } private fun endOfStreet(): Boolean = posInStreet == street.length fun reachedEndOfPath(): Boolean = endOfStreet() && streetIndex == car.streets.lastIndex } data class IntersectionState( val schedule: Schedule, ) { val maxQueueByStreet: MutableMap<StreetName, Int> = mutableMapOf() private val carQueuesByStreet: MutableMap<StreetName, MutableList<CarID>> = mutableMapOf() private var lastThatLeft: CarID? = null fun enqueueCar(street: StreetName, car: CarID) { val queue = carQueuesByStreet.computeIfAbsent(street) { ArrayList() } queue.add(car) maxQueueByStreet.merge(street, queue.size, ::maxOf) } fun didCarLeave(car: CarID): Boolean = car == lastThatLeft fun step() { val cars = carQueuesByStreet[schedule.greenStreet] ?: mutableListOf() lastThatLeft = cars.removeFirstOrNull() schedule.step() } } data class Schedule( private val schedule: LinkedHashMap<StreetName, Time>, ) { val greenStreet: StreetName? get() = if (greenStreetIndex in streets.indices) streets[greenStreetIndex] else null private val streets = schedule.keys.toList() private var greenStreetIndex: Int = 0 private var greenFor: Time = 0 fun step() { greenFor++ if (greenStreet != null && greenFor >= schedule[greenStreet]!!) { greenFor = 0 greenStreetIndex = (greenStreetIndex + 1) % streets.size } } } data class SimulationResult( val intersectionMaxQueues: Map<IntersectionID, Map<StreetName, Int>>, val score: Int, ) data class Street( val start: Int, val end: Int, val name: String, val length: Int, ) data class Car( val id: CarID, val streets: List<Street>, ) fun HCReader.readProblem(): Problem { val duration = readInt() val nIntersections = readInt() val nStreets = readInt() val nCars = readInt() val nPoints = readInt() val streets = List(nStreets) { readStreet() } val streetsByName = streets.associateBy { it.name } val cars = List(nCars) { readCar(it, streetsByName) } return Problem(duration, nIntersections, nStreets, nCars, nPoints, streets, cars) } fun HCReader.readStreet(): Street { val start = readInt() val end = readInt() val name = readString() val timeToCross = readInt() return Street(start, end, name, timeToCross) } fun HCReader.readCar(id: Int, streetsByName: Map<String, Street>): Car { val nStreets = readInt() val streets = List(nStreets) { val streetName = readString() streetsByName[streetName]!! } return Car(id, streets) }
0
Kotlin
0
0
1c668eecc504eaf019f9fbce36ee78e6bf9bddb8
7,523
hashcode-2021-qualif
MIT License
src/2020/Day7_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import kotlin.collections.ArrayList /* shiny gold bag dark olive bag faded blue bags faded blue bags faded blue bags dotted black dotted black dotted black dotted black vibrant plum bag faded blue faded blue faded blue faded blue faded blue dotted black dotted black dotted black dotted black dotted black dotted black vibrant plum bag faded blue faded blue faded blue faded blue faded blue dotted black dotted black dotted black dotted black dotted black dotted black */ data class Bag(val color: String, val contents: ArrayList<Bag> = ArrayList<Bag>()) { fun findBagOrNew(color: String): Bag { val x = contents.filter { color == it.color } val i = x.indexOfFirst { color == it.color } return if (i >= 0) x[i] else Bag(color) } fun look(lookingFor: String): Long = contents.filter { it.color == lookingFor }.map { it.count() }.sum() fun count(): Long = contents.size + contents.map { c -> c.count() }.sum() } val bags = Bag("TOP", ArrayList<Bag>()) File("input/2020/day7").forEachLine { val (color,inner) = it.split(" bags contain ") val bag = bags.findBagOrNew(color) if (!bags.contents.contains(bag)) { bags.contents.add(bag) } inner.trim().split(",") .filter { it != "no other bags." } .forEach { val descriptors = it.trim().split(" ") val count = descriptors[0].trim().toInt() val color = descriptors.subList(1, descriptors.lastIndex).joinToString(" ").trim() var innerBag = bags.findBagOrNew(color) if (!bags.contents.contains(innerBag)) { bags.contents.add(innerBag) } for(i in 1..count) { bag.contents.add(innerBag) } } } val lookingFor = "shiny gold" val matches = HashSet<Int>() val total = bags.look(lookingFor) println(total)
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
2,009
adventofcode
MIT License
nebulosa-imaging/src/main/kotlin/nebulosa/imaging/algorithms/computation/fwhm/FWHM.kt
tiagohm
568,578,345
false
{"Kotlin": 2031289, "TypeScript": 322187, "HTML": 164617, "SCSS": 10191, "Python": 2817, "JavaScript": 1119}
package nebulosa.imaging.algorithms.computation.fwhm import nebulosa.imaging.Image import nebulosa.imaging.algorithms.ComputationAlgorithm import kotlin.math.max import kotlin.math.min data class FWHM( private val x: Int, private val y: Int, private val mode: Mode = Mode.MIDDLE_ROW, ) : ComputationAlgorithm<Float> { enum class Mode { MIDDLE_ROW, AVERAGE_ROW, AVERAGE_COL, } override fun compute(source: Image): Float { return compute(source, x, y, mode) } companion object { const val HALFW = 10 const val FULLW = 2 * HALFW + 1 @JvmStatic fun compute(source: Image, x: Int, y: Int, mode: Mode = Mode.MIDDLE_ROW): Float { val profile = FloatArray(FULLW) val startX = max(0, min(x - HALFW, source.width - FULLW)) val startY = max(0, min(y - HALFW, source.height - FULLW)) if (mode == Mode.AVERAGE_ROW || mode == Mode.AVERAGE_COL) { repeat(FULLW) { a -> var index = source.indexAt(startX, startY + a) repeat(FULLW) { b -> val p = source.readGrayBT709(index++) if (mode == Mode.AVERAGE_COL) profile[a] += p else profile[b] += p } } } else { var index = source.indexAt(startX, startY + HALFW) repeat(FULLW) { profile[it] = source.readGrayBT709(index++) } } val min = profile.min() val max = profile.max() val mid = (max - min) / 2f + min var m = 0 var n = 0 for (i in 1 until FULLW) { val a = profile[i] val b = profile[i - 1] if (mid in b..a) m = i else if (mid in a..b) n = i } val c = m - (profile[m] - mid) / (profile[m] - profile[m - 1]) val d = n - (profile[n - 1] - mid) / (profile[n - 1] - profile[n]) return d - c } } }
0
Kotlin
0
1
de96a26e1a79c5b6f604d9af85311223cc28f264
2,134
nebulosa
MIT License
src/Day01.kt
erwinw
572,913,172
false
{"Kotlin": 87621}
@file:Suppress("MagicNumber") private const val DAY = "01" private const val PART1_CHECK = 24000 private const val PART2_CHECK = 45000 fun main() { fun part1(input: List<String>): Int { var highestElfCalories = 0 var currentElfCalories = 0 input.forEach { if (it.isEmpty()) { currentElfCalories = 0 return@forEach } val lineCalories = it.toInt() currentElfCalories += lineCalories if (currentElfCalories > highestElfCalories) { highestElfCalories = currentElfCalories } } return highestElfCalories } fun part2(input: List<String>): Int { val elfCalories: MutableList<Int> = mutableListOf(0) var currentElf = 0 input.forEach { if (it.isEmpty()) { currentElf += 1 return@forEach } val lineCalories = it.toInt() if (currentElf >= elfCalories.size) { elfCalories.add(0) } elfCalories[currentElf] = elfCalories[currentElf] + lineCalories } elfCalories.sortDescending() return elfCalories.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") check(part1(testInput) == PART1_CHECK) check(part2(testInput) == PART2_CHECK) val input = readInput("Day$DAY") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
57cba37265a3c63dea741c187095eff24d0b5381
1,580
adventofcode2022
Apache License 2.0
src/main/kotlin/day12.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
var hits = 0L val foundSprings = mutableMapOf<String, Long>() var cacheHits = 0L fun day12 (lines: List<String>) { var totalArrangements = 0L val allPossibilities = mutableListOf<String>() lines.forEach { line -> val spring = line.split(" ")[0] val groups = line.split(" ")[1].split(",").map { Integer.parseInt(it) } generateAllPossibilities(groups, "", allPossibilities, spring) totalArrangements += allPossibilities.size allPossibilities.clear() foundSprings.clear() } println("Day 12 part 1: $totalArrangements") val unfoldedLines = unfoldLines(lines) var totalUnfoldedArrangements = 0L /*unfoldedLines.forEach { line -> println(line) totalArrangements += findArrangements(line.split(" ")[0], line.split(" ")[1].split(",").map { Integer.parseInt(it) }) foundSprings.clear() }*/ /*unfoldedLines.forEach { line -> val spring = line.split(" ")[0] val groups = line.split(" ")[1].split(",").map { Integer.parseInt(it) } println(spring) generateAllPossibilities(groups, "", allPossibilities, spring) totalUnfoldedArrangements += allPossibilities.size allPossibilities.clear() }*/ println(hits) println(foundSprings.size) println(cacheHits) //generateAllPossibilities(mutableListOf(3,2,1), "", allPossibilities, "?###????????") println("Day 12 part 2: $totalUnfoldedArrangements") println() } fun generateAllPossibilities(groups: List<Int>, spring: String, allPossibilities: MutableList<String>, actualPattern: String) { if (spring.length + groups.sum() + groups.size - 1 > actualPattern.length) { return } for (i in spring.indices) { if (actualPattern[i] != '?' && actualPattern[i] != spring[i]) { return } } if (groups.isEmpty()) { var fillDots = "" for (i in 1..actualPattern.length-spring.length) { fillDots += "." } val newEntry = spring + fillDots for (i in actualPattern.indices) { if (actualPattern[i] != '?' && actualPattern[i] != newEntry[i]) { return } } allPossibilities.add(newEntry) return } generateAllPossibilities(groups, "$spring.", allPossibilities, actualPattern) var localSpring = spring if (localSpring.isEmpty() || localSpring.last() == '.') { for (i in 1..groups[0]) { localSpring += '#' } generateAllPossibilities(groups.drop(1), localSpring, allPossibilities, actualPattern) } } fun findArrangements(springs: String, groups: List<Int>): Long { hits++ /*if (hits % 10000L == 0L) { println(hits) }*/ var springGroupCount = 0 val foundGroups = mutableListOf<Int>() springs.forEach { if (it == '#') { springGroupCount++ } else if (it == '.' && springGroupCount > 0) { foundGroups.add(springGroupCount) springGroupCount = 0 } else if (it != '.') { springGroupCount = 0 } } if (springGroupCount > 0) { foundGroups.add(springGroupCount) springGroupCount = 0 } if (foundGroups.size > groups.size || (foundGroups.size > 0 && foundGroups.max() > groups.max())) { return 0 } if (springs.contains("?")) { val dotReplace = springs.replaceFirst("?", ".") val hashtagReplace = springs.replaceFirst("?", "#") val left: Long val right: Long if (foundSprings.contains(dotReplace)) { cacheHits++ left = foundSprings[dotReplace]!! } else { val temp = findArrangements(dotReplace, groups) foundSprings[dotReplace] = temp left = temp } if(foundSprings.contains(hashtagReplace)) { cacheHits++ right = foundSprings[hashtagReplace]!! } else { val temp = findArrangements(hashtagReplace, groups) foundSprings[hashtagReplace] = temp right = temp } return left + right } if (foundGroups == groups) { return 1 } return 0 } fun unfoldLines(lines: List<String>): List<String> { val unfoldedLines = mutableListOf<String>() lines.forEach { val springs = it.split(" ")[0] val groups = it.split(" ")[1] unfoldedLines.add("$springs?$springs?$springs?$springs?$springs $groups,$groups,$groups,$groups,$groups") } return unfoldedLines }
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
4,743
advent_of_code_2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CanPlaceFlowers.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 /** * 605. Can Place Flowers * @see <a href="https://leetcode.com/problems/can-place-flowers/">Source</a> */ fun interface CanPlaceFlowers { operator fun invoke(flowerbed: IntArray, n: Int): Boolean } class CanPlaceFlowersGreedy : CanPlaceFlowers { override operator fun invoke(flowerbed: IntArray, n: Int): Boolean { var count = 0 var i = 0 while (i < flowerbed.size && count < n) { if (flowerbed[i] == 0) { // get next and prev flower bed slot values. If i lies at the ends the next and prev are // considered as 0. val next = if (i == flowerbed.size - 1) 0 else flowerbed[i + 1] val prev = if (i == 0) 0 else flowerbed[i - 1] if (next == 0 && prev == 0) { flowerbed[i] = 1 count++ } } i++ } return count == n } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,586
kotlab
Apache License 2.0
src/medium/_43MultiplyStrings.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium class _43MultiplyStrings { class Solution { fun multiply(num1: String, num2: String): String { if (num1 == "0" || num2 == "0") { return "0" } val sb = StringBuffer() val length1 = num1.length val length2 = num2.length val answerArr = IntArray(length1 + length2) for (i in (length1 - 1) downTo 0) { val x = num1[i] - '0' for (j in (length2 - 1) downTo 0) { val y = num2[j] - '0' answerArr[i + j + 1] += x * y } } for (i in (length1 + length2 - 1) downTo 1) { answerArr[i - 1] += answerArr[i] / 10 answerArr[i] = answerArr[i] % 10 } var k = if (answerArr[0] == 0) 1 else 0 while (k < (length1 + length2)) { sb.append(answerArr[k]) k++ } return sb.toString() } } class BestSolution { fun multiply(num1: String, num2: String): String { if (num1 == "0" || num2 == "0") { return "0" } val m = num1.length val n = num2.length val ansArr = IntArray(m + n) for (i in m - 1 downTo 0) { val x = num1[i] - '0' for (j in n - 1 downTo 0) { val y = num2[j] - '0' ansArr[i + j + 1] += x * y } } for (i in m + n - 1 downTo 1) { ansArr[i - 1] += ansArr[i] / 10 ansArr[i] %= 10 } var index = if (ansArr[0] == 0) 1 else 0 val ans = StringBuffer() while (index < m + n) { ans.append(ansArr[index]) index++ } return ans.toString() } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
1,951
AlgorithmsProject
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/searching/QuickSelect.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.searching fun main() { val arr = mutableListOf(4, 1, 2, 6, 3, 9, 10, 5, 7, 8) print(quickSelect(arr, 3)) // 4 } // O(n) time | O(1) space private fun quickSelect(arr: MutableList<Int>, k: Int): Int { var low = 0 var high = arr.size - 1 while (low < high) { val j = partition(arr, low, high) when { j < k -> low = j + 1 j > k -> high = j - 1 else -> return arr[j] } } return arr[low] } private fun partition(arr: MutableList<Int>, low: Int, high: Int): Int { var i = low var j = high + 1 val v = arr[low] while (true) { while (arr[++i] < v) if (i == high) break while (v < arr[--j]) if (j == low) break if (j <= i) break swap(arr, i, j) } swap(arr, low, j) return j } private fun swap(arr: MutableList<Int>, i: Int, j: Int) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
993
algs4-leprosorium
MIT License
src/main/kotlin/days/y2023/day14/Day14.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day14 import util.InputReader typealias PuzzleLine = String typealias PuzzleInput = List<PuzzleLine> class Day14(val input: PuzzleInput) { private val start = input.toGrid() fun partOne(): Int { val rows = start.transpose() val rolled = rows.roll() val cols = rolled.transpose() return countLoad(cols) } fun partTwo(n: Int = 1000000000): Int { val cycleParams = detectCycle() val position = cycleParams.get(n) return countLoad(position) } data class CyclicPositions( val positions: List<PuzzleGrid>, val cycleLength: Int, ) { val headerSection = positions.subList(0, positions.size - cycleLength) val cycleSection = positions.subList(positions.size - cycleLength, positions.size) fun get(n: Int): PuzzleGrid { val positionN = n -1 return if (positionN < headerSection.size) { headerSection[positionN] } else { val cycleIndex = positionN - headerSection.size val positionIndex = cycleIndex % cycleLength cycleSection[positionIndex] } } } private fun detectCycle(): CyclicPositions { var position = start val seenOnce = mutableListOf<PuzzleGrid>() val seenTwice = mutableListOf<PuzzleGrid>() val seenThrice = mutableListOf<PuzzleGrid>() while (true) { position = cycle(position) if (seenOnce.contains(position)) { if (!seenTwice.contains(position)) { seenTwice.add(position) } else { if (!seenThrice.contains(position)) { seenThrice.add(position) } else { require(seenThrice.size == seenTwice.size) { "P sure these should always be equal" } return CyclicPositions(seenOnce, seenThrice.size) } } } else { seenOnce.add(position) } } } private fun percentComplete(i: Int, ofI: Int): String { return "%.2f".format(i.toFloat() / ofI.toFloat() * 100) } var cacheHits = 0 var cacheMisses = 0 var seenCache = false val memo: MutableMap<PuzzleGrid, PuzzleGrid> = mutableMapOf() fun cycle(grid: PuzzleGrid): List<List<Char>> { if (memo.contains(grid)) { seenCache = true cacheHits += 1 return memo[grid]!! } else { cacheMisses += 1 } var result = grid // this is definitely not the most efficient way to do this // roll north = transpose, roll, transpose // println("start") // println(toString(result)) result = result.transpose().roll().transpose() // println("roll north") // println(toString(result)) // roll west == roll result = result.roll() // println("roll west") // println(toString(result)) // roll south = reverse, roll north, reverse result = result.reversed().transpose().roll().transpose().reversed() // println("roll south") // println(toString(result)) result = result.transpose().reversed().transpose().roll().transpose().reversed().transpose() // println("roll east") // println(toString(result)) return result.also { memo[grid] = it } } private fun countLoad(rows: PuzzleGrid): Int { val reverseRows = rows.reversed() val counts = reverseRows.mapIndexed { i, row -> i + 1 to row.count { it == 'O' } } return counts.sumOf { it.first * it.second } } private fun PuzzleGrid.roll(): PuzzleGrid = map { row -> rollRow(row) } private fun rollRow(row: List<Char>) = mutableListOf<Char>().apply { var skippedDots = 0 row.forEach { c -> if (c == '.') { skippedDots++ } else { if (c != 'O' && skippedDots > 0) { this.addAll(".".repeat(skippedDots).toList()) skippedDots = 0 } this += c } } if (skippedDots > 0) { this.addAll(".".repeat(skippedDots).toList()) } require(this.size == row.size) { "Result size ${this.size} != row size ${row.size}" } } } typealias PuzzleGrid = List<List<Char>> fun PuzzleInput.toGrid(): PuzzleGrid { return this.map { it.toList() } } fun toString(grid: PuzzleGrid): String { return grid.joinToString("\n") { it.joinToString("") } } private fun PuzzleGrid.transpose(): PuzzleGrid { val rows = this.size val cols = this[0].size val newGrid = MutableList(cols) { MutableList(rows) { ' ' } } for (row in 0 until rows) { for (col in 0 until cols) { newGrid[col][row] = this[row][col] } } return newGrid } fun PuzzleGrid.rotateClockwise(): PuzzleGrid { return this.transpose().map { it.reversed() } } fun PuzzleGrid.rotateCounterClockwise(): PuzzleGrid { return this.reversed().transpose() } fun main() { val year = 2023 val day = 14 val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day) fun partOne(input: PuzzleInput) = Day14(input).partOne() fun partTwo(input: PuzzleInput) = Day14(input).partTwo() fun partTwo(input: PuzzleInput, n: Int) = Day14(input).partTwo(n) println("Example 1: ${partOne(exampleInput)}") println("Puzzle 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput, 1)}") println("Example 2: ${partTwo(exampleInput, 2)}") println("Example 2: ${partTwo(exampleInput, 3)}") println("Puzzle 2: ${partTwo(puzzleInput)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
6,027
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/hj/leetcode/kotlin/problem1396/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1396 /** * LeetCode page: [1396. Design Underground System](https://leetcode.com/problems/design-underground-system/); */ class UndergroundSystem() { private val activeCheckIn = hashMapOf<CustomerID, CheckInRecord>() private val tripTimeSummary = hashMapOf<Trip, TimeSummary>() private data class CustomerID(val value: Int) private data class CheckInRecord(val stationName: String, val timeStamp: Int) private data class Trip(val fromStation: String, val toStation: String) private data class TimeSummary(val totalTimes: Int, val numTrips: Int) { fun averageTravelTime(): Double { return totalTimes.toDouble() / numTrips } } /* Complexity of N calls: * Time O(N) and Space O(N); */ fun checkIn(id: Int, stationName: String, t: Int) { check(!activeCheckIn.contains(CustomerID(id))) { "The customer has already checked in but has not yet checked out." } activeCheckIn[CustomerID(id)] = CheckInRecord(stationName, t) } /* Complexity of N calls: * Time O(N) and Space O(N); */ fun checkOut(id: Int, stationName: String, t: Int) { val checkInRecord = activeCheckIn[CustomerID(id)] ?: throw IllegalStateException("The corresponding check in record is not found.") activeCheckIn.remove(CustomerID(id)) val trip = Trip(checkInRecord.stationName, stationName) val tripDuration = t - checkInRecord.timeStamp val oldSummary = tripTimeSummary[trip] ?: TimeSummary(0, 0) val newSummary = TimeSummary(oldSummary.totalTimes + tripDuration, oldSummary.numTrips + 1) tripTimeSummary[trip] = newSummary } /* Complexity: * Time O(1) and Space O(1); */ fun getAverageTime(startStation: String, endStation: String): Double { val trip = Trip(startStation, endStation) val summary = tripTimeSummary[trip] ?: TimeSummary(0, 0) return summary.averageTravelTime() } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,042
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/be/amedee/adventofcode/aoc2015/day02/Day02.kt
amedee
160,062,642
false
{"Kotlin": 9459, "Markdown": 7503}
package be.amedee.adventofcode.aoc2015.day02 import java.io.BufferedReader import java.io.InputStreamReader fun getSurfaceArea( length: Int, width: Int, height: Int, ) = 2 * ((length * width) + (width * height) + (height * length)) fun getSlack( length: Int, width: Int, height: Int, ) = minOf(length * width, width * height, height * length) fun calculateWrappingPaperOrder(presentDimensions: List<Triple<Int, Int, Int>>): Int { var totalSquareFeet = 0 presentDimensions.forEach { (l, w, h) -> val surfaceArea = getSurfaceArea(l, w, h) val slack = getSlack(l, w, h) totalSquareFeet += surfaceArea + slack } return totalSquareFeet } class Day02 { fun readPresentDimensionsFromFile(fileName: String): List<Triple<Int, Int, Int>> { val packageName = javaClass.`package`.name.replace(".", "/") val filePath = "/$packageName/$fileName" val inputStream = javaClass.getResourceAsStream(filePath) val presentDimensions = mutableListOf<Triple<Int, Int, Int>>() if (inputStream != null) { BufferedReader(InputStreamReader(inputStream)).useLines { lines -> lines.forEach { line -> val dimensions = line.split("x").map { it.toInt() } if (dimensions.size == 3) { presentDimensions.add(Triple(dimensions[0], dimensions[1], dimensions[2])) } } } } return presentDimensions } } fun main() { val inputFile = "input" val presentDimensions = Day02().readPresentDimensionsFromFile(inputFile) val totalSquareFeet = calculateWrappingPaperOrder(presentDimensions) println("Elves should order ${"%,d".format(totalSquareFeet)} square feet of wrapping paper.") }
0
Kotlin
0
1
02e8e0754f2252a2850175fc8b134dd36bc6d042
1,834
adventofcode
MIT License
src/main/kotlin/at2020/day1/At2020Day1Part1.kt
JeanBarbosa27
575,328,729
false
{"Kotlin": 10872}
package at2020.day1 class At2020Day1Part1 : At2020Day1() { override var entriesToReachTargetSum = IntArray(2) { 0 } override val puzzleDescription: String = "Day1 part 1 description:\n" + "Find the two entries that sum to 2020; what do you get if you multiply them together?\n" private fun calculateProduct(): Int { return entriesToReachTargetSum[0] * entriesToReachTargetSum[1] } private fun setEntriesToReachTargetSum(elementToSum: Int) { entriesToReachTargetSum[0] = expenseReport[currentIndex] entriesToReachTargetSum[1] = elementToSum } override fun searchEntriesToGetProduct(list: List<Int>) { println("list.size: ${list.size}") if (list.size < 5) { println("list is less than 5, here it is: $list") var elementToSumIndex = 0 while (elementToSumIndex <= list.lastIndex) { println("list.lastIndex: ${list.lastIndex}") println("currentIndex: $currentIndex") println("elementToSumIndex: $elementToSumIndex") setEntriesToReachTargetSum(list[elementToSumIndex]) if (entriesToReachTargetSum.sum() == targetSum) { println("product is: ${calculateProduct()}") break } elementToSumIndex++ if (elementToSumIndex > list.lastIndex) { currentIndex++ searchEntriesToGetProduct(expenseReport) } } return } val listMiddleIndex = list.lastIndex / 2 println("listMiddleIndex: $listMiddleIndex") println("lastIndex: ${list.lastIndex}") if (listMiddleIndex > 0) { println("list[currentIndex]: ${list[currentIndex]}") println("list[listMiddleIndex]: ${list[listMiddleIndex]}") setEntriesToReachTargetSum(list[listMiddleIndex]) println("entriesToReachTargetSum: ${entriesToReachTargetSum[0]}, ${entriesToReachTargetSum[1]}") if (entriesToReachTargetSum.sum() == targetSum) { println("Target sum found!") println(calculateProduct()) return } val halfList = mutableListOf<Int>() if (entriesToReachTargetSum.sum() > targetSum) { println("Target sum is in first half, reiterating") println(entriesToReachTargetSum.sum()) list.forEachIndexed { index, number -> if (index <= listMiddleIndex) halfList.add(number) } println("halfList is: $halfList") searchEntriesToGetProduct(halfList) return } println("Target sum is in second half, reiterating") println(entriesToReachTargetSum.sum()) list.forEachIndexed { index, number -> if (index >= listMiddleIndex && index <= list.lastIndex ) halfList.add(number) } searchEntriesToGetProduct(halfList) } } }
0
Kotlin
0
0
62c4e514cd9a306e6a4b5dbd0c146213f08e05f3
3,067
advent-of-code-solving-kotlin
MIT License
test/leetcode/MaxWordsThatCanBeTyped.kt
andrej-dyck
340,964,799
false
null
package leetcode import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource /** * https://leetcode.com/problems/maximum-number-of-words-you-can-type/ * * 1935. Maximum Number of Words You Can Type * [Easy] * * There is a malfunctioning keyboard where some letter keys do not work. * All other keys on the keyboard work properly. * * Given a string text of words separated by a single space (no leading or trailing spaces) * and a string brokenLetters of all distinct letter keys that are broken, return the number * of words in text you can fully type using this keyboard. * * Constraints: * - 1 <= text.length <= 10^4 * - 0 <= brokenLetters.length <= 26 * - text consists of words separated by a single space without any leading or trailing spaces. * - Each word only consists of lowercase English letters. * - brokenLetters consists of distinct lowercase English letters. */ fun maxWordsThatCanBeTyped(text: String, brokenLetters: String): Int = maxWordsThatCanBeTyped(text.lowercase(), brokenLetters.toHashSet()) fun maxWordsThatCanBeTyped(text: String, brokenLetters: Set<Char>) = text.split(' ').count { it.containsNone(brokenLetters) } fun String.containsNone(other: Set<Char>) = toHashSet().intersect(other).none() /** * Unit tests */ class MaxWordsThatCanBeTypedTest { @ParameterizedTest @CsvSource( "a, '', 1", "a, a, 0", "the quick brown fox jumps over the lazy dog, '', 9", "the quick brown fox jumps over the lazy dog, abcdefghijklmnopqrstuvwxyz, 0", "the quick brown fox jumps over the lazy dog, t, 7", "hello world, ad, 1", "leet code, lt, 1", "leet code, e, 0" ) fun `max number of words you can type of the text with the broken-keys`( text: String, brokenLetters: String, expectedWords: Int ) { assertThat( maxWordsThatCanBeTyped(text, brokenLetters) ).isEqualTo( expectedWords ) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
2,090
coding-challenges
MIT License
leetcode/src/offer/middle/Offer31.kt
zhangweizhe
387,808,774
false
null
package offer.middle import java.util.* fun main() { // 剑指 Offer 31. 栈的压入、弹出序列 // https://leetcode.cn/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/ println(validateStackSequences1(intArrayOf(2,1,0), intArrayOf(1,2,0))) } fun validateStackSequences(pushed: IntArray, popped: IntArray): Boolean { val stack = Stack<Int>() var popIndex = 0 for (i in pushed) { stack.push(i) // 循环判断与出栈 while (stack.isNotEmpty() && stack.peek() == popped[popIndex]) { stack.pop() popIndex++ } } return stack.isEmpty() } fun validateStackSequences1(pushed: IntArray, popped: IntArray): Boolean { val stack = Stack<Int>() var poppedIndex = 0 for (i in pushed) { if (i == popped[poppedIndex]) { poppedIndex++ while (stack.isNotEmpty() && poppedIndex < popped.size && stack.peek() == popped[poppedIndex]) { poppedIndex++ stack.pop() } }else { stack.push(i) } } return stack.isEmpty() } class Test { fun higherFunction(age: Int, param: (unit:String, weight:Float)->String) { val weightUnit = param("kg", 20.0f) println(weightUnit) } fun testLambda() { higherFunction(1) {unit, weight -> "$weight $unit" } val listOf = listOf(1, 2, 3) listOf.forEach { println(it) } listOf.find { it % 2 == 0 } } fun normalFunc(block: () -> Unit) { block() println("call normal func") } inline fun inlineFunc(block: () -> Unit) { block() println("call inline func") } fun callInline() { val normal = normalFunc{ } val in_line = inlineFunc { } } }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,874
kotlin-study
MIT License
src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0947_most_stones_removed_with_same_row_or_column // #Medium #Depth_First_Search #Graph #Union_Find #Level_2_Day_19_Union_Find // #2023_04_30_Time_200_ms_(100.00%)_Space_56_MB_(5.88%) class Solution { private val roots = IntArray(20002) fun removeStones(stones: Array<IntArray>): Int { for (stone in stones) { init(stone[0] + 1, roots) init(stone[1] + 10000, roots) union(stone[0] + 1, stone[1] + 10000) } val set: HashSet<Int> = HashSet() for (n in roots) { if (n == 0) { continue } set.add(find(n)) } return stones.size - set.size } private fun init(i: Int, roots: IntArray) { if (roots[i] != 0) { return } roots[i] = i } private fun union(i: Int, j: Int) { val ri = find(i) val rj = find(j) if (ri == rj) { return } roots[ri] = rj } private fun find(i: Int): Int { var cur = i while (cur != roots[cur]) { cur = roots[roots[cur]] } return cur } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,178
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g1401_1500/s1443_minimum_time_to_collect_all_apples_in_a_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1443_minimum_time_to_collect_all_apples_in_a_tree // #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree // #2023_06_07_Time_793_ms_(85.71%)_Space_104.6_MB_(57.14%) @Suppress("UNUSED_PARAMETER") class Solution { fun minTime(n: Int, edges: Array<IntArray>, hasApple: List<Boolean>): Int { val visited: MutableSet<Int> = HashSet() val graph: MutableMap<Int, MutableList<Int>> = HashMap() for (edge in edges) { val vertexA = edge[0] val vertexB = edge[1] graph.computeIfAbsent(vertexA) { _: Int? -> ArrayList() }.add(vertexB) graph.computeIfAbsent(vertexB) { _: Int? -> ArrayList() }.add(vertexA) } visited.add(0) val steps = helper(graph, hasApple, 0, visited) return if (steps > 0) steps - 2 else 0 } private fun helper( graph: Map<Int, MutableList<Int>>, hasApple: List<Boolean>, node: Int, visited: MutableSet<Int> ): Int { var steps = 0 for (child in graph.getOrDefault(node, mutableListOf())) { if (visited.contains(child)) { continue } else { visited.add(child) } steps += helper(graph, hasApple, child, visited) } return if (steps > 0) { steps + 2 } else if (java.lang.Boolean.TRUE == hasApple[node]) { 2 } else { 0 } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,494
LeetCode-in-Kotlin
MIT License
aoc2022/aoc2022-kotlin/src/main/kotlin/de/havox_design/aoc2022/day16/ProboscideaVolcanium.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2022.day16 class ProboscideaVolcanium(private var filename: String) { val valves = readFile() private val usefulValves = valves.filter { valve -> valve.value.rate > 0 } private val distances = computeDistances() fun processPart1(): Int = traverse(minutes = 30) fun processPart2(): Int = traverse(minutes = 26, elephantGoesNext = true) @SuppressWarnings("kotlin:S6611") private fun traverse( minutes: Int, current: Valve = valves.getValue("AA"), remaining: Set<Valve> = usefulValves.values.toSet(), cache: MutableMap<State, Int> = mutableMapOf(), elephantGoesNext: Boolean = false ): Int { val currentScore = minutes * current.rate val currentState = State(current.name, minutes, remaining) return currentScore + cache.getOrPut(currentState) { val maxCurrent = remaining .filter { next -> distances[current.name]!![next.name]!! < minutes } .takeIf { it.isNotEmpty() } ?.maxOf { next -> val remainingMinutes = minutes - 1 - distances[current.name]!![next.name]!! traverse(remainingMinutes, next, remaining - next, cache, elephantGoesNext) } ?: 0 maxOf(maxCurrent, if (elephantGoesNext) traverse(minutes = 26, remaining = remaining) else 0) } } @SuppressWarnings("kotlin:S6611") private fun computeDistances(): Map<String, Map<String, Int>> = valves .keys .map { valve -> val distances = mutableMapOf<String, Int>() .withDefault { Int.MAX_VALUE } .apply { put(valve, 0) } val toVisit = mutableListOf(valve) while (toVisit.isNotEmpty()) { val current = toVisit.removeFirst() valves[current]!! .next .forEach { neighbour -> val newDistance = distances[current]!! + 1 if (newDistance < distances.getValue(neighbour)) { distances[neighbour] = newDistance toVisit.add(neighbour) } } } distances }.associateBy { it.keys.first() } private fun readFile(): Map<String, Valve> { val fileData = getResourceAsText(filename) return fileData .map(Valve.Companion::from) .associateBy(Valve::name) } private fun getResourceAsText(path: String): List<String> = this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines() }
4
Kotlin
0
1
b94716fbc95f18e68774eb99069c0b703875615c
2,824
aoc2022
Apache License 2.0
src/shreckye/coursera/algorithms/IntBits.kt
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms fun Int.flipSequence(length: Int, hammingDistance: Int, startIndex: Int = 0): Sequence<Int> = if (hammingDistance == 0) sequenceOf(this) else (startIndex..length - hammingDistance).asSequence().flatMap { (this xor (1 shl it)).flipSequence(length, hammingDistance - 1, it + 1) } fun setSequence(length: Int, setSize: Int) = 0.flipSequence(length, setSize) /** [this] must be smaller than 1 [shl] [startIndex] */ fun Int.supersetSequence(length: Int, extraSetSize: Int, startIndex: Int) = this.flipSequence(length, extraSetSize, startIndex) fun Int.subsetSequenceWithSingleDifference(length: Int): Sequence<IntPair> = (0 until length).asSequence() .map { it to (1 shl it) } .filter { (_, mask) -> this and mask != 0 } .map { (index, mask) -> index to (this xor mask) } fun Int.subsetsWithSingleDifference(length: Int): List<IntPair> = subsetSequenceWithSingleDifference(length).toList() fun Int.elementBitIndices(length: Int): Sequence<Int> = (0 until length).asSequence() .filter { this and (1 shl it) != 0 }
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
1,146
coursera-stanford-algorithms-solutions-kotlin
MIT License
src/main/kotlin/com/github/michaelbull/advent2023/day18/DigPlan.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day18 import com.github.michaelbull.advent2023.math.Vector2 import kotlin.math.absoluteValue fun Sequence<String>.toDigPlan(): DigPlan { return DigPlan(this.map(String::toInstruction).toList()) } data class DigPlan( val instructions: List<Instruction>, ) { fun lagoonCapacity(): Long { val vertices = instructions.runningFold(Vector2.ZERO, Vector2::plus) val perimeter = instructions.sumOf(Instruction::length).toLong() return vertices.area() + (perimeter / 2) + 1 } fun fix(): DigPlan { return copy(instructions = instructions.map(Instruction::fix)) } } private operator fun Vector2.plus(instruction: Instruction): Vector2 { return this + (instruction.direction.vector * instruction.length) } private fun List<Vector2>.area(): Long { return zipWithNext(Vector2::cross).sum().absoluteValue / 2 } private fun Instruction.fix(): Instruction { return copy( direction = color.last().toDirection(), length = color.take(5).toInt(16) ) }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
1,069
advent-2023
ISC License
src/main/kotlin/pl/jpodeszwik/aoc2023/Day06.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 import java.lang.Long.parseLong private fun parseLine(line: String) = line.split(":")[1] .trim() .replace("\\s+".toRegex(), " ") .split(" ") .map { parseLong(it) } private fun part1(lines: List<String>) { val times = parseLine(lines[0]) val distances = parseLine(lines[1]) var mul = 1L for (i in times.indices) { val time = times[i] val distance = distances[i] var waysToBeat = 0L for (j in 1..<time) { if ((time - j) * j > distance) { waysToBeat++ } } mul *= waysToBeat } println(mul) } private fun parseLinePart2(line: String) = line.split(":")[1] .trim() .replace("\\s+".toRegex(), "") .let { parseLong(it) } private fun part2(lines: List<String>) { val time = parseLinePart2(lines[0]) val distance = parseLinePart2(lines[1]) var waysToBeat = 0L for (j in 1..<time) { val resultDistance = (time - j) * j if (resultDistance > distance) { waysToBeat++ } } println(waysToBeat) } fun main() { val lines = loadFile("/aoc2023/input6") part1(lines) part2(lines) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
1,212
advent-of-code
MIT License
src/main/kotlin/me/peckb/aoc/_2022/calendar/day20/Day20.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2022.calendar.day20 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import kotlin.math.abs class Day20 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::number) { input -> val (zeroNode, circle) = setupData(input) rotate(circle) groveCoordinates(zeroNode).sumOf { circle[it].data } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::number) { input -> val key = 811589153L val (zeroNode, circle) = setupData(input) val originalValues = mutableMapOf<Int, Long>() circle.forEach { n -> originalValues[n.id] = n.data n.data = (n.data * key) % (circle.size - 1) } repeat(10) { rotate(circle) } groveCoordinates(zeroNode).sumOf { originalValues[it]!! * key } } private fun setupData(input: Sequence<Long>): Pair<Node, List<Node>> { var zeroNode: Node? = null val circle = input.mapIndexed { index, data -> Node(index, data).also { if (data == 0L) zeroNode = it } }.toList() circle.windowed(2).forEach { (a, b) -> a.next = b b.previous = a } (circle.first() to circle.last()).let { (a, b) -> a.previous = b b.next = a } return zeroNode!! to circle } private fun rotate(circle: List<Node>) { circle.forEach { node -> repeat(abs(node.data).toInt()) { if (node.data < 0) { swap(node.previous, node) } else { swap(node, node.next) } } } } // [x first second y] -> [x second first y] private fun swap(first: Node, second: Node) { val x = first.previous val y = second.next y.previous = first first.next = y first.previous = second second.next = first second.previous = x x.next = second } private fun groveCoordinates(zeroNode: Node): List<Int> { val numbers = mutableListOf<Int>() var current = zeroNode repeat(3000) { current = current.next if (((it + 1) % 1000) == 0) numbers.add(current.id) } return numbers } private fun number(line: String) = line.toLong() data class Node(val id: Int, var data: Long) { lateinit var previous: Node lateinit var next: Node } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,356
advent-of-code
MIT License