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/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions53.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 fun test53() { printlnResult1(3, intArrayOf(1, 2, 3, 3, 3, 3, 4, 5)) printlnResult1(3, intArrayOf(3, 3, 3, 3, 4, 5, 6)) printlnResult1(3, intArrayOf(1, 1, 2, 3, 3, 3, 3)) printlnResult1(1, intArrayOf(1)) printlnResult1(0, intArrayOf(1, 1, 1, 1, 1, 1)) printlnResult2(intArrayOf(0, 1, 2, 3, 4, 6 ,7, 8, 9)) printlnResult2(intArrayOf(1, 2, 3, 4, 5, 6 ,7, 8, 9)) printlnResult2(intArrayOf(1)) printlnResult3(intArrayOf(-3, -1, 1, 3, 5)) printlnResult3(intArrayOf(0)) printlnResult3(intArrayOf(0, 1, 2, 3, 4)) printlnResult3(intArrayOf(-3, -1, 1, 3, 5, 9)) } /** * Questions 53-1: Find the count of a number appears in a sorted IntArray. */ private infix fun IntArray.findCount(num: Int): Int { require(isNotEmpty()) { "The array can't be empty" } var firstIndex = -1 var start = 0 var mid = size / 2 var end = lastIndex if (first() > num || last() < num) return 0 while (mid in 0..lastIndex) { when { this[mid] > num -> { end = mid mid = (end - start) / 2 + start } this[mid] < num -> { start = mid + 1 mid = (end - start) / 2 + start } else -> if (mid == 0 || this[mid - 1] != this[mid]) { firstIndex = mid break } else { end = mid mid = (end - start) / 2 + start } } } var lastIndex1 = -1 start = 0 mid = size / 2 end = lastIndex while (mid in 0..lastIndex) { when { this[mid] > num -> { end = mid mid = (end - start) / 2 + start } this[mid] < num -> { start = mid + 1 mid = (end - start) / 2 + start } else -> { if (mid == lastIndex || this[mid + 1] != this[mid]) { lastIndex1 = mid break } else { start = mid + 1 mid = (end - start) / 2 + start } } } } return if (lastIndex1 >= 0 && firstIndex >= 0) lastIndex1 - firstIndex + 1 else 0 } private fun printlnResult1(num: Int, array: IntArray) = println("The number $num appear ${array findCount num} times in array: ${array.toList()}") /** * Questions 52-2: There is a IntArray that's size is n-1, the numbers in the IntArray is sorted, and it begins with 0, ends with n, * and each number is different, find the number that the IntArray doesn't contain. */ private fun IntArray.findLeakedNumber(): Int { var start = 0 var mid = size / 2 var end = lastIndex while (mid in 0..lastIndex) { when { this[mid] == mid -> { start = mid + 1 mid = (end - start) / 2 + start } mid == 0 || this[mid - 1] == mid - 1 -> return mid else -> { end = mid mid = (end - start) / 2 + start } } } throw IllegalArgumentException("The IntArray doesn't leak any number") } private fun printlnResult2(array: IntArray) = println("The array: ${array.toList()} leaks number ${array.findLeakedNumber()}") /** * Questions 53-3: An IntArray monotonically increasing, each number is only one. Found the number that equals its index in the IntArray. */ private fun IntArray.findNumberThatEqualsIndex(): Int { require(isNotEmpty()) { "The IntArray can't be empty" } var start = 0 var mid = size / 2 var end = lastIndex while (mid in 0..lastIndex) { when { this[mid] == mid -> return mid mid == 0 || mid == lastIndex -> throw IllegalArgumentException("The IntArray doesn't contain the number that equals its index") this[mid] > mid -> { end = mid mid = (end - start) / 2 + start } this[mid] < mid -> { start = mid + 1 mid = (end - start) / 2 + start } } } throw IllegalArgumentException("The IntArray doesn't contain the number that equals its index") } private fun printlnResult3(array: IntArray) = println("The number that equals its index in IntArray: ${array.toList()} is ${array.findNumberThatEqualsIndex()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
4,513
Algorithm
Apache License 2.0
src/main/kotlin/Day10.kt
andrewrlee
434,584,657
false
{"Kotlin": 29493, "Clojure": 14117, "Shell": 398}
import Day10.Type.CLOSE import Day10.Type.OPEN import java.io.File import java.nio.charset.Charset.defaultCharset import java.util.Stack object Day10 { data class Bracket(val bracketType: BracketType, val type: Type) enum class Type { OPEN, CLOSE } enum class BracketType(val open: Char, val close: Char, val points: Int, val autoCompleteScore: Int) { SQUARE('[', ']', 57, 2), ROUND('(', ')', 3, 1), BRACE('{', '}', 1197, 3), ANGLE('<', '>', 25137, 4); fun match(c: Char): Type? = when (c) { open -> OPEN close -> CLOSE else -> null } } fun String.toBrackets() = this.map { c -> BracketType.values().firstNotNullOf { b -> b.match(c)?.let { Bracket(b, it) } } } object Part1 { private fun findInvalid(brackets: List<Bracket>): BracketType? { val stack = Stack<Bracket>() brackets.forEach { if (it.type == CLOSE) { val opening = stack.pop() if (it.bracketType != opening.bracketType) { return it.bracketType } } else { stack.push(it) } } return null } fun run() { File("day10/input-real.txt") .readLines(defaultCharset()) .mapNotNull { findInvalid(it.toBrackets()) } .map { it.points } .reduce(Int::plus) .also { println(it) } } } object Part2 { private fun complete(brackets: List<Bracket>): Long? { val stack = Stack<Bracket>() brackets.forEach { if (it.type == CLOSE) { val opening = stack.pop() if (it.bracketType != opening.bracketType) { return null } } else { stack.push(it) } } if (stack.isEmpty()) { return null } return stack.reversed().fold(0L) { acc, b -> (acc * 5) + b.bracketType.autoCompleteScore } } fun run() { File("day10/input-real.txt").readLines(defaultCharset()) .mapNotNull { complete(it.toBrackets()) } .sorted() .also { println(it[it.size/2]) } } } } fun main() { Day10.Part1.run() Day10.Part2.run() }
0
Kotlin
0
0
aace0fccf9bb739d57f781b0b79f2f3a5d9d038e
2,551
adventOfCode2021
MIT License
src/main/kotlin/g2601_2700/s2601_prime_subtraction_operation/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2601_prime_subtraction_operation // #Medium #Array #Math #Greedy #Binary_Search #Number_Theory // #2023_07_13_Time_233_ms_(100.00%)_Space_38.4_MB_(100.00%) class Solution { private fun primesUntil(n: Int): IntArray { if (n < 2) return intArrayOf() val primes = IntArray(200) val composite = BooleanArray(n + 1) primes[0] = 2 var added = 1 var i = 3 while (i <= n) { if (composite[i]) { i += 2 continue } primes[added++] = i var j = i * i while (j <= n) { composite[j] = true j += i } i += 2 } return primes.copyOf(added) } fun primeSubOperation(nums: IntArray): Boolean { var max = 0 for (n in nums) { max = max.coerceAtLeast(n) } val primes = primesUntil(max) var prev = 0 for (n in nums) { val pos = primes.binarySearch(n - prev - 1) if (pos == -1 && n <= prev) return false prev = n - if (pos == -1) 0 else if (pos < 0) primes[-pos - 2] else primes[pos] } return true } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,246
LeetCode-in-Kotlin
MIT License
src/main/kotlin/Day05.kt
uipko
572,710,263
false
{"Kotlin": 25828}
enum class MoverType { TYPE_9000, TYPE_9001 } fun main() { val crates = crateMover("Day05.txt", MoverType.TYPE_9000) println("CrateMover 9000 top crates are $crates") val crates2 = crateMover("Day05.txt", MoverType.TYPE_9001) println("CrateMover 9001 top crates are $crates2") } fun crateMover(fileName: String, type: MoverType): String { val (stack, moves) = readFile(fileName).split("\n\n").map { it.lines()} val stacks = (stack.dropLast(1).map { it.padEnd(stack.last().length+3/4*4, ' ' ) }.map { chunks -> chunks.chunked(4).map { it[1]} }) val columns = (stacks.first().indices).map { columnIndex -> stacks.map { it[columnIndex] }.filter { !it.isWhitespace() }.toMutableList() } moves.forEach { move -> move.split(" ").drop(1).filter { it.toIntOrNull() != null } .map { it.toInt() }.let { (nr, from, to) -> val elementsToMove = columns[from - 1].subList(0,nr) columns[to - 1].addAll(0, elementsToMove.let {if (type == MoverType.TYPE_9000) it.reversed() else it}) elementsToMove.clear() } } return columns.map { it.first() }.joinToString("") }
0
Kotlin
0
0
b2604043f387914b7f043e43dbcde574b7173462
1,198
aoc2022
Apache License 2.0
src/jvmMain/kotlin/Atom.kt
leonhardbrenner
327,734,139
false
null
import java.util.* val Pair<Int, Int>.a: Int get() = first val Pair<Int, Int>.b: Int get() = second fun <T, R> Sequence<T>.reductions(initial: R, operation: (acc: R, T) -> R) : Sequence<R> = sequence { var last = initial forEach { last = operation(last, it) yield(last) } } class Atom(val data: IntArray) { override fun toString() = Arrays.toString(this.data) operator fun get(index: Atom) = Atom(data.sliceArray(index.data.toList())) operator fun set(index: Atom, value: Atom) { (index.data zip value.data).map { pair: Pair<Int, Int> -> val (index, value) = pair this.data[index] = value } } operator fun plus(b: Int) = Atom(data.map { it + b }.toIntArray()) operator fun plus(other: Atom) = Atom((data zip other.data).map { it.a + it.b }.toIntArray()) operator fun minus(b: Int) = Atom(data.map { it - b }.toIntArray()) operator fun minus(other: Atom) = Atom((data zip other.data).map { it.a - it.b }.toIntArray()) operator fun times(b: Int) = Atom(data.map { it * b }.toIntArray()) operator fun times(other: Atom) = Atom((data zip other.data).map { it.a * it.b }.toIntArray()) operator fun div(b: Int) = Atom(data.map { it / b }.toIntArray()) operator fun div(other: Atom) = Atom((data zip other.data).map { it.a / it.b }.toIntArray()) operator fun rem(b: Int) = Atom(data.map { it % b }.toIntArray()) operator fun rem(other: Atom) = Atom((data zip other.data).map { it.a % it.b }.toIntArray()) //Todo - implement this like rl.range operator fun rangeTo(b: Int): Atom = TODO("Not specified yet") //Atom(data.map { it % b }.toIntArray()) operator fun rangeTo(other: Atom): Atom = TODO("Not specified yet") //Atom((data zip other.data).map { it.a % it.b }.toIntArray()) fun cumsum(): Atom { var last = 0 return Atom(data.map { last += it last }.toIntArray()) } fun repeat(count: Int): Atom { return Atom(this.data.flatMap { value -> IntRange(1, count).map { value } }.toIntArray()) } fun repeat(counts: IntArray): Atom { return Atom(this.data.zip(counts).flatMap { pair -> val (value, count) = pair IntRange(1, count).map { value } }.toIntArray()) } fun repeat(counts: Atom): Atom { return this.repeat(counts.data) } } fun main(args: Array<String>) { val x = Atom(arrayOf(1, 2, 3, 4).toIntArray()) val y = Atom(arrayOf(1, 3).toIntArray()) println("x = $x") println("y = $y") println("x[y] = ${x[y]}") println("x + 1 = ${x + 1}") println("x + x = ${x + x}") println("x - 1 = ${x - 1}") println("x - x = ${x - x}") println("x * 1 = ${x * 1}") println("x * x = ${x * x}") println("x / 2 = ${x / 2}") println("x / (x * 2) = ${x / (x * 2)}") println("x % 2 = ${x % 2}") println("x % (x * 2) = ${x % Atom(arrayOf(2, 2, 2, 2).toIntArray())}") x[y] = y + 2; println("x[y] = y + 2; x = ${x}") try { x[y]..2 } catch (ex: NotImplementedError) { println("TODO - Think of a useful way of using ..") } try { x[y]..y } catch (ex: NotImplementedError) { println("TODO - Think of a useful way of using ..") } println(x) println(x.cumsum()) //SequenceOf println(sequenceOf(0, 1, 2, 3, 4).reductions(0) { last, it -> last + it }.toList()) //Cumsum println(sequenceOf(0, 1, 2, 3, 4).reduce { last, it -> last + it }) //Sum println(x.repeat(3)) println(x.repeat(x)) }
0
Kotlin
0
1
a7b970179bb6a740475879a036dc4d9189203290
3,628
kitchensink
MIT License
src/utils/Itertools.kt
abhabongse
576,594,038
false
{"Kotlin": 63915}
package utils import java.util.* /** * Chain multiple sequences together. */ fun <T> Sequence<T>.chain(other: Sequence<T>): Sequence<T> = this.iterator().let { iterator -> sequence { for (item in iterator) { this.yield(item) } for (item in other.iterator()) { this.yield(item) } } } /** * Find [n] smallest items from the sequence. * The result is returned in the sorted descending order. */ fun <T : Comparable<T>> Sequence<T>.smallest(n: Int): List<T> { return this.largestWith(n, reverseOrder()) } /** * Find [n] largest items from the sequence. * The result is returned in the sorted descending order. */ fun <T : Comparable<T>> Sequence<T>.largest(n: Int): List<T> { return this.largestWith(n, naturalOrder()) } /** * Find [n] smallest items from the sequence according to the provided key [selector]. * The result is returned in the sorted order starting from the largest item. */ fun <T> Sequence<T>.smallestBy(n: Int, selector: (T) -> Comparable<*>): List<T> { return this.largestWith(n, compareByDescending(selector)) } /** * Find [n] largest items from the sequence according to the provided key [selector]. * The result is returned in the sorted order starting from the largest item. */ fun <T> Sequence<T>.largestBy(n: Int, selector: (T) -> Comparable<*>): List<T> { return this.largestWith(n, compareBy(selector)) } /** * Finds [n] largest items from the sequence according to the provided [comparator] * The result is returned in the sorted order starting from the largest item. */ private fun <T> Sequence<T>.smallestWith(n: Int, comparator: Comparator<T>): List<T> { return this.largestWith(n, comparator.reversed()) } /** * Finds [n] largest items from the sequence according to the provided [comparator] * The result is returned in the sorted order starting from the largest item. */ private fun <T> Sequence<T>.largestWith(n: Int, comparator: Comparator<T>): List<T> { val heap: PriorityQueue<T> = PriorityQueue(comparator) val iterator = this.iterator() for (item in iterator) { heap.add(item) while (heap.size > n) { heap.remove() } } val result: ArrayList<T> = arrayListOf() while (heap.isNotEmpty()) { result.add(heap.remove()) } return result.asReversed() } /** * Splits the given iterator into multiple chunks * using the given predicate to determine the separator. * See also: [more_itertools.split_at](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_at) */ inline fun <T> Sequence<T>.splitAt(crossinline predicate: (T) -> Boolean): Sequence<List<T>> = this.iterator().let { iterator -> sequence { var accmList: ArrayList<T> = arrayListOf() for (item in iterator) { if (predicate(item)) { this.yield(accmList) accmList = arrayListOf() } else { accmList.add(item) } } if (accmList.isNotEmpty()) { this.yield(accmList) } } } /** * Splits the given iterator into multiple chunks * using the given predicate to determine the start of a new chunk. * See also: [more_itertools.split_before](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_before) */ inline fun <T> Sequence<T>.splitBefore(crossinline predicate: (T) -> Boolean): Sequence<List<T>> = this.iterator().let { iterator -> sequence { var accmList: ArrayList<T> = arrayListOf() for (item in iterator) { if (accmList.isNotEmpty() && predicate(item)) { this.yield(accmList) accmList = arrayListOf() } accmList.add(item) } if (accmList.isNotEmpty()) { this.yield(accmList) } } } /** * Make an iterator that returns accumulated results of binary functions. * See also: [itertools.accumulate](https://docs.python.org/3/library/itertools.html#itertools.accumulate) */ inline fun <T, R> Sequence<T>.accumulate( initial: R, includeInitial: Boolean = false, crossinline operation: (R, T) -> R ): Sequence<R> = this.iterator().let { iterator -> sequence { var accm: R = initial if (includeInitial) { this.yield(accm) } for (item in iterator) { accm = operation(accm, item) this.yield(accm) } } } /** * Make an iterator that returns accumulated results of binary functions. * See also: [itertools.accumulate](https://docs.python.org/3/library/itertools.html#itertools.accumulate) */ inline fun <T> Sequence<T>.accumulate(crossinline operation: (T, T) -> T): Sequence<T> = this.iterator().let { iterator -> return sequence { var accm: T? = null for (item in iterator) { accm = if (accm == null) { item } else { operation(accm, item) } this.yield(accm) } } }
0
Kotlin
0
0
8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb
5,336
aoc2022-kotlin
Apache License 2.0
src/Day01.kt
korsik
573,366,257
false
{"Kotlin": 5186}
fun main() { fun part1(input: List<String>): Int { val data = mutableListOf<Int>() var point = 0 data.add(0) for (num in input) { if (num == "") { point++ data.add(0) } else { data[point] += num.toInt() } } return data.max() } fun part2(input: List<String>): Int { val data = mutableListOf<Int>() var point = 0 data.add(0) for (num in input) { if (num == "") { point++ data.add(0) } else { data[point] += num.toInt() } } return data.sorted().reversed().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_default") println(part2(testInput)) // check(part1(testInput) == 1) val input = readInput("Day01_test") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1a576c51fc8233b1a2d64e44e9301c7f4f2b6b01
1,055
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DesignTicTacToe.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.abs /** * Design Tic-Tac-Toe * @see <a href="https://leetcode.com/problems/design-tic-tac-toe/">Source</a> */ fun interface DesignTicTacToe { fun move(row: Int, col: Int, player: Int): Int } /** * Time Complexity: O(n) * Space Complexity: O(n^2) */ class TTTOptimizedBruteForce(val n: Int) : DesignTicTacToe { private val board: Array<IntArray> = Array(n) { IntArray(n) } override fun move(row: Int, col: Int, player: Int): Int { board[row][col] = player // check if the player wins val rowOrColumn = checkRow(row, player) || checkColumn(col, player) || row == col && checkDiagonal(player) if (rowOrColumn || col == n - row - 1 && checkAntiDiagonal(player)) { return player } // No one wins return 0 } private fun checkDiagonal(player: Int): Boolean { for (row in 0 until n) { if (board[row][row] != player) { return false } } return true } private fun checkAntiDiagonal(player: Int): Boolean { for (row in 0 until n) { if (board[row][n - row - 1] != player) { return false } } return true } private fun checkColumn(col: Int, player: Int): Boolean { for (row in 0 until n) { if (board[row][col] != player) { return false } } return true } private fun checkRow(row: Int, player: Int): Boolean { for (col in 0 until n) { if (board[row][col] != player) { return false } } return true } } /** * Approach 2: Optimised Approach * Time Complexity: O(1) * Space Complexity: O(n) */ class TTTOptimised(val n: Int) : DesignTicTacToe { private var rows: IntArray = IntArray(n) private var cols: IntArray = IntArray(n) private var diagonal = 0 private var antiDiagonal = 0 override fun move(row: Int, col: Int, player: Int): Int { val currentPlayer = if (player == 1) 1 else -1 // update currentPlayer in rows and cols arrays rows[row] += currentPlayer cols[col] += currentPlayer // update diagonal if (row == col) { diagonal += currentPlayer } // update anti diagonal if (col == cols.size - row - 1) { antiDiagonal += currentPlayer } val n: Int = rows.size // check if the current player wins val rowsOrCols = abs(rows[row]) == n || abs(cols[col]) == n return if (rowsOrCols || abs(diagonal) == n || abs(antiDiagonal) == n) { player } else { 0 } // No one wins } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,416
kotlab
Apache License 2.0
src/Day14.kt
Tomcat88
572,566,485
false
{"Kotlin": 52372}
import kotlin.math.abs object Day14 { @JvmStatic fun main(args: Array<String>) { val input = downloadAndReadInput("Day14", "\n").filter { it.isNotBlank() }.map { it.split(" -> ").map { it.split(",").let { (x, y) -> Point(x.toInt(), y.toInt()) } } } val minX = input.flatten().minOf { it.x } - 350 val maxX = input.flatten().maxOf { it.x } + 200 val minY = 0 val maxY = input.flatten().maxOf { it.y } + 2 minX.log() maxX.log() val xLength = maxX - minX val yLength = maxY - minY val grid = (0..yLength).map { y -> (0..xLength).map { x -> Field.Empty as Field }.toMutableList() }.toMutableList() input.forEach { rockPath -> rockPath.map { Point(it.x - minX, it.y - minY) }.windowed(2).forEach { (start, end) -> grid[start.y][start.x] = Field.Rock if (start.x == end.x) { repeat(abs(start.y - end.y)) { i -> if (start.y < end.y) { grid[start.y + i + 1][start.x] = Field.Rock } else { grid[start.y - (i + 1)][start.x] = Field.Rock } } } else if (end.y == start.y) { repeat(abs(start.x - end.x)) { i -> if (start.x < end.x) { grid[start.y][start.x + i + 1] = Field.Rock } else { grid[start.y][start.x - (i + 1)] = Field.Rock } } } } } grid[grid.size - 1] = (0..xLength).map { x -> Field.Rock as Field }.toMutableList() var i = 0 var exit = false var part1 = false while (i < 30000 && !exit) { var s = Point(500 - minX, 0) var atRest = false while (!atRest) { when { !part1 && (s.y + 1 >= grid.size - 1 || s.x - 1 < 0) -> { part1 = true i.log("part1") } grid[s.y + 1][s.x] is Field.Empty -> { s = Point(s.x, s.y + 1) } grid[s.y + 1][s.x] is Field.NotEmpty && grid[s.y + 1][s.x - 1] is Field.Empty -> { s = Point(s.x - 1, s.y + 1) } grid[s.y + 1][s.x] is Field.NotEmpty && grid[s.y + 1][s.x + 1] is Field.Empty -> { s = Point(s.x + 1, s.y + 1) } else -> { atRest = true grid[s.y][s.x] = Field.Sand if (s.y == 0) { (i + 1).log("part2") exit = true break } } } } i++ } // plot(grid) } fun plot(grid: MutableList<MutableList<Field>>) { grid.forEachIndexed { x, row -> row.forEachIndexed { y, f -> when (f) { is Field.Empty -> "." is Field.Rock -> "#" is Field.Sand -> "o" }.let { print(it) } } println() } } data class Point(val x: Int, val y: Int) sealed interface Field { sealed interface NotEmpty : Field object Rock : NotEmpty object Sand : NotEmpty object Empty : Field } }
0
Kotlin
0
0
6d95882887128c322d46cbf975b283e4a985f74f
3,759
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day20/part2/Part2.kt
bagguley
329,976,670
false
null
package day20.part2 import day20.* import java.lang.StringBuilder fun main() { val tiles = load(data) val corners = findCorners(tiles) println(corners.map { it.number }.fold(1L, {a,i -> a * i} )) val edges = findEdges(tiles) val allEdges: MutableList<Tile> = mutableListOf() allEdges.addAll(corners) allEdges.addAll(edges) val tileMap: MutableMap<String,Tile> = mutableMapOf() val first = corners.first() allEdges.remove(first) tileMap["0,0"] = first // Rotate 0,0 to be correct val topLeft = tileMap["0,0"]!! while(true) { val cornerEdges = listOf(topLeft.left(), topLeft.top()) if (!matches(cornerEdges, allEdges)) break topLeft.rotate() } // Fill top row println("Fill top row") for (x in 1..11) { val leftTile = tileMap["${x-1},0"]!! val leftTileRightEdge = leftTile.right() val nextTile = allEdges.find { it.matches(leftTileRightEdge) }!! // Rotate it while(true) { val nextTileLeftEdge = nextTile.left() if (leftTileRightEdge == nextTileLeftEdge) break if (leftTileRightEdge == nextTileLeftEdge.reversed()) { nextTile.flip() break } nextTile.rotate() } tileMap["$x,0"] = nextTile allEdges.remove(nextTile) } // Fill remaining rows println("Fill remaining rows") val allTiles: MutableList<Tile> = tiles.toMutableList() allTiles.removeAll(tileMap.values) for (y in 1..11) { for (x in 0..11) { val aboveTile = tileMap["$x,${y - 1}"]!! val aboveTileBottomEdge = aboveTile.bottom() val nextTile = allTiles.find { aboveTile.matches(it) }!! // Rotate it while (true) { val nextTileTopEdge = nextTile.top() if (aboveTileBottomEdge == nextTileTopEdge) break if (aboveTileBottomEdge == nextTileTopEdge.reversed()) { nextTile.flip() } nextTile.rotate() } tileMap["$x,$y"] = nextTile allTiles.remove(nextTile) } } // Remove outer edges println("Remove outer edges") tileMap.values.forEach{it.removeEdges()} // Build picture println("Build picture") var picture = createPicture(tileMap) // Find monsters println("Find monsters") var c1 = 0 var r = 1 while (c1 == 0) { picture = if (r % 4 == 0) flip(picture) else rotate(picture) c1 = countMonsters(picture) r++ } val uniqueMonsterSquares = countMonstersSquares(picture).size val countOfHashes = picture.sumBy { it.count { it == '#' } } println("Monsters: $c1") println("Total #'s: $countOfHashes") println("Monster #: $uniqueMonsterSquares") println("Not affected #: " + (countOfHashes - uniqueMonsterSquares)) } fun load(data: List<String>): List<Tile> { return data.map { loadTile(it) } } fun loadTile(data: String): Tile { val lines = data.split("\n").filter { it.isNotEmpty() }.toMutableList() val first = lines.removeFirst() val tileNum = first.substring(5, 9).toInt() return Tile(tileNum, lines) } fun findCorners(tiles: List<Tile>): List<Tile> { val result:MutableList<Tile> = mutableListOf() for (tile in tiles) { val otherTiles = tiles.filter { it != tile } val otherEdges = otherTiles.flatMap { it.edges() } val edges = tile.edges() val matchingEdges = edges.filterNot { otherEdges.contains(it) || otherEdges.contains(it.reversed()) } if (matchingEdges.size == 2) { result.add(tile) } } return result } fun findEdges(tiles: List<Tile>): List<Tile> { val result:MutableList<Tile> = mutableListOf() for (tile in tiles) { val otherTiles = tiles.filter { it != tile } val otherEdges = otherTiles.flatMap { it.edges() } val edges = tile.edges() val matchingEdges = edges.filterNot { otherEdges.contains(it) || otherEdges.contains(it.reversed()) } if (matchingEdges.size == 1) { result.add(tile) } } return result } fun matches(edges: List<String>, tile: List<Tile>): Boolean { val otherEdges = tile.flatMap { it.edges() } val matchingEdges = edges.filter { otherEdges.contains(it) } return matchingEdges.isNotEmpty() } fun createPicture(tileMap: MutableMap<String, Tile>): List<String> { val picture: MutableList<String> = mutableListOf() for (y in 0..11) { for (yy in 0..7) { val sb = StringBuilder() for (x in 0..11) { sb.append(tileMap["$x,$y"]!!.row(yy)) } picture.add(sb.toString()) } } return picture } fun countMonsters(picture: List<String>): Int { var count = 0 val pictureWidth = picture[0].length val pictureHeight = picture.size for (y in 0 until pictureHeight - monsterHeight) { for (x in 0 until pictureWidth - monsterWidth) { val section = grabSection(picture, x, y) if (checkMonster(section)) count++ } } return count } fun countMonstersSquares(picture: List<String>): Set<String> { val squareSet: MutableSet<String> = mutableSetOf() var count = 0L val pictureWidth = picture[0].length val pictureHeight = picture.size for (y in 0 until pictureHeight - monsterHeight) { for (x in 0 until pictureWidth - monsterWidth) { val section = grabSection(picture, x, y) if (checkMonster(section)) { count++ squareSet.addAll(monsterCoords.map { "${it.first+x},${it.second+y}" }) } } } return squareSet } fun grabSection(picture: List<String>, x: Int, y: Int): List<String> { val section: MutableList<String> = mutableListOf() for (yy in y until y + monsterHeight) { section.add(picture[yy].substring(x, x + monsterWidth)) } return section } fun checkMonster(section: List<String>): Boolean { return monsterCoords.all { section[it.second][it.first] == '#' } } fun rotate(picture: List<String>): List<String> { val newPicture = picture.toMutableList() for (x in 0 until 96) { val sb = StringBuilder() for (y in 95 downTo 0) { sb.append(picture[y][x]) } newPicture[x] = sb.toString() } return newPicture } fun flip(picture: List<String>): List<String> { return picture.reversed() }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
6,604
adventofcode2020
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day9/Day9.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day9 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.permutations import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 9](https://adventofcode.com/2015/day/9) */ object Day9 : DayOf2015(9) { private val PATTERN = "^\\b(\\w*)\\b to \\b(\\w*)\\b = (\\d*)$".toRegex() private val EDGES = lines .flatMap { line -> PATTERN.matchEntire(line)?.let { match -> val (city1, city2, distance) = match.destructured return@let listOf( Pair(city1, city2) to distance.toInt(), Pair(city2, city1) to distance.toInt(), ) }.orEmpty() } .toMap() private val CITIES = EDGES.keys.flatMap { listOf(it.first, it.second) }.distinct() override fun first(): Any? { return CITIES.permutations() .minOf { city -> city .zipWithNext() .sumOf { EDGES[it] ?: 0 } } } override fun second(): Any? { return CITIES.permutations() .maxOf { city -> city .zipWithNext() .sumOf { EDGES[it] ?: 0 } } } } fun main() = SomeDay.mainify(Day9)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,136
adventofcode
MIT License
src/main/kotlin/aoc/utils/Collections.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package aoc.utils fun <T> List<T>.splitMiddle(): Pair<List<T>,List<T>> { if(size % 2 != 0) throw Error("Cannot split middle list of size $size") return Pair(subList(0,size/2),subList(size/2,size)) } fun <E> List<E>.getLooping(index: Int): E { if(index < 0) { return this[(index+(-1 * index / size + 1)*size)%size] } else { return this[index % size] } } /** * Ceaser cipher i.e. simple substition mapping * A,B (this list, i.e the plain values) * X,Y (cipher list) * listOf("A","B").decode("X", listOf("X","Y")) -> "A" */ fun <E,C> List<E>.decode(element: C, cipher: List<C>): E = this[cipher.indexOf(element)] fun <E,C> List<E>.encode(element: E, cipher: List<C>): C = cipher[this.indexOf(element)] /** * Optimization tool * Container storing key/value pairs providing fast value access and ordered by value */ class SortedLookup<K, V : Comparable<V>> { private val valueLookup = mutableMapOf<K, V>() private val sortedByValue = sortedSetOf<Pair<K, V>>(Comparator<Pair<K, V>> { o1, o2 -> o1.second.compareTo(o2.second) }.thenComparing { o1, o2 -> o1.first.hashCode().compareTo(o2.first.hashCode()) }) fun add(key: K, value: V) { valueLookup[key] = value sortedByValue.add(Pair(key, value)) } fun drop(key: K): Pair<K, V> { valueLookup.remove(key) val toRemove = sortedByValue.first { it.first == key } sortedByValue.remove(toRemove) return toRemove } fun containsKey(key: K) = valueLookup.contains(key) fun get(key: K) = valueLookup[key] fun sortedByValue() = sortedByValue.asSequence() fun size() = valueLookup.size }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
1,689
adventOfCode2022
Apache License 2.0
src/Day06.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
fun main() { fun solvePart1(s: String): Int { for (i in 4 until s.length) { if (s.substring(i - 4, i).toSet().size == 4) { return i } } return -1 } fun solvePart2(s: String): Int { val chars = MutableList<Int>(26) { 0 } // unique chars in the current window var window = 0 for (i in s.indices) { if (chars[s[i] - 'a'] == 0) { window += 1 } chars[s[i] - 'a'] += 1 if (i >= 14) { chars[s[i - 14] - 'a'] -= 1 if (chars[s[i - 14] - 'a'] == 0) { window -= 1 } } if (window == 14) { return i + 1 } } return -1 } // last sample input val testInput = readInput("input/Day06_test")[0] check(solvePart1(testInput) == 11) check(solvePart2(testInput) == 26) val input = readInput("input/Day06_input")[0] println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
1,093
AoC-2022-kotlin
Apache License 2.0
advent-of-code-2023/src/main/kotlin/Day01.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 1: Trebuchet?! // https://adventofcode.com/2023/day/1 import java.io.File private val digits = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") fun main() { val lines = File("src/main/resources/Day01.txt").readLines() val sum1 = lines.sumOf { line -> line.first { it.isDigit() }.digitToInt() * 10 + line.last { it.isDigit() }.digitToInt() } println(sum1) val sum2 = lines.sumOf { line -> getFirstDigit(line) * 10 + getLastDigit(line) } println(sum2) } private fun getFirstDigit(line: String): Int { var temp = line line.toList().map { it.toString() }.runningReduce { acc, string -> acc + string }.forEach { val stringToReplace = stringToReplace(it) if (stringToReplace.isNotEmpty()) { temp = temp.replace(stringToReplace, digits.indexOf(stringToReplace).toString()) } } return temp.first { it.isDigit() }.digitToInt() } private fun getLastDigit(line: String): Int { var temp = line line.reversed().toList().map { it.toString() }.runningReduce { acc, string -> acc + string }.forEach { val stringToReplace = stringToReplace(it.reversed()) if (stringToReplace.isNotEmpty()) { temp = temp.replace(stringToReplace, digits.indexOf(stringToReplace).toString()) } } return temp.last { it.isDigit() }.digitToInt() } private fun stringToReplace(line: String): String { digits.forEachIndexed { _, digit -> if (line.contains(digit)) { return digit } } return "" }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
1,593
advent-of-code
Apache License 2.0
jtransc-core/src/com/jtransc/graph/LCA.kt
jtransc
51,313,992
false
null
package com.jtransc.graph // https://en.wikipedia.org/wiki/Lowest_common_ancestor class LCATree(val capacity: Int) { val parents: IntArray = IntArray(capacity) val depths: IntArray = IntArray(capacity) private var current: Int = 1 val Int.parent:Int get() = parents[this] val Int.depth:Int get() = depths[this] fun create(parent: Int): Int { parents[current] = parent depths[current] = depths[parent] + 1 return current++ } fun lca(items: Iterable<Int>): Int = items.reduce { a, b -> lca(a, b) } fun lca(a: Int, b: Int): Int { var (l, r) = if (a.depth < b.depth) Pair(a, b) else Pair(b, a) while (true) { if (l == r) return a while (l.depth > r.depth) l = l.parent while (r.depth > l.depth) r = r.parent } } } // https://en.wikipedia.org/wiki/Lowest_common_ancestor#Extension_to_directed_acyclic_graphs /* fun <T> AcyclicDigraph<T>.lca(items:Iterable<Int>):Int = items.reduce { a, b -> lca(a, b) } fun <T> AcyclicDigraph<T>.lca(a:Int, b:Int):Int { } */
59
Java
66
619
6f9a2166f128c2ce5fb66f9af46fdbdbcbbe4ba4
992
jtransc
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PancakeSortLeetcode.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 object PancakeSortLeetcode { fun pancakeSort(arr: IntArray): List<Int> { val ans: MutableList<Int> = ArrayList() for (valueToSort in arr.size downTo 1) { // locate the position for the value to sort in this round val index = this.find(arr, valueToSort) // sink the value_to_sort to the bottom, // with at most two steps of pancake flipping. if (index == valueToSort - 1) continue // 1). flip the value to the head if necessary if (index != 0) { ans.add(index + 1) flip(arr, index + 1) } // 2). now that the value is at the head, flip it to the bottom ans.add(valueToSort) flip(arr, valueToSort) } return ans } private fun flip(sublist: IntArray, k: Int) { var i = 0 while (i < k / 2) { val temp = sublist[i] sublist[i] = sublist[k - i - 1] sublist[k - i - 1] = temp i += 1 } } private fun find(a: IntArray, target: Int): Int { for (i in a.indices) if (a[i] == target) return i return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,846
kotlab
Apache License 2.0
tonilopezmr/day6/MemoryBank.kt
CloudCoders
112,667,277
false
{"Mathematica": 37090, "Python": 36924, "Scala": 26540, "Kotlin": 24988, "Ruby": 5084, "Java": 4495, "JavaScript": 3440, "MATLAB": 3013}
package day6 import kategory.combine import org.junit.Assert.assertEquals import org.junit.Test typealias P = Pair<Int, Int> class MemoryBank { private fun chooseBank(input: List<Int>): Pair<Int, Int> = input.foldRightIndexed(P(0, 0)) { idx, bank, (index, blocks) -> if (bank >= blocks) P(idx, bank) else P(index, blocks) } private fun balance(input: List<Int>): List<Int> { var (index, bank) = chooseBank(input) val distribution = if (bank < input.size) bank else input.size - 1 val blocksForEach = bank / distribution val list = input.toMutableList() val displacement = blocksForEach * distribution list[index] = bank - displacement index++ for (i in 1..distribution) { index %= input.size list[index] = list[index] + blocksForEach index++ } return list } private fun infiniteLoopCircleInI(input: List<Int>): Int { val history = mutableListOf<List<Int>>() var banks = input var count = 0 while (!history.contains(banks)) { history.add(banks) banks = balance(banks) count++ } return count } tailrec private fun infiniteLoopCircleIn(input: List<Int>, history: List<List<Int>> = emptyList(), count: Int = 0): Int = if (history.contains(input)) count else { val newInput = balance(input) infiniteLoopCircleIn(newInput, history.toMutableList().apply { add(input) }, count + 1) } @Test fun `choose the bank with more blocks`() { val (index, bank) = chooseBank(listOf(1, 2, 3, 7)) assertEquals(3, index) assertEquals(7, bank) } @Test fun `choose the first bank with more blocks when there is a tie`() { val (index, bank) = chooseBank(listOf(1, 7, 3, 7)) assertEquals(1, index) assertEquals(7, bank) } @Test fun `balance blocks in banks`() { val input = listOf(0, 2, 7, 0) assertEquals(listOf(2, 4, 1, 2), balance(input)) } @Test fun `balance blocks in banks iteration 2`() { val input = listOf(2, 4, 1, 2) assertEquals(listOf(3, 1, 2, 3), balance(input)) } @Test fun `balance blocks in banks when there is a tie`() { val input = listOf(3, 1, 2, 3) assertEquals(listOf(0, 2, 3, 4), balance(input)) } @Test fun `balance blocks in banks iteration 4`() { val input = listOf(1, 3, 4, 1) assertEquals(listOf(2, 4, 1, 2), balance(input)) } @Test fun `detect infinite loop circle in blocks redistribution`() { val input = listOf(0, 2, 7, 0) assertEquals(5, infiniteLoopCircleIn(input)) } @Test fun `the result of the infinite loop circle is`() { val input = listOf(0, 5, 10, 0, 11, 14, 13, 4, 11, 8, 8, 7, 1, 4, 12, 11) assertEquals(7864, infiniteLoopCircleIn(input)) } }
2
Mathematica
0
8
5a52d1e89076eccb55686e4af5848de289309813
2,763
AdventOfCode2017
MIT License
src/main/kotlin/org/flightofstairs/kpd/TreeMap.kt
FlightOfStairs
229,950,208
false
null
package org.flightofstairs.kpd import org.flightofstairs.kpd.utils.maybeUpdate import kotlin.math.sign private class TreeMapNode<K, V>( private val entry: Map.Entry<K, V>, private val comparator: Comparator<K>, private val left: TreeMapNode<K, V>?, private val right: TreeMapNode<K, V>? ) { constructor(entry: Map.Entry<K, V>, comparator: Comparator<K>) : this(entry, comparator, null, null) val size: Int = (left?.size ?: 0) + (right?.size ?: 0) + 1 operator fun get(key: K): Map.Entry<K, V>? = when (comparator.compare(key, entry.key).sign) { -1 -> left?.get(key) 1 -> right?.get(key) else -> entry } fun set(newEntry: Map.Entry<K, V>): TreeMapNode<K, V> = when (comparator.compare(newEntry.key, entry.key).sign) { -1 -> addLeft(newEntry) 1 -> addRight(newEntry) else -> if (newEntry.value === entry.value) this else TreeMapNode(newEntry, comparator, left, right) } private fun addLeft(newEntry: Map.Entry<K, V>): TreeMapNode<K, V> { if (left == null) return TreeMapNode(this.entry, comparator, TreeMapNode(newEntry, comparator), right) return left.maybeUpdate { it.set(newEntry) }?.let { TreeMapNode(this.entry, comparator, it, right) } ?: this } private fun addRight(newEntry: Map.Entry<K, V>): TreeMapNode<K, V> { if (right == null) return TreeMapNode(this.entry, comparator, left, TreeMapNode(newEntry, comparator)) return right.maybeUpdate { it.set(newEntry) }?.let { TreeMapNode(this.entry, comparator, left, it) } ?: this } fun sequence(): Sequence<Map.Entry<K, V>> = sequence { if (left != null) yieldAll(left.sequence()) yield(entry) if (right != null) yieldAll(right.sequence()) } } class TreeMap<K, V> private constructor( private val root: TreeMapNode<K, V>?, private val comparator: Comparator<K> ) : Map<K, V> { constructor(comparator: Comparator<K>) : this(null, comparator) override fun get(key: K): V? = root?.get(key)?.value override fun set(key: K, value: V): TreeMap<K, V> { val entry = Map.Entry(key, value) return if (root == null) { TreeMap(TreeMapNode(entry, comparator), comparator) } else root.maybeUpdate { it.set(entry) } ?.let { TreeMap(it, comparator) } ?: this } override val size: Int = root?.size ?: 0 override fun contains(key: K): Boolean = root?.get(key) != null override fun iterator(): Iterator<Map.Entry<K, V>> = root?.sequence()?.iterator() ?: emptySequence<Map.Entry<K, V>>().iterator() }
0
Kotlin
0
0
c5e61094a6f398f3ddce6d84f5284588cc21d37d
2,609
kotlin-persistent-datastructures
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/BinaryTreePaths.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue import java.util.Stack private const val FORMAT = "%s%s%s" private const val ARROW = "->" fun interface BinaryTreePathsStrategy { fun binaryTreePaths(root: TreeNode?): List<String> } class BinaryTreePathsRecursion : BinaryTreePathsStrategy { override fun binaryTreePaths(root: TreeNode?): List<String> { val sList: MutableList<String> = LinkedList() if (root == null) return sList if (root.left == null && root.right == null) { sList.add(root.value.toString()) return sList } for (s in binaryTreePaths(root.left)) { sList.add(String.format(FORMAT, root.value.toString(), ARROW, s)) } for (s in binaryTreePaths(root.right)) { sList.add(String.format(FORMAT, root.value.toString(), ARROW, s)) } return sList } } class BinaryTreePathsBFSQueue : BinaryTreePathsStrategy { override fun binaryTreePaths(root: TreeNode?): List<String> { val list: MutableList<String> = ArrayList() val qNode: Queue<TreeNode> = LinkedList() val qStr: Queue<String> = LinkedList() if (root == null) return list qNode.add(root) qStr.add("") while (qNode.isNotEmpty()) { val curNode: TreeNode = qNode.remove() val curStr: String = qStr.remove() if (curNode.left == null && curNode.right == null) list.add(curStr + curNode.value) if (curNode.left != null) { qNode.add(curNode.left) qStr.add(String.format(FORMAT, curStr, curNode.value.toString(), ARROW)) } if (curNode.right != null) { qNode.add(curNode.right) qStr.add(String.format(FORMAT, curStr, curNode.value.toString(), ARROW)) } } return list } } class BinaryTreePathsBFSStack : BinaryTreePathsStrategy { override fun binaryTreePaths(root: TreeNode?): List<String> { val list: MutableList<String> = ArrayList() val sNode: Stack<TreeNode> = Stack<TreeNode>() val sStr: Stack<String> = Stack<String>() if (root == null) return list sNode.push(root) sStr.push("") while (sNode.isNotEmpty()) { val curNode: TreeNode = sNode.pop() val curStr: String = sStr.pop() if (curNode.left == null && curNode.right == null) list.add(curStr + curNode.value) if (curNode.left != null) { sNode.push(curNode.left) sStr.push(String.format(FORMAT, curStr, curNode.value.toString(), ARROW)) } if (curNode.right != null) { sNode.push(curNode.right) sStr.push(String.format(FORMAT, curStr, curNode.value.toString(), ARROW)) } } return list } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,536
kotlab
Apache License 2.0
src/main/kotlin/dev/claudio/adventofcode2021/Day4Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 fun main() { Day4Part2().main() } private class Day4Part2 { fun main() { val inputList: List<String> = Support.readFileAsListString("day4-input.txt").filter { it != "" } val marks: List<Int> = inputList[0].split(",").map { Integer.valueOf(it) } var start = 1 val boards = mutableListOf<Board>() while(start < inputList.size) { val boardList = (0 until 5).map { inputList[start + it].split(" ").filter { it2 -> it2 != "" }.map { it2 -> Integer.valueOf(it2) } } boards.add(Board(boardList)) start += 5 } var lastWinner: Int? = null var lastMark: Int? = null marks.forEach{ mark -> boards.forEach{ board -> board.hit(mark) } val winners = boards.filter { it.isWin() } winners.forEach { winner -> lastMark = mark lastWinner = winner.winLossNumbers().second.sum() boards.remove(winner) } } println(lastWinner!! * lastMark!!) } data class Board( val board: List<List<Int>>, private var marks: MutableList<Int> = mutableListOf(), ) { fun hit(number: Int) { marks.add(number) } fun isWin(): Boolean { (board.indices).forEach { index -> val horiz = board[index].all { marks.contains(it) } val vert = board[index].indices.map { index2 -> board[index2][index] }.all { marks.contains(it) } if (horiz || vert) return true } return false } fun winLossNumbers(): Pair<List<Int>, List<Int>> { val allNumbers: List<Int> = board.flatten() return Pair(allNumbers.filter { marks.contains(it) }, allNumbers.filterNot { marks.contains(it) }) } } }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
1,976
adventofcode-2021
Apache License 2.0
src/main/java/com/booknara/practice/kotlin/higherorderfunction/Groceries.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.practice.kotlin.higherorderfunction data class Grocery( val name: String, val category: String, val unit: String, val unitPrice: Double, val quantity: Int) fun main(args: Array<String>) { val groceries = listOf<Grocery>( Grocery("Tomatoes", "Vegetable", "lb", 3.0, 3), Grocery("Mushroom", "Vegetable", "lb", 4.0, 1), Grocery("Bagels", "Bakery", "Pack", 1.5, 2), Grocery("Olive oil", "Pantry", "Bottle", 6.0, 1), Grocery("Ice cream", "Frozen", "Pack", 3.0, 2) ) val highestUnitPrice = groceries.maxBy { it.unitPrice * 5 } println("highestUnitPrice: $highestUnitPrice") val lowestQuantity = groceries.minBy { it.quantity } println("lowestQuantity: $lowestQuantity") val sumQuantity = groceries.sumBy { it.quantity } println("sumQuantity: $sumQuantity") val totalPrice = groceries.sumByDouble { it.unitPrice * it.quantity } println("totalPrice: $totalPrice") val vegetables = groceries.filter { it.category == "Vegetable" } val unitPriceOver3 = groceries.filter { it.unitPrice > 3.0 } val nonFrozen = groceries.filterNot { it.category != "Frozen" } val groceryNames = groceries.map { it.name } val halfUnitPrice = groceries.map { it.unitPrice * 0.5 } val newPrices = groceries.filter { it.unitPrice > 3.0 } .map { it.unitPrice * 2 } for (item in groceries) { println(item.name) } groceries.forEach { println(it.name) } for (item in groceries) { if (item.unitPrice > 3.0) println(item.name) } groceries.filter { it.unitPrice > 3.0 } .forEach { println(it.name) } var itemNames = "" for (item in groceries) { itemNames += "${item.name} " } println("itemNames: $itemNames ") itemNames = "" groceries.forEach { itemNames += "${it.name} " } println("itemNames: $itemNames ") val groupBycategory = groceries.groupBy { it.category } // println(groupBycategory) groceries.groupBy { it.category }.forEach { println(it.key) it.value.forEach { println(" ${it.name}") } } val ints = listOf<Int>(1, 2, 3) val sumOfInts = ints.fold(0) { runningSum, item -> runningSum + item } println("sumOfInts: $sumOfInts") println(sumOfInts.javaClass.kotlin.simpleName) val productOfInts = ints.fold(1) { runningSum, item -> runningSum * item } println("productOfInts: $productOfInts") val names = groceries.fold("") { string, item -> string + " ${item.name}" } println("names: $names") val changeFrom50 = groceries.fold(50.0) { change, item -> change - item.unitPrice * item.quantity } println("changeFrom50: $changeFrom50") }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
2,820
playground
MIT License
src/2021/Day12_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import java.util.LinkedList import java.util.Queue class UndirectedGraph { private val graph = hashMapOf<String, MutableList<String>>() private fun addVertex(vertex: String) { graph[vertex] = LinkedList<String>() } fun addEdge(source: String, destination: String) { if (!graph.containsKey(source)) addVertex(source) if (destination != "end") { if (!graph.containsKey(destination)) addVertex(destination) } graph[source]?.add(destination) if (source != "start") { graph[destination]?.add(source) } } fun get(key: String): List<String> = graph[key]!! fun getTotalPathUsingBFS(source: String, destination: String): Int { val queue: Queue<List<String>> = LinkedList() val paths: MutableList<List<String>> = mutableListOf() get(source).forEach { queue.add(listOf(source, it)) } val addInPath: (List<String>, String) -> Unit = { frontElement, vertex -> paths.add(mutableListOf<String>().also { it.addAll(frontElement) it.add(vertex) }) } val addInQueue: (List<String>, String) -> Unit = { frontElement, vertex -> queue.add(mutableListOf<String>().also { it.addAll(frontElement) it.add(vertex) }) } while (queue.isNotEmpty()) { val frontElement = queue.remove() get(frontElement.last()).forEach { vertex -> if (vertex == destination) { addInPath(frontElement, vertex) } else { if (vertex[0].isLowerCase()) { if (!frontElement.contains(vertex)) { addInQueue(frontElement, vertex) } else { frontElement.filter { it[0].isLowerCase() } .let { list -> val (matching, others) = list.partition { it == vertex } if (matching.count() == 1 && others.groupingBy { it }.eachCount().filter { it.value > 1 }.count() == 0 ) { addInQueue(frontElement, vertex) } } } } else { addInQueue(frontElement, vertex) } } } } return paths.size } } val graph = UndirectedGraph() File("input/2021/day12").forEachLine { line -> val (source, destination) = line.split("-").map { it.trim() } if (source == "end" || destination == "start") { graph.addEdge(destination, source) } else { graph.addEdge(source, destination) } } val result = graph.getTotalPathUsingBFS("start", "end") println(result)
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
3,030
adventofcode
MIT License
src/iii_conventions/MyDate.kt
mariusz-zawadzki
99,572,209
true
{"Kotlin": 73383, "Java": 4953}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { val compareList = listOf(year.compareTo(other.year), month.compareTo(other.month), dayOfMonth.compareTo(other.dayOfMonth)) val firstOrNull = compareList.filter { it != 0 }.firstOrNull() return if (firstOrNull != null) firstOrNull else 0; } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(interval: TimeInterval) = addTimeIntervals(interval, 1) operator fun MyDate.plus(interval: MultipleTimeInterval) = addTimeIntervals(interval.interval, interval.times) data class MultipleTimeInterval(val interval: TimeInterval, val times: Int) operator fun TimeInterval.times(times: Int) = MultipleTimeInterval(this, times) enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(val start: MyDate, val endInclusive: MyDate){ operator fun contains(myDate: MyDate): Boolean = (start <= myDate) && (myDate <= endInclusive) } class MyDateRangeIterator(val range: DateRange) : Iterator<MyDate>{ var currentDate: MyDate= range.start; override fun hasNext(): Boolean { return currentDate <= range.endInclusive; } override fun next(): MyDate { val returnDate = currentDate currentDate = currentDate.nextDay() return returnDate; } } operator fun DateRange.iterator() : Iterator<MyDate> = MyDateRangeIterator(this)
0
Kotlin
0
0
dd14ec8c516f36d29fc74db29875d8cb476f74db
1,564
kotlin-koans
MIT License
kotlin/src/com/daily/algothrim/graph/TopologySort.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.graph import java.util.* /** * 拓扑排序 */ class TopologySort(private val v: Int) { companion object { @JvmStatic fun main(args: Array<String>) { TopologySort(4).apply { addEdge(0, 1) addEdge(0, 2) addEdge(0, 3) addEdge(1, 2) addEdge(1, 3) addEdge(2, 3) topologySortByKahn() println() topologySortByDFS() } } } private val adj = Array(v) { LinkedList<Int>() } fun addEdge(s: Int, t: Int) { // s优先于t执行,t依赖于s adj[s].add(t) } /** * 卡恩 * O(V+E) */ fun topologySortByKahn() { val inDegree = IntArray(v) var i = 0 // t依赖于s,s的入度+1 // 统计入度 while (i < v) { var j = 0 while (j < adj[i].size) { val w = adj[i][j] inDegree[w]++ j++ } i++ } val queue = LinkedList<Int>() var k = 0 while (k < v) { // 初始化入度为0的进入队列 if (inDegree[k] == 0) queue.offer(k) k++ } // 遍历消除入度为零的节点 while (queue.isNotEmpty()) { val n = queue.pop() print("->$n") var m = 0 while (m < adj[n].size) { val w = adj[n][m] // 依赖当前入度为零的节点,对应的入度减1 inDegree[w]-- // 入度为0入队 if (inDegree[w] == 0) queue.offer(w) m++ } } } /** * 深度优先搜索 * O(V+E) */ fun topologySortByDFS() { val reverseAdj = Array(v) { LinkedList<Int>() } var i = 0 while (i < v) { var j = 0 while (j < adj[i].size) { val w = adj[i][j] // 生成逆邻接表,对应w依赖于i reverseAdj[w].add(i) j++ } i++ } var k = 0 val visited = BooleanArray(v) while (k < v) { if (!visited[k]) { visited[k] = true // 递归寻找k依赖的节点 recurDFS(k, visited, reverseAdj) } k++ } } private fun recurDFS(k: Int, visited: BooleanArray, reverseAdj: Array<LinkedList<Int>>) { var m = 0 while (m < reverseAdj[k].size) { val w = reverseAdj[k][m] if (!visited[w]) { visited[w] = true recurDFS(w, visited, reverseAdj) } m++ } print("->$k") } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,889
daily_algorithm
Apache License 2.0
lib/src/main/kotlin/aoc/day03/Day03.kt
Denaun
636,769,784
false
null
package aoc.day03 import aoc.AocGrammar import com.github.h0tk3y.betterParse.combinators.use import com.github.h0tk3y.betterParse.grammar.parseToEnd import com.github.h0tk3y.betterParse.lexer.regexToken import com.google.common.collect.Iterables.getOnlyElement object Day03Grammar : AocGrammar<List<String>>() { private val rucksackToken by regexToken("[a-zA-Z]+") private val rucksack by rucksackToken use { text } override val rootParser by lineList(rucksack) } fun parse(data: String): List<String> = Day03Grammar.parseToEnd(data) fun Char.priority(): Int { require(this in ('a'..'z') + ('A'..'Z')) if (this in 'a'..'z') { return this.dec() - 'a'.dec() + 1 } if (this in 'A'..'Z') { return this.dec() - 'A'.dec() + 27 } throw IllegalStateException() } fun misplacedItem(rucksack: String): Char { require(rucksack.length % 2 == 0) val mid = rucksack.length / 2 val firstCompartment = rucksack.subSequence(0, mid).toSet() val secondCompartment = rucksack.subSequence(mid, rucksack.length).toSet() return getOnlyElement(firstCompartment.intersect(secondCompartment)) } fun badge(group: List<String>): Char { require(group.size % 3 == 0) return getOnlyElement(group.map(String::toSet).reduce(Set<Char>::intersect)) } fun part1(input: String): Int = parse(input).sumOf { misplacedItem(it).priority() } fun part2(input: String): Int = parse(input).chunked(3).sumOf { badge(it).priority() }
0
Kotlin
0
0
560f6e33f8ca46e631879297fadc0bc884ac5620
1,476
aoc-2022
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2022/Day13.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2022 import com.github.davio.aoc.general.* import kotlinx.serialization.json.* import kotlin.system.measureTimeMillis fun main() { println(Day13.getResultPart1()) measureTimeMillis { println(Day13.getResultPart2()) }.call { println("Took $it ms") } } /** * See [Advent of Code 2022 Day 13](https://adventofcode.com/2022/day/13#part2]) */ object Day13 : Day() { sealed interface Packet : Comparable<Packet> @JvmInline value class PacketValue(private val i: Int) : Packet { override fun compareTo(other: Packet) = if (other is PacketValue) { this.i.compareTo(other.i) } else { PacketList(mutableListOf(this)).compareTo(other) } override fun toString() = i.toString() } @JvmInline value class PacketList(val packets: List<Packet>) : Packet { override fun compareTo(other: Packet): Int { if (other is PacketValue) { return this.compareTo(PacketList(mutableListOf(other))) } else { other as PacketList this.packets.indices.forEach { index -> if (index > other.packets.lastIndex) { return 1 } val comparison = this.packets[index].compareTo(other.packets[index]) if (comparison != 0) return comparison } if (this.packets.size < other.packets.size) { return -1 } return 0 } } override fun toString() = "[${packets.joinToString(",")}]" } fun getResultPart1() = getInputAsList() .split { it.isBlank() } .map { parsePacketPair(it) } .withIndex() .sumOf { (index, pair) -> val left = pair.first val right = pair.second if (left <= right) index + 1 else 0 } fun getResultPart2(): Int { val divider1 = parsePacket("[[2]]") val divider2 = parsePacket("[[6]]") return getInputAsSequence() .filter(String::isNotBlank) .map { parsePacket(it) } .plus(sequenceOf(divider1, divider2)) .sorted() .mapIndexedNotNull { index, packet -> if (packet == divider1 || packet == divider2) index + 1 else null } .reduce(Int::times) } private fun parsePacketPair(packetLines: List<String>): Pair<Packet, Packet> = Pair(parsePacket(packetLines[0]), parsePacket(packetLines[1])) private fun parsePacket(line: String) = parseJson(Json.decodeFromString<JsonArray>(line)) private fun parseJson(jsonElement: JsonElement) : Packet { return when (jsonElement) { is JsonArray -> PacketList(jsonElement.map { parseJson(it) }) is JsonPrimitive -> PacketValue(jsonElement.int) else -> throw IllegalStateException() } } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
3,050
advent-of-code
MIT License
src/day-9/part-1/solution-day-9-part-1.kts
d3ns0n
572,960,768
false
{"Kotlin": 31665}
import java.io.File import kotlin.math.abs class Coordinate(val x: Int = 0, val y: Int = 0) { fun moveRight() = Coordinate(x + 1, y) fun moveLeft() = Coordinate(x - 1, y) fun moveUp() = Coordinate(x, y + 1) fun moveDown() = Coordinate(x, y - 1) fun isTouching(other: Coordinate) = abs(x - other.x) <= 1 && abs(y - other.y) <= 1 override fun equals(other: Any?): Boolean { return other is Coordinate && x == other.x && y == other.y } override fun hashCode(): Int { var result = x result = 31 * result + y return result } } var headLog: MutableList<Coordinate> = mutableListOf(Coordinate()) var tailLog: MutableList<Coordinate> = mutableListOf(Coordinate()) fun moveHead(direction: String, distance: Int) { for (i in 1..distance) { when (direction) { "R" -> headLog.add(headLog.last().moveRight()) "L" -> headLog.add(headLog.last().moveLeft()) "U" -> headLog.add(headLog.last().moveUp()) "D" -> headLog.add(headLog.last().moveDown()) } moveTailIfNecessary() } } fun moveTailIfNecessary() { val tail = tailLog.last() val head = headLog.last() if (!tail.isTouching(head)) { var tempTail = tail if (head.x != tail.x) { tempTail = if (head.x - tail.x > 0) tempTail.moveRight() else tempTail.moveLeft() } if (head.y != tail.y) { tempTail = if (head.y - tail.y > 0) tempTail.moveUp() else tempTail.moveDown() } tailLog.add(tempTail) } else { tailLog.add(tail) } } fun process(line: String) { val (direction, distance) = line.split(" ", limit = 2) moveHead(direction, distance.toInt()) } File("../input.txt").readLines() .forEach { process(it) } val tailLogDistinctSize = tailLog.distinct().size println(tailLogDistinctSize) assert(tailLogDistinctSize == 6339)
0
Kotlin
0
0
8e8851403a44af233d00a53b03cf45c72f252045
1,923
advent-of-code-22
MIT License
src/questions/MaxSubarray.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertAllWithArgs /** * Given an integer array nums, find the contiguous subarray (containing at least one number) * which has the largest sum and return its sum. * [Source](https://leetcode.com/problems/maximum-subarray/) – [Solution](https://leetcode.com/problems/maximum-subarray/discuss/20396/Easy-Python-Way) */ @UseCommentAsDocumentation private fun maxSubArray(nums: IntArray): Int { for (i in 1..nums.lastIndex) { if (nums[i - 1] > 0) { // if previous sum is -ve, then no use for it so keep the ith index as it is i.e. discard the prev sums nums[i] += nums[i - 1] // mutate with sum of positives } } return nums.maxOrNull()!! } private fun maxSubArrayII(nums: IntArray): Int { var best = 0 var sum = 0 for (i in 0..nums.lastIndex) { sum = maxOf(nums[i], nums[i] + sum) best = maxOf(best, sum) } return best } private fun maxSubArrayIII(nums: IntArray): Int { var best = 0 for (i in 0..nums.lastIndex) { var sum = 0 for (j in i..nums.lastIndex) { sum += nums[j] best = maxOf(best, sum) } } return best } fun main() { assertAllWithArgs( 6, argsProducer = { intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4) }, ::maxSubArray, ::maxSubArrayII, ::maxSubArrayIII ) assertAllWithArgs( 23, argsProducer = { intArrayOf(5, 4, -1, 7, 8) }, ::maxSubArray, ::maxSubArrayII, ::maxSubArrayIII ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,600
algorithms
MIT License
src/main/kotlin/kgp/fitness/Metric.kt
JedS6391
90,571,337
false
null
package kgp.fitness /** * A feature of some case in a data set. * * A feature is essentially a variable to a GP program. * * @param value The value of this feature. * @param name A name for this feature. */ data class Feature(val value: Double, val name: String) /** * A case in a data set. * * A case is really just a collection of features mapping to an output. * * @param features A set of features that make up this case. * @param output The output expected for this set of features. */ data class Case(val features: List<Feature>, val output: Double) /** * A set of outputs given by a program on a set of training cases. */ typealias Outputs = List<Double> /** * A set of cases that a program will be trained on. */ typealias Cases = List<Case> /** * A function that will evaluate the performance a program based on * how close its outputs were to the cases given. */ typealias FitnessFunction = (Cases, Outputs) -> Double /** * Provides a way of measuring the fitness of a set of outputs. * * @property name A name for this metric. * @property function A fitness function this metric encapsulates. */ interface Metric { val name: String val function: FitnessFunction /** * Evaluates the fitness using this metrics fitness function. * * @property cases The expected input-output cases. * @property outputs The predicted outputs of a program. * @property programLength The length of the program being evaluated. */ fun fitness(cases: Cases, outputs: Outputs, programLength: Int): Double } /** * A base implementation for measuring the fitness of solutions. */ class BaseMetric(override val name: String, override val function: FitnessFunction) : Metric { /** * Evaluates the fitness based on a set of cases and a set of outputs. * * @property cases The expected input-output cases. * @property outputs The predicted outputs of a program. * @property programLength The length of the program being evaluated (unused). */ override fun fitness(cases: Cases, outputs: Outputs, programLength: Int): Double { return this.function(cases, outputs) } } /** * Provides a way of measuring the fitness of a set of outputs with a penalty for parsimony pressure. * * @property parsimonyCoefficient A coefficient that is used to penalise solutions based on their length. */ class ParsimonyAwareMetric( override val name: String, override val function: FitnessFunction, val parsimonyCoefficient: Double) : Metric { /** * Evaluates the fitness based on a set of cases and a set of outputs. * * The raw fitness will be penalised with by a small factor based on the program's length: * * fitness = [function] - ([parsimonyCoefficient] * [programLength]) * * @property cases The expected input-output cases. * @property outputs The predicted outputs of a program. * @property programLength The length of the program being evaluated. */ override fun fitness(cases: Cases, outputs: Outputs, programLength: Int): Double { val fitness = this.function(cases, outputs) return fitness - (this.parsimonyCoefficient * programLength.toDouble()) } } /** * A collection of standard fitness functions as metrics. */ object FitnessFunctions { /** * Sum of squared errors. */ val sse = BaseMetric( name = "SSE", function = { cases, outputs -> cases.zip(outputs).map { (expected, predicted) -> Math.pow((predicted - expected.output), 2.0) }.sum() } ) /** * Mean squared error. */ val mse = BaseMetric( name = "MSE", function = { cases, outputs -> val sse = cases.zip(outputs).map { (expected, predicted) -> Math.pow((predicted - expected.output), 2.0) }.sum() ((1.0 / cases.size.toDouble()) * sse) } ) /** * Mean absolute error. */ val mae = BaseMetric( name = "MAE", function = { cases, outputs -> val ae = cases.zip(outputs).map { (expected, predicted) -> Math.abs(predicted - expected.output) }.sum() ((1.0 / cases.size.toDouble()) * ae) } ) /** * Mean squared error with parsimony pressure. */ val parsimonyAwareMse = ParsimonyAwareMetric( name = "MSE (parsimony aware)", parsimonyCoefficient = 0.001, function = { cases, outputs -> val sse = cases.zip(outputs).map { (expected, predicted) -> Math.pow((predicted - expected.output), 2.0) }.sum() ((1.0 / cases.size.toDouble()) * sse) } ) }
0
Kotlin
0
1
045fd23e0fac9ea31c20489ae459bd168846d30b
4,800
KGP
MIT License
usvm-core/src/main/kotlin/org/usvm/PathNode.kt
UnitTestBot
586,907,774
false
{"Kotlin": 2547205, "Java": 471958}
package org.usvm import org.usvm.algorithms.findLcaLinear import org.usvm.merging.UMergeable sealed interface PathSegment<Statement> { val statement: Statement data class Single<Statement>( override val statement: Statement, ) : PathSegment<Statement> { override fun toString(): String = "$statement" } data class Merged<Statement>( override val statement: Statement, val left: List<PathSegment<Statement>>, val right: List<PathSegment<Statement>>, ) : PathSegment<Statement> { override fun toString(): String = buildString { appendLine(statement) val targetSize = kotlin.math.max(left.size, right.size) val leftStrs = left.map { it.toString() } + List(targetSize - left.size) { "" } val rightStrs = right.map { it.toString() } + List(targetSize - right.size) { "" } val leftColumnnSize = (leftStrs.maxOfOrNull { it.length } ?: 0) + 8 leftStrs.zip(rightStrs).forEach { (left, right) -> append(left.padEnd(leftColumnnSize)) appendLine(right) } } } } class PathNode<Statement> private constructor( val parent: PathNode<Statement>?, private val _segment: PathSegment<Statement>?, depth: Int, ) : UMergeable<PathNode<Statement>, Unit> { var depth: Int = depth private set val statement: Statement get() = requireNotNull(_segment).statement operator fun plus(statement: Statement): PathNode<Statement> { return PathNode(this, PathSegment.Single(statement), depth + 1) } val allStatements get(): Iterable<Statement> = Iterable { object : Iterator<Statement> { var cur = this@PathNode override fun hasNext(): Boolean = cur._segment != null override fun next(): Statement { if (!hasNext()) { throw NoSuchElementException() } val element = requireNotNull(cur._segment) cur = requireNotNull(cur.parent) return element.statement } } } /** * Check if this [PathNode] can be merged with [other] path node. * * TODO: now the only supported case is: * - statements are equal * * TODO: doesn't save the suffix paths into the result node * * @return the merged path node. */ override fun mergeWith(other: PathNode<Statement>, by: Unit): PathNode<Statement>? { if (_segment != other._segment) { return null } val (lca, suffixLeft, suffixRight) = findLcaLinear( this, other, { it.parent!! }, { it.depth }, { it._segment!! } ) val segment = PathSegment.Merged(statement, suffixLeft, suffixRight) return PathNode(lca, segment, lca.depth + 1) } companion object { private val EMPTY = PathNode<Nothing?>(parent = null, _segment = null, depth = 0) @Suppress("UNCHECKED_CAST") fun <Statement> root(): PathNode<Statement> = EMPTY as PathNode<Statement> } override fun toString(): String = buildString { appendLine(_segment) appendLine(parent) } }
39
Kotlin
0
7
94c5a49a0812737024dee5be9d642f22baf991a2
3,367
usvm
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2021/day3/DiagnosticReport.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day3 import java.util.BitSet private typealias BitCriteria = (Int, Int) -> Int private fun String.toBitSet(): BitSet { return BitSet.valueOf(longArrayOf(this.toLong(radix = 2))) } fun List<String>.toDiagnosticReport(): DiagnosticReport { return DiagnosticReport( stride = first().length, bitmap = map(String::toBitSet) ) } data class DiagnosticReport( val stride: Int, val bitmap: List<BitSet> ) { val powerConsumption: Int get() = gammaRate * epsilonRate val lifeSupportRating: Int get() = oxygenGeneratorRating * cO2ScrubberRating private val columns = stride - 1 downTo 0 private val gammaRate: Int get() = columns.map(::mostCommonBit).toDecimal() private val epsilonRate: Int get() = columns.map(::leastCommonBit).toDecimal() private val oxygenGeneratorRating: Int get() = findRating { mostCommon, leastCommon -> when (mostCommon) { 1, leastCommon -> 1 else -> 0 } } private val cO2ScrubberRating: Int get() = findRating { mostCommon, leastCommon -> when (leastCommon) { 0, mostCommon -> 0 else -> 1 } } private fun mostCommonBit(column: Int): Int { return bitmap.bitCounts(column).maxByOrZero() } private fun leastCommonBit(column: Int): Int { return bitmap.bitCounts(column).minByOrZero() } private fun List<BitSet>.bitCounts(column: Int): Map<Int, Int> { return map { it[column].toInt() } .groupingBy { it } .eachCount() } private fun findRating(criteria: BitCriteria): Int { return columns.fold(bitmap) { bitmap, column -> bitmap.filterColumns(column, criteria) }.first().toDecimal() } private inline fun List<BitSet>.filterColumns(column: Int, criteria: BitCriteria): List<BitSet> { return if (size == 1) { this } else { val bitCounts = bitCounts(column) val mostCommon = bitCounts.maxByOrZero() val leastCommon = bitCounts.minByOrZero() val selected = criteria(mostCommon, leastCommon) filter { row -> row[column].toInt() == selected } } } private fun Boolean.toInt(): Int { return if (this) 1 else 0 } private fun List<Int>.toDecimal(): Int { return joinToString("").toInt(radix = 2) } private fun BitSet.toDecimal(): Int { var result = 0 for (bit in 0 until length()) { if (this[bit]) { result = result or (1 shl bit) } } return result } private fun Map<Int, Int>.maxByOrZero(): Int { val entry = maxByOrNull(Map.Entry<Int, Int>::value) return entry?.key ?: 0 } private fun Map<Int, Int>.minByOrZero(): Int { val entry = minByOrNull(Map.Entry<Int, Int>::value) return entry?.key ?: 0 } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
3,105
advent-2021
ISC License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[155]最小栈.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* //设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 // // // push(x) —— 将元素 x 推入栈中。 // pop() —— 删除栈顶的元素。 // top() —— 获取栈顶元素。 // getMin() —— 检索栈中的最小元素。 // // // // // 示例: // // 输入: //["MinStack","push","push","push","getMin","pop","top","getMin"] //[[],[-2],[0],[-3],[],[],[],[]] // //输出: //[null,null,null,null,-3,null,0,-2] // //解释: //MinStack minStack = new MinStack(); //minStack.push(-2); //minStack.push(0); //minStack.push(-3); //minStack.getMin(); --> 返回 -3. //minStack.pop(); //minStack.top(); --> 返回 0. //minStack.getMin(); --> 返回 -2. // // // // // 提示: // // // pop、top 和 getMin 操作总是在 非空栈 上调用。 // // Related Topics 栈 设计 // 👍 1117 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class MinStack() { var stack:LinkedList<Int> = LinkedList() var minStack:LinkedList<Int> = LinkedList() fun push(`val`: Int) { stack.addLast(`val`) if (minStack.isEmpty() || minStack.last > `val`){ minStack.addLast(`val`) }else{ minStack.addLast(minStack.last) } } fun pop() { if (!stack.isEmpty()) stack.removeLast() minStack.removeLast() } fun top(): Int { return stack.last } fun getMin(): Int { return minStack.last } } /** * Your MinStack object will be instantiated and called as such: * var obj = MinStack() * obj.push(`val`) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.getMin() */ //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,792
MyLeetCode
Apache License 2.0
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day21Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import java.lang.IllegalStateException private fun solution1(input: String) = parse(input).let { ctx -> ctx.getValue("root").evaluate(ctx) } private fun solution2(input: String) = parse(input, true).toMutableMap().let { ctx -> val root = ctx.getValue("root") var min = 0L var max = Long.MAX_VALUE var interval = 1_000_000_000_000L while (min != max) { (min..max step interval).asSequence() .onEach { ctx["humn"] = ValueExpr(it) } .map { it to root.evaluate(ctx) } .windowed(2) .first { (a, b) -> (a.second >= 0L && b.second <= 0L) || (a.second <= 0 && b.second >= 0) } .let { (a, b) -> if (a.second == 0L) { min = a.first max = a.first } else if (b.second == 0L) { min = b.first max = b.first } else { min = a.first max = b.first } } interval /= 10 } min } private fun parse(input: String, part2: Boolean = false) = input.lineSequence().map { line -> Expr.parse(line, part2) }.associate { it } private interface Expr { fun evaluate(ctx: Map<String, Expr>): Long companion object { fun parse(str: String, part2: Boolean) = "(.*): (.*) ([+\\-/*]) (.*)".toRegex().matchEntire(str) ?.groupValues?.let { it[1] to when (it[3]) { "+" -> if (part2 && it[1] == "root") SubExpr(it[2], it[4]) else AddExpr(it[2], it[4]) "-" -> SubExpr(it[2], it[4]) "*" -> MulExpr(it[2], it[4]) "/" -> DivExpr(it[2], it[4]) else -> throw IllegalStateException() } } ?: "(.*): (\\d+)".toRegex().matchEntire(str)!! .groupValues.let { it[1] to ValueExpr(it[2].toLong()) } } } private class ValueExpr(private val value: Long) : Expr { override fun evaluate(ctx: Map<String, Expr>) = value } private class AddExpr(private val id1: String, private val id2: String) : Expr { override fun evaluate(ctx: Map<String, Expr>) = ctx.getValue(id1).evaluate(ctx) + ctx.getValue(id2).evaluate(ctx) } private class SubExpr(private val id1: String, private val id2: String) : Expr { override fun evaluate(ctx: Map<String, Expr>) = ctx.getValue(id1).evaluate(ctx) - ctx.getValue(id2).evaluate(ctx) } private class MulExpr(private val id1: String, private val id2: String) : Expr { override fun evaluate(ctx: Map<String, Expr>) = ctx.getValue(id1).evaluate(ctx) * ctx.getValue(id2).evaluate(ctx) } private class DivExpr(private val id1: String, private val id2: String) : Expr { override fun evaluate(ctx: Map<String, Expr>) = ctx.getValue(id1).evaluate(ctx) / ctx.getValue(id2).evaluate(ctx) } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 21 class Day21Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 152L } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 21208142603224L } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 301L } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 3882224466191L } }) private val exampleInput = """ 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 """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,988
adventofcode-kotlin
MIT License
src/Day06.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
fun main() { fun part1(input: List<String>): Int { val subList = mutableListOf<Char>() var result = 0 input.first().toCharArray().forEachIndexed { index, char -> subList += char if (subList.size > 4) { subList.removeFirst() } if (subList.size == 4) { if (subList.toSet().size == 4) if (result == 0) result = index + 1 } } return result } fun part2(input: List<String>): Int { val subList = mutableListOf<Char>() var result = 0 input.first().toCharArray().forEachIndexed { index, char -> subList += char if (subList.size > 14) { subList.removeFirst() } if (subList.size == 14) { if (subList.toSet().size == 14) if (result == 0) result = index + 1 } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) //check(part2(testInput) == 0) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d7ab334f38a9e260c72725d3f583228acb6aa0e
1,270
advent-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DinnerPlates.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import java.util.Stack import java.util.TreeSet /** * 1172. Dinner Plate Stacks */ interface DinnerPlatesDS { fun push(value: Int) fun pop(): Int fun popAtStack(index: Int): Int } class DinnerPlates(val capacity: Int) : DinnerPlatesDS { private val pq: PriorityQueue<Int> = PriorityQueue() private val map: MutableMap<Int, Stack<Int>> = HashMap() private var max = 0 init { map[max] = Stack() } override fun push(value: Int) { if (pq.isEmpty()) { if (map[max]?.size == capacity) { max++ } map.putIfAbsent(max, Stack()) map[max]?.push(value) } else { val index = pq.poll() map[index]?.push(value) } } override fun pop(): Int { if (max == -1) { max = 0 return -1 } if (map[max]?.size == 0) { max-- return pop() } val top = map[max]?.pop() if (map[max]?.size == 0) { max-- } return top ?: -1 } override fun popAtStack(index: Int): Int { if (!map.containsKey(index) || map[index]?.size == 0) { return -1 } val res = map[index]?.pop() pq.offer(index) return res ?: -1 } } class DinnerPlatesTree(val capacity: Int) : DinnerPlatesDS { private val stacks: Stack<Stack<Int>> = Stack() private val set = TreeSet<Int>() override fun push(value: Int) { if (set.isNotEmpty()) { val idx = set.iterator().next() stacks[idx].push(value) if (stacks[idx].size == capacity) { set.remove(idx) } } else { if (stacks.isEmpty() || stacks.peek().size == capacity) { stacks.add(Stack()) stacks.peek().add(value) } else { stacks.peek().add(value) } } } override fun pop(): Int { if (stacks.isNotEmpty()) { val k = stacks.peek().pop() while (stacks.isNotEmpty() && stacks.peek().isEmpty()) { set.remove(stacks.size - 1) stacks.pop() } return k } return -1 } override fun popAtStack(index: Int): Int { if (index >= stacks.size || stacks[index].isEmpty()) { return -1 } if (index == stacks.size - 1) { return pop() } set.add(index) return stacks[index].pop() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,252
kotlab
Apache License 2.0
src/main/aoc2023/Day9.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 class Day9(input: List<String>) { private val histories = input.map { it.split(" ").map { raw -> raw.toInt() } } private fun differences(history: List<Int>): List<List<Int>> { return buildList { add(history) var current = history do { val next = current.windowed(2, 1).map { (first, second) -> second - first } add(next) current = next } while (!next.all { it == 0 }) } } private fun List<List<Int>>.extrapolate(): Int { var next = 0 for (i in indices.reversed().drop(1)) { next += this[i].last() } return next } private fun List<List<Int>>.extrapolateBackwards(): Int { var next = 0 for (i in indices.reversed().drop(1)) { next = this[i].first() - next } return next } fun solvePart1(): Int { return histories.map { differences(it) }.sumOf { it.extrapolate() } } fun solvePart2(): Int { return histories.map { differences(it) }.sumOf { it.extrapolateBackwards() } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,151
aoc
MIT License
src/commonMain/kotlin/guru/nidi/simple3d/model/Line.kt
nidi3
159,038,498
false
null
package guru.nidi.simple3d.model import kotlin.math.abs import kotlin.math.max import kotlin.math.min open class Line(val a: Vector, val b: Vector) { protected fun insideSegment(p: Vector): Boolean = min(abs(p.x - a.x), abs(p.x - b.x)) + min(abs(p.y - a.y), abs(p.y - b.y)) + min(abs(p.z - a.z), abs(p.z - b.z)) > EPSILON && onSegment(p) protected fun onSegment(p: Vector): Boolean = p.x >= min(a.x, b.x) && p.x <= max(a.x, b.x) && p.y >= min(a.y, b.y) && p.y <= max(a.y, b.y) && p.z >= min(a.z, b.z) && p.z <= max(a.z, b.z) && onStraight(p) protected fun onStraight(p: Vector): Boolean = when { abs(a.x - b.x) > EPSILON -> { abs(p.y - (a.y + (p.x - a.x) * ((b.y - a.y) / (b.x - a.x)))) < EPSILON && abs(p.z - (a.z + (p.x - a.x) * ((b.z - a.z) / (b.x - a.x)))) < EPSILON } abs(a.y - b.y) > EPSILON -> { abs(p.x - (a.x + (p.y - a.y) * ((b.x - a.x) / (b.y - a.y)))) < EPSILON && abs(p.z - (a.z + (p.y - a.y) * ((b.z - a.z) / (b.y - a.y)))) < EPSILON } abs(a.z - b.z) > EPSILON -> { abs(p.y - (a.y + (p.z - a.z) * ((b.y - a.y) / (b.z - a.z)))) < EPSILON && abs(p.x - (a.x + (p.z - a.z) * ((b.x - a.x) / (b.z - a.z)))) < EPSILON } else -> throw IllegalArgumentException("a and b are equal") } } class OpenSegment(a: Vector, b: Vector) : Line(a, b) { operator fun contains(p: Vector): Boolean = insideSegment(p) } class Segment(a: Vector, b: Vector) : Line(a, b) { operator fun contains(p: Vector): Boolean = onSegment(p) } class Straight(a: Vector, b: Vector) : Line(a, b) { operator fun contains(p: Vector): Boolean = onStraight(p) }
0
Kotlin
0
5
bd2a72ac34b32588da31e74aef299ca29e31bde7
1,830
simple-3d
Apache License 2.0
app/src/main/kotlin/com/github/ilikeyourhat/kudoku/solving/deduction/algorithm/NakedValuesAlgorithm.kt
ILikeYourHat
139,063,649
false
{"Kotlin": 166134}
package com.github.ilikeyourhat.kudoku.solving.deduction.algorithm import com.github.ilikeyourhat.kudoku.model.Region import com.github.ilikeyourhat.kudoku.model.hint.SudokuHintGrid import com.github.ilikeyourhat.kudoku.solving.deduction.combinations.CollectionCombinator class NakedValuesAlgorithm( regions: List<Region>, possibilities: SudokuHintGrid, private val size: Int ) : DeductionAlgorithm(regions, possibilities) { class Factory(private val size: Int) : DeductionAlgorithm.Factory { override fun instance(regions: List<Region>, possibilities: SudokuHintGrid): NakedValuesAlgorithm { return NakedValuesAlgorithm(regions, possibilities, size) } } override fun solve(region: Region): Boolean { val list = mutableListOf<Set<Int>>() var changed = false for (field in region) { val hints = possibilities.forField(field) if (hints.isNotEmpty()) { list.add(hints) } } val combinator = CollectionCombinator(size) combinator.iterate(list) { values: List<Set<Int>> -> val sum = mutableSetOf<Int>() for (set in values) { sum.addAll(set) } if (sum.size == size) { changed = changed or clearFromRegion(region, sum) } } return changed } private fun clearFromRegion(region: Region, hintsToRemove: Set<Int>): Boolean { var changed = false for (field in region) { val hints = possibilities.forField(field) if (hints.isNotEmpty() && shouldBeCleared(hints, hintsToRemove)) { possibilities.removeAll(field, hintsToRemove) changed = true } } return changed } private fun shouldBeCleared(currentHints: Set<Int>, hintsToRemove: Set<Int>): Boolean { val tempHints = currentHints.toMutableSet() tempHints.removeAll(hintsToRemove) return tempHints.isNotEmpty() && currentHints.size > tempHints.size } }
1
Kotlin
0
0
b234b2de2edb753844c88ea3cd573444675fc1cf
2,096
Kudoku
Apache License 2.0
librefit-service/src/main/kotlin/io/tohuwabohu/calc/Tdee.kt
tohuwabohu-io
606,202,766
false
{"Kotlin": 125186, "Svelte": 69183, "JavaScript": 48573, "HTML": 13431, "CSS": 850, "Shell": 252}
package io.tohuwabohu.calc import kotlin.math.pow import kotlin.math.round /** * Calculation of basic metabolic rate (BMR) and total daily energy expenditure (TDEE) based on the Harris-Benedict * formula. */ data class Tdee( val age: Number, val sex: CalculationSex, val weight: Number, val height: Number, val activityLevel: Number, val weeklyDifference: Number, val calculationGoal: CalculationGoal ) { val bmr = when (sex) { CalculationSex.MALE -> { round(66 + (13.7 * weight.toFloat()) + (5 * height.toFloat()) - (6.8 * age.toFloat())) } CalculationSex.FEMALE -> { round(655 + (9.6 * weight.toFloat()) + (1.8 * height.toFloat()) - (4.7 * age.toFloat())) } } val tdee = round(activityLevel.toFloat() * bmr) val deficit = weeklyDifference.toFloat() / 10 * 7000 / 7 val target: Float = when (calculationGoal) { CalculationGoal.GAIN -> { tdee.toFloat() + deficit } CalculationGoal.LOSS -> { tdee.toFloat() - deficit; } } val bmi: Float = round(weight.toFloat() / ((height.toFloat() / 100).pow(2))) val bmiCategory: BmiCategory = when (sex) { CalculationSex.FEMALE -> { when (bmi) { in 0f..18f -> BmiCategory.UNDERWEIGHT in 19f..24f -> BmiCategory.STANDARD_WEIGHT in 25f..30f -> BmiCategory.OVERWEIGHT in 31f..40f -> BmiCategory.OBESE else -> BmiCategory.SEVERELY_OBESE } } CalculationSex.MALE -> { when (bmi) { in 0f..19f -> BmiCategory.UNDERWEIGHT in 20f..25f -> BmiCategory.STANDARD_WEIGHT in 26f..30f -> BmiCategory.OVERWEIGHT in 31f..40f -> BmiCategory.OBESE else -> BmiCategory.SEVERELY_OBESE } } } val targetBmi = when (age) { in 19..24 -> arrayOf(19,24) in 25..34 -> arrayOf(20,25) in 35..44 -> arrayOf(21,26) in 45..54 -> arrayOf(22,27) in 55..64 -> arrayOf(23,28) else -> arrayOf(24,29) } val targetWeight = round(((targetBmi[0] + targetBmi[1]).toFloat() / 2) * (height.toFloat() / 100).pow(2)) val durationDays = when (calculationGoal) { CalculationGoal.GAIN -> { (targetWeight - weight.toFloat()) * 7000 / deficit } CalculationGoal.LOSS -> { (weight.toFloat() - targetWeight) * 7000 / deficit } } } enum class CalculationGoal { GAIN, LOSS } enum class CalculationSex { MALE, FEMALE } enum class BmiCategory { UNDERWEIGHT, STANDARD_WEIGHT, OVERWEIGHT, OBESE, SEVERELY_OBESE, }
6
Kotlin
0
0
031d34cd2b343884e0009d76007e10e4261df828
2,783
librefit
MIT License
src/main/kotlin/kt/kotlinalgs/app/leetcode/ArrayProdExceptSelf.ws.kts
sjaindl
384,471,324
false
null
package com.sjaindl.kotlinalgsandroid.leetcode // https://docs.google.com/document/d/1Z8ia8-90S7QFfq5S0LkE_TbFoG9fXQekmeTEnzZx9aY/edit // https://leetcode.com/problems/product-of-array-except-self/ fun productExceptSelf(nums: IntArray): IntArray { //[1,2,4,3] if (nums.isEmpty()) return IntArray(0) val left = IntArray(nums.size) // [1,1,2,8] val right = IntArray(nums.size) // [0,0,3,1] left[0] = 1 right[nums.size - 1] = 1 for (index in 1 until nums.size) { left[index] = left[index - 1] * nums[index - 1] right[nums.size - 1 - index] = right[nums.size - index] * nums[nums.size - index] } val output = IntArray(nums.size) for (index in nums.indices) { output[index] = left[index] * right[index] } return output } productExceptSelf(intArrayOf(3, 3)).toList() productExceptSelf(intArrayOf(2, 2, 0, 2)).toList() productExceptSelf(intArrayOf(1, 2, 4, 3)).toList() // Solved: 20:04
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
961
KotlinAlgs
MIT License
src/main/kotlin/g1301_1400/s1330_reverse_subarray_to_maximize_array_value/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1330_reverse_subarray_to_maximize_array_value // #Hard #Array #Math #Greedy #2023_06_06_Time_347_ms_(100.00%)_Space_43.1_MB_(100.00%) class Solution { private fun getAbsoluteDifference(a: Int, b: Int): Int { return Math.abs(a - b) } fun maxValueAfterReverse(nums: IntArray): Int { val n = nums.size var result = 0 for (i in 0 until n - 1) { result += getAbsoluteDifference(nums[i], nums[i + 1]) } var minLine = Int.MIN_VALUE var maxLine = Int.MAX_VALUE for (i in 0 until n - 1) { minLine = Math.max(minLine, Math.min(nums[i], nums[i + 1])) maxLine = Math.min(maxLine, Math.max(nums[i], nums[i + 1])) } var diff = Math.max(0, (minLine - maxLine) * 2) for (i in 1 until n - 1) { diff = Math.max( diff, getAbsoluteDifference(nums[0], nums[i + 1]) - getAbsoluteDifference(nums[i], nums[i + 1]) ) } for (i in 0 until n - 1) { diff = Math.max( diff, getAbsoluteDifference(nums[n - 1], nums[i]) - getAbsoluteDifference(nums[i + 1], nums[i]) ) } return result + diff } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,310
LeetCode-in-Kotlin
MIT License
src/main/kotlin/d24/D24_1.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d24 import input.Input import java.math.BigDecimal import java.math.RoundingMode val MIN = BigDecimal(200_000_000_000_000L) val MAX = BigDecimal(400_000_000_000_000L) data class Line( val a: BigDecimal, val b: BigDecimal ) fun parseToLine(hailstone: Hailstone): Line { val vx = hailstone.velocity.x val vy = hailstone.velocity.y return Line( vy.divide(vx, 100, RoundingMode.HALF_UP), hailstone.pos.y - vy * hailstone.pos.x / vx ) } fun calculateIntersect(lineA: Line, lineB: Line): Vector? { if (lineA.a == lineB.a) return null // parallel lines val intersectX = (lineA.b - lineB.b).divide(lineB.a - lineA.a, 100, RoundingMode.HALF_UP) val intersectY = lineB.a * intersectX + lineB.b return Vector(intersectX, intersectY, BigDecimal.ZERO) } fun checkInBounds(intersect: Vector): Boolean { return intersect.x in MIN..MAX && intersect.y in MIN..MAX } fun checkInFuture(intersect: Vector, hailstoneA: Hailstone, hailstoneB: Hailstone): Boolean { return intersect.x - hailstoneA.pos.x < BigDecimal.ZERO == hailstoneA.velocity.x < BigDecimal.ZERO && intersect.x - hailstoneB.pos.x < BigDecimal.ZERO == hailstoneB.velocity.x < BigDecimal.ZERO } fun main() { val lines = Input.read("input.txt") val hailstones = lines.map { parseHailstone(it) } var count = 0 for (i in hailstones.indices) { for (j in (i + 1)..hailstones.lastIndex) { val hailstoneA = hailstones[i] val hailstoneB = hailstones[j] val lineA = parseToLine(hailstoneA) val lineB = parseToLine(hailstoneB) val intersect = calculateIntersect(lineA, lineB) ?: continue val inBounds = checkInBounds(intersect) if (!inBounds) continue val inFuture = checkInFuture(intersect, hailstoneA, hailstoneB) if (!inFuture) continue count++ } } println(count) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
1,964
aoc2023-kotlin
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day09.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day09 : Day("572", "847044") { private val map = input .lines() .map { line -> line.toCharArray().map { it.digitToInt() } } private val mapWidth = map[0].size private val mapHeight = map.size override fun solvePartOne(): Any { var riskSum = 0 for (y in 0 until mapHeight) { for (x in 0 until mapWidth) { if (x != 0 && map[y][x] >= map[y][x - 1]) { continue } if (x != mapWidth - 1 && map[y][x] >= map[y][x + 1]) { continue } if (y != 0 && map[y][x] >= map[y - 1][x]) { continue } if (y != mapHeight - 1 && map[y][x] >= map[y + 1][x]) { continue } riskSum += 1 + map[y][x] } } return riskSum } override fun solvePartTwo(): Any { val basinSizes = mutableListOf<Int>() val filled = Array(mapHeight) { BooleanArray(mapWidth) } for (y in 0 until mapHeight) { for (x in 0 until mapWidth) { if (map[y][x] == 9 || filled[y][x]) { continue } var basinSize = 0 val locationsToFill = ArrayDeque<Pair<Int, Int>>() locationsToFill.add(x to y) while (!locationsToFill.isEmpty()) { val (currentX, currentY) = locationsToFill.removeFirst() if (currentX < 0 || currentX >= mapWidth || currentY < 0 || currentY >= mapHeight) { continue } if (map[currentY][currentX] == 9 || filled[currentY][currentX]) { continue } filled[currentY][currentX] = true basinSize++ locationsToFill.add(currentX + 1 to currentY) locationsToFill.add(currentX - 1 to currentY) locationsToFill.add(currentX to currentY + 1) locationsToFill.add(currentX to currentY - 1) } basinSizes.add(basinSize) } } basinSizes.sortDescending() return basinSizes[0] * basinSizes[1] * basinSizes[2] } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
2,421
advent-of-code-2021
MIT License
src/main/kotlin/com/colinodell/advent2021/Day16.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day16(input: String) { private val transmission = decodePacket(BitString(input)) fun solvePart1() = transmission.versionSum() fun solvePart2() = transmission.value() interface Packet { val version: Int fun versionSum(): Int fun value(): Long } data class Literal(override val version: Int, val value: Long) : Packet { override fun versionSum() = version override fun value() = value } data class Operator(override val version: Int, private val type: Int, val subPackets: List<Packet>) : Packet { override fun versionSum() = version + subPackets.sumOf { it.versionSum() } override fun value() = when (type) { 0 -> subPackets.sumOf { it.value() } 1 -> subPackets.map { it.value() }.reduce { a, b -> a * b} 2 -> subPackets.minOf { it.value() } 3 -> subPackets.maxOf { it.value() } 5 -> if (subPackets[0].value() > subPackets[1].value()) 1 else 0 6 -> if (subPackets[0].value() < subPackets[1].value()) 1 else 0 7 -> if (subPackets[0].value() == subPackets[1].value()) 1 else 0 else -> throw IllegalArgumentException("Unsupported operator type: $type") } } companion object { fun decodePacket(bits: String): Packet = decodePacket(BitString(bits)) private fun decodePacket(bits: BitString): Packet { val version = bits.takeInt(3) val type = bits.takeInt(3) return when (type) { 4 -> Literal(version, parseLiteral(bits)) else -> Operator(version, type, parseSubPackets(bits)) } } private fun parseLiteral(bits: BitString): Long { var value = 0L do { val isLastNumberGroup = bits.take(1) == "0" value = value * 16 + bits.takeInt(4) } while (!isLastNumberGroup) return value } private fun parseSubPackets(bits: BitString): List<Packet> { return when (bits.takeInt(1)) { 0 -> bits.subsequence(bits.takeInt(15)).whileNotAtEnd { decodePacket(it) } 1 -> (0 until bits.takeInt(11)).map { decodePacket(bits) } else -> throw IllegalArgumentException("Unsupported operation length type") } } } private class BitString(hexString: String) { private var bits = hexString.map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString("") private var cursor = 0 fun take(len: Int) = bits.substring(cursor, cursor + len).also { cursor += len } fun takeInt(len: Int) = take(len).toInt(2) fun subsequence(len: Int): BitString { val sub = bits.substring(cursor, cursor + len) return BitString("").apply { bits = sub }.also { cursor += len } } fun <T> whileNotAtEnd(fn: (BitString) -> T): List<T> { val result = mutableListOf<T>() while (cursor != bits.length) { result.add(fn(this)) } return result } } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
3,199
advent-2021
Apache License 2.0
src/main/kotlin/aoc23/Day19.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import aoc23.Day19Domain.Accepted import common.Year23 import aoc23.Day19Domain.Aplenty import aoc23.Day19Domain.Part import aoc23.Day19Domain.Rating import aoc23.Day19Domain.RatingCategory import aoc23.Day19Domain.Rejected import aoc23.Day19Domain.Rule import aoc23.Day19Domain.Transitional import aoc23.Day19Domain.WorkflowKey import aoc23.Day19Parser.toAplenty import common.Collections.partitionedBy import common.Collections.product import common.Space3D.Parser.valuesFor object Day19 : Year23 { fun List<String>.part1(): Int = toAplenty() .apply { sortParts() } .sumOfAcceptedRatings() fun List<String>.part2(overrideParts: List<Part>? = null): Long = toAplenty(overrideParts = overrideParts ?: rangeParts()) .apply { sortParts() } .countOfCombinationsOfAccepted() private fun rangeParts(): List<Part> = listOf( Part( ratings = RatingCategory.entries.map { Rating(it, IntRange(1, 4000)) } ) ) } object Day19Domain { class Aplenty( private val workflows: Map<String, Workflow>, private val parts: List<Part>, ) { private var accepted = listOf<Part>() fun sumOfAcceptedRatings(): Int = accepted .sumOf(Part::ratings) fun countOfCombinationsOfAccepted(): Long = accepted .sumOf(Part::combinations) fun sortParts() { accepted = parts.flatMap { sortThisPart(it, workflows["in"]!!) }.filterNotNull() } private fun sortThisPart(part: Part, workflow: Workflow): List<Part?> = when (workflow) { Accepted -> listOf(part) Rejected -> listOf(null) is Transitional -> { workflow.match(part).flatMap { (part, nextWorkflow) -> sortThisPart(part, workflows[nextWorkflow.value]!!) } } } } @JvmInline value class WorkflowKey(val value: String) sealed interface Workflow class Transitional( private val key: WorkflowKey, private val rules: List<Rule>, private val unMatchedWorkflow: WorkflowKey, ) : Workflow { fun match(part: Part): List<Pair<Part, WorkflowKey>> { val maybeMatches = rules.firstNotNullOfOrNull { rule -> rule.checkPart(part) } return maybeMatches ?: listOf(part to unMatchedWorkflow) } private fun Rule.checkPart(part: Part): List<Pair<Part, WorkflowKey>>? = part.ratings .filter { it.category == ratingCategory } .firstNotNullOfOrNull { rating -> invoke(rating)?.map { (newRating, workflow) -> (part.withRating(newRating) to workflow) } } } enum class LtGt { Lt, Gt } class Rule( val ratingCategory: RatingCategory, private val ltgt: LtGt, private val comparator: Int, private val current: WorkflowKey, private val destination: WorkflowKey ) : (Rating) -> List<Pair<Rating, WorkflowKey>>? { override fun invoke(rating: Rating): List<Pair<Rating, WorkflowKey>>? = when (ltgt) { LtGt.Lt -> rating.nextFor { it < comparator } LtGt.Gt -> rating.nextFor { it > comparator } } private fun Rating.nextFor(predicate: (Int) -> Boolean): List<Pair<Rating, WorkflowKey>>? = this.range.partition(predicate).let { (match, noMatch) -> listOfNotNull( this.toPair(match, destination), this.toPair(noMatch, current) ).takeIf { match.isNotEmpty() } } private fun Rating.toPair(ints: List<Int>, workflowKey: WorkflowKey): Pair<Rating, WorkflowKey>? = ints .takeIf { it.isNotEmpty() } ?.let { Pair( this.copy(range = IntRange(it.min(), it.max())), workflowKey ) } } sealed interface Terminal : Workflow data object Accepted : Terminal data object Rejected : Terminal enum class RatingCategory { x, m, a, s } data class Rating( val category: RatingCategory, val range: IntRange, ) data class Part( val ratings: List<Rating> ) { fun ratings(): Int = ratings .sumOf { it.range.sum() } fun combinations(): Long = ratings .map { (it.range.last() - it.range.first()) + 1L } .product() fun withRating(rating: Rating): Part { val index = this@Part.ratings.indexOfFirst { it.category == rating.category } return Part( ratings = ratings.toMutableList() .apply { set(index, rating) } ) } } } object Day19Parser { fun List<String>.toAplenty(overrideParts: List<Part>? = null): Aplenty { val partitionedBy = this.partitionedBy("") val workflows = partitionedBy.first() val parts = partitionedBy.last() return Aplenty( workflows = workflows .associate { it.dropLast(1).split("{").run { first() to last().toTransistional(first()) } } + mapOf( "A" to Accepted, "R" to Rejected, ), parts = overrideParts ?: parts.map { it.toPart() } ) } private fun String.toTransistional(key: String): Transitional { val split = this.split(",") val current = WorkflowKey(key) return Transitional( key = current, rules = split.dropLast(1).map { it.toRule(current) }, unMatchedWorkflow = WorkflowKey(split.last()) ) } private val ruleRegex = """(\w)([<>])(\d+):(\w+)""".toRegex() private fun String.toRule(current: WorkflowKey): Rule { val (ratingCategory, ltgt, comparator, destination) = ruleRegex.valuesFor(this) return Rule( ratingCategory = RatingCategory.valueOf(ratingCategory), ltgt = when (ltgt[0]) { '<' -> Day19Domain.LtGt.Lt '>' -> Day19Domain.LtGt.Gt else -> error("bad") }, comparator = comparator.toInt(), current = current, destination = WorkflowKey(destination), ) } private fun String.toPart(): Part = Part( ratings = this .drop(1) .dropLast(1) .split(",") .map { it.toRating() } ) private fun String.toRating(): Rating { val (category, value) = this.split("=") return Rating( category = RatingCategory.valueOf(category), range = IntRange(value.toInt(), value.toInt()) ) } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
7,281
aoc
Apache License 2.0
src/Day01.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
import java.util.* fun main() { fun sorted(input: List<String>): SortedSet<Int> { var sum = 0 return TreeSet(Comparator.naturalOrder<Int>().reversed()).apply { input.map { if (it.isBlank()) { add(sum) sum = 0 } else { sum += it.toInt() } } if (sum != 0) { add(sum) } } } fun part1(input: List<String>): Int { val ts = sorted(input) // println(ts.joinToString()) return ts.first() } fun part2(input: List<String>): Int { return sorted(input).take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
956
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1713_minimum_operations_to_make_a_subsequence // #Hard #Array #Hash_Table #Greedy #Binary_Search // #2023_06_16_Time_862_ms_(100.00%)_Space_67.3_MB_(100.00%) import java.util.Arrays class Solution { fun minOperations(target: IntArray, arr: IntArray): Int { val map: MutableMap<Int, Int> = HashMap() for (i in target.indices) { map[target[i]] = i } val list: MutableList<Int?> = ArrayList() for (num in arr) { if (map.containsKey(num)) { list.add(map[num]) } } return target.size - longestIncreasingSubsequence(list) } private fun longestIncreasingSubsequence(list: List<Int?>): Int { val n = list.size var l = 0 val arr = IntArray(n) for (num in list) { var index = Arrays.binarySearch(arr, 0, l, num!!) if (index < 0) { index = index.inv() } arr[index] = num if (index == l) { l++ } } return l } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,099
LeetCode-in-Kotlin
MIT License
src/Day10.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
fun main() { fun part1(input: List<String>): Int { var x = 1 var cycle = 1 var addValue = 0 var adding = false val cycleValues = mutableListOf<Int>() var i = 0 while (i < input.size) { if (adding) { x += addValue adding = false i++ } else if (input[i] == "noop") { // do nothing i++ } else { val (command, value) = input[i].split(" ") if (command == "addx") { adding = true addValue = value.toInt() println("x: $x cycle: $cycle addvalue: $addValue adding $adding i $i") } } cycle++ if ((cycle + 20) % 40 == 0) { cycleValues.add(x * cycle) } } println(cycleValues) return cycleValues.sum() } fun part2(input: List<String>): Int { var x = 1 var cycle = 0 var addValue = 0 var adding = false var screen = mutableListOf<String>() var line = "" var i = 0 while (i < input.size) { cycle++ if(cycle - 1 in x-1..x+1) { // if(x >= cycle - 1 && x <= cycle + 1) { line += "█" } else { line += " " } if(cycle >= 40) { screen.add(line) line = "" cycle = 0 } if (adding) { x += addValue adding = false i++ } else if (input[i] == "noop") { // do nothing i++ } else { val (command, value) = input[i].split(" ") if (command == "addx") { adding = true addValue = value.toInt() } } } for(row in screen) { println(row) } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") // println(part1(testInput)) println(part2(testInput)) val input = readInput("Day10") // output(part1(input)) output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
1,920
AdventOfCode2022
Apache License 2.0
src/main/kotlin/dynamicProgramming/EditDistance.kt
TheAlgorithms
177,334,737
false
{"Kotlin": 41212}
package dynamicProgramming fun min(x: Int, y: Int, z: Int): Int { if (x <= y && x <= z) return x return if (y <= x && y <= z) y else z } /* * This is a dynamic programming implementation of edit distance. * @Params str1,str2 - strings to be compared * @Return minimum number of operations to convert one string to another * */ fun editDistance(str1: String, str2: String): Int { val dp = Array(str1.length + 1) { IntArray(str2.length + 1) } for (i in 0..str1.length) { for (j in 0..str2.length) { if (i == 0) dp[i][j] = j else if (j == 0) dp[i][j] = i else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1] else dp[i][j] = (1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])) } } return dp[str1.length][str2.length] }
62
Kotlin
369
1,221
e57a8888dec4454d39414082bbe6a672a9d27ad1
894
Kotlin
MIT License
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day04.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues /** * * @author <NAME> */ class Day04 : Day(title = "Security Through Obscurity") { private companion object Configuration { private const val CHECKSUM_LENGTH = 5 private const val SECRET_PHRASE = "northpole object storage" private const val INPUT_PATTERN_STRING = """^([a-z-]+)-(\d+)\[([a-z]{5})]$""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() private const val NAME_INDEX = 1 private const val ID_INDEX = 2 private const val CHECKSUM_INDEX = 3 private val PARAM_INDICES = intArrayOf(NAME_INDEX, ID_INDEX, CHECKSUM_INDEX) } override fun first(input: Sequence<String>): Any = input .getValidRooms() .map { it.sectorId } .sum() override fun second(input: Sequence<String>): Any = input .getValidRooms() .find { (encryptedName, sectorId, _) -> SECRET_PHRASE == encryptedName.asSequence() .map { if (it != '-') 'a' + ((it - 'a' + (sectorId % 26)) % 26) else ' ' } .joinToString("") }?.sectorId ?: throw IllegalStateException("No answer found") private fun Sequence<String>.getValidRooms(): Sequence<Room> { return this .map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) } .map { (name, id, checksum) -> Room(name, id.toInt(), checksum) } .filter { room -> room.checksum == room.encryptedName .filter { it != '-' } .groupBy { it } .asIterable() .sortedWith(Comparator { (k, v), (ok, ov) -> if (v.size > ov.size || (v.size == ov.size && k < ok)) -1 else 1 }) .take(CHECKSUM_LENGTH) .map { it.key } .joinToString("") } } private data class Room(val encryptedName: String, val sectorId: Int, val checksum: String) }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,145
AdventOfCode
MIT License
src/main/kotlin/days/Day8.kt
hughjdavey
317,575,435
false
null
package days import days.Day8.Operation.ACC import days.Day8.Operation.JMP import days.Day8.Operation.NOP class Day8 : Day(8) { // 1928 override fun partOne(): Any { return Program(inputList).run().accumulator } // 1319 override fun partTwo(): Any { return sequence { yieldAll(inputList.mapIndexedNotNull { i, s -> if (s.startsWith("nop") || s.startsWith("jmp")) i else null }) } .map { Program(inputList).flipAt(it) } .map { it.run() }.first { it.isHalted }.accumulator } class Program(code: List<String>) { private val instructions = code.map { it.split(" ") }.map { (op, arg) -> Instruction(Operation.valueOf(op.toUpperCase()), arg.toInt()) }.toMutableList() private var isLooping = false private var isHalted = false private var accumulator = 0 private var pointer = 0 fun run(): ProgramState { while (refreshState()) { advance() } return ProgramState(accumulator, isLooping, isHalted) } fun flipAt(index: Int): Program { instructions[index] = instructions[index].flip() return this } private fun advance() { val instruction = instructions[pointer] if (instruction.operation == ACC) { accumulator += instruction.argument } pointer += if (instruction.operation == JMP) instruction.argument else 1 instruction.executed = true } private fun refreshState(): Boolean { if (pointer > instructions.lastIndex) { isHalted = true } else if (instructions[pointer].executed) { isLooping = true } return !isLooping && !isHalted } } data class ProgramState(val accumulator: Int, val isLooping: Boolean, val isHalted: Boolean) data class Instruction(var operation: Operation, val argument: Int) { var executed = false fun flip(): Instruction { return when (operation) { JMP -> copy(operation = NOP) NOP -> copy(operation = JMP) ACC -> this } } } enum class Operation { ACC, JMP, NOP } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,323
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/java/challenges/educative_grokking_coding_interview/fast_slow_pointers/_6/PalindromeList.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.fast_slow_pointers._6 import challenges.educative_grokking_coding_interview.LinkedList import challenges.educative_grokking_coding_interview.LinkedListNode import challenges.educative_grokking_coding_interview.PrintList.printListWithForwardArrow /** Given the head of a linked list, your task is to check whether the linked list is a palindrome or not. Return TRUE if the linked list is a palindrome; otherwise, return FALSE. https://www.educative.io/courses/grokking-coding-interview-patterns-java/B1kqL0GDRVn */ object PalindromeList { fun palindrome(head: LinkedListNode?): Boolean { // Initialize slow and fast pointers to the head of the linked list var slow: LinkedListNode? = head var fast: LinkedListNode? = head // Find the middle of the linked list using the slow and fast pointers while (fast?.next != null) { // move slow one step forward slow = slow?.next // move fast two steps forward fast = fast.next?.next } // Reverse the second half of the linked list starting from the middle node var revertData: LinkedListNode? = LinkedListReversal.reverseLinkedList(slow) // Compare the first half of the linked list with the reversed second half of the linked list val check = compareTwoHalves(head, revertData) // Re-reverse the second half of the linked list to restore the original linked list revertData = LinkedListReversal.reverseLinkedList(revertData) // Return True if the linked list is a palindrome, else False return if (check) { true } else false } fun compareTwoHalves(firstHalf: LinkedListNode?, secondHalf: LinkedListNode?): Boolean { // Compare the corresponding nodes of the first and second halves of the linked list var firstHalf: LinkedListNode? = firstHalf var secondHalf: LinkedListNode? = secondHalf while (firstHalf != null && secondHalf != null) { if (firstHalf.data !== secondHalf.data) { return false } else { firstHalf = firstHalf.next secondHalf = secondHalf.next } } return true } @JvmStatic fun main(args: Array<String>) { val input = arrayOf( intArrayOf(2, 4, 6, 4, 2), intArrayOf(0, 3, 5, 5, 0), intArrayOf(9, 27, 4, 4, 27, 9), intArrayOf(5, 4, 7, 9, 4, 5), intArrayOf(5, 10, 15, 20, 15, 10, 5) ) for (i in input.indices) { print(i + 1) val list = LinkedList() list.createLinkedList(input[i]) print(".\tLinked list: ") printListWithForwardArrow(list.head) print("\tIs it a palindrome? ") val result = palindrome(list.head) if (result) { println("Yes") } else { println("No") } println(String(CharArray(100)).replace('\u0000', '-')) } } } object LinkedListReversal { fun reverseLinkedList(slowPtr: LinkedListNode?): LinkedListNode? { var prev: LinkedListNode? = null var next: LinkedListNode? var curr = slowPtr while (curr != null) { next = curr.next curr.next = prev prev = curr curr = next } return prev } fun reverseLinkedList(node: LinkedListNode?, k: Int): Array<LinkedListNode?> { var previous: LinkedListNode? = null var current = node var next: LinkedListNode? = null for (i in 0 until k) { next = current!!.next current.next = previous previous = current current = next } return arrayOf(previous, current) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,932
CodingChallenges
Apache License 2.0
src/main/kotlin/day07/Day07.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day07 import java.io.File fun main() { val data = parse("src/main/kotlin/day07/Day07-Sample.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 07 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<Long> { var node = "/" val dirs = mutableMapOf(node to 0L) File(path).forEachLine { line -> val tokens = line.split(" ") if (tokens[0] == "$" && tokens[1] == "cd") { val name = tokens[2] node = when (name) { "/" -> "/" ".." -> node.substringBeforeLast('/') else -> "$node/$name" } } else { tokens[0].toLongOrNull()?.let { size -> var current = node while (current.isNotBlank()) { dirs.merge(current, size, Long::plus) current = current.substringBeforeLast('/') } } } } return dirs.map { it.value } } private fun part1(data: List<Long>): Long { return data.filter { it <= 100000L }.sum() } private fun part2(data: List<Long>): Long { val required = 30_000_000 - (70_000_000 - data.first()) return data.sorted().first { it >= required } }
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
1,424
advent-of-code-2022
MIT License
src/Day12.kt
SnyderConsulting
573,040,913
false
{"Kotlin": 46459}
fun main() { fun part1(input: List<String>): Int { val grid = mutableListOf<MutableList<Position>>() var startPosition = Position(0, 0, 0) var endPosition = Position(0, 0, 0) input.forEachIndexed { y, line -> grid.add(mutableListOf()) line.forEachIndexed { x, char -> if (char == 'S') { //start startPosition = Position(x, y, 0, 0) grid.last().add(startPosition) } else if (char == 'E') { //end endPosition = Position(x, y, 25) grid.last().add(endPosition) } else { grid.last().add(Position(x, y, ('a'..'z').toList().indexOf(char))) } } } val currentPositions = mutableListOf(startPosition) val stagedPositions = mutableListOf<Position>() while (currentPositions.isNotEmpty()) { currentPositions.forEach { stagedPositions.addAll(it.getOtherPositions(grid)) } currentPositions.clear() currentPositions.addAll(stagedPositions) stagedPositions.clear() } return grid[endPosition.y][endPosition.x].distance!! } fun part2(input: List<String>): Int { val grid = mutableListOf<MutableList<Position>>() val startingPositions = mutableListOf<Position>() var endPosition = Position(0, 0, 0) input.forEachIndexed { y, line -> grid.add(mutableListOf()) line.forEachIndexed { x, char -> if (char == 'a' || char == 'S') { //start? val startingPosition = Position(x, y, 0) startingPositions.add(startingPosition) grid.last().add(startingPosition) } else if (char == 'E') { //end endPosition = Position(x, y, 25) grid.last().add(endPosition) } else { grid.last().add(Position(x, y, ('a'..'z').toList().indexOf(char))) } } } val resultList = mutableListOf<Int>() startingPositions.forEach { position -> position.distance = 0 val currentPositions = mutableListOf(position) val stagedPositions = mutableListOf<Position>() while (currentPositions.isNotEmpty()) { currentPositions.forEach { stagedPositions.addAll(it.getOtherPositions(grid)) } currentPositions.clear() currentPositions.addAll(stagedPositions) stagedPositions.clear() } grid[endPosition.y][endPosition.x].distance?.also { resultList.add(it) } grid.forEach { row -> row.forEach { it.distance = null } } } return resultList.min() } val input = readInput("Day12") println(part1(input)) println(part2(input)) } data class Position(val x: Int, val y: Int, val height: Int, var distance: Int? = null) { fun getOtherPositions(grid: List<List<Position>>): MutableList<Position> { val otherPositions = mutableListOf<Position>() val gridWidth = grid.first().size val gridHeight = grid.size fun checkPosition(otherPosition: Position) { if (otherPosition.height <= height + 1 && otherPosition.distance == null) { otherPosition.distance = distance!! + 1 otherPositions.add(otherPosition) } } if (x != 0) { //get left checkPosition(grid[y][x - 1]) } if (x != gridWidth - 1) { //get right checkPosition(grid[y][x + 1]) } if (y != 0) { //get bottom checkPosition(grid[y - 1][x]) } if (y != gridHeight - 1) { //get top checkPosition(grid[y + 1][x]) } return otherPositions } }
0
Kotlin
0
0
ee8806b1b4916fe0b3d576b37269c7e76712a921
4,228
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/day7/day7.kt
lavong
317,978,236
false
null
/* --- Day 7: Handy Haversacks --- You land at the regional airport in time for your next flight. In fact, it looks like you'll even have time to grab some food: all flights are currently delayed due to issues in luggage processing. Due to recent aviation regulations, many rules (your puzzle input) are being enforced about bags and their contents; bags must be color-coded and must contain specific quantities of other color-coded bags. Apparently, nobody responsible for these regulations considered how long they would take to enforce! For example, consider the following rules: light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. These rules specify the required contents for 9 bag types. In this example, every faded blue bag is empty, every vibrant plum bag contains 11 bags (5 faded blue and 6 dotted black), and so on. You have a shiny gold bag. If you wanted to carry it in at least one other bag, how many different bag colors would be valid for the outermost bag? (In other words: how many colors can, eventually, contain at least one shiny gold bag?) In the above rules, the following options would be available to you: A bright white bag, which can hold your shiny gold bag directly. A muted yellow bag, which can hold your shiny gold bag directly, plus some other bags. A dark orange bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag. A light red bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag. So, in this example, the number of bag colors that can eventually contain at least one shiny gold bag is 4. How many bag colors can eventually contain at least one shiny gold bag? (The list of rules is quite long; make sure you get all of it.) --- Part Two --- It's getting pretty expensive to fly these days - not because of ticket prices, but because of the ridiculous number of bags you need to buy! Consider again your shiny gold bag and the rules from the above example: faded blue bags contain 0 other bags. dotted black bags contain 0 other bags. vibrant plum bags contain 11 other bags: 5 faded blue bags and 6 dotted black bags. dark olive bags contain 7 other bags: 3 faded blue bags and 4 dotted black bags. So, a single shiny gold bag must contain 1 dark olive bag (and the 7 bags within it) plus 2 vibrant plum bags (and the 11 bags within each of those): 1 + 1*7 + 2 + 2*11 = 32 bags! Of course, the actual rules have a small chance of going several levels deeper than this example; be sure to count all of the bags, even if the nesting becomes topologically impractical! Here's another example: shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags. In this example, a single shiny gold bag must contain 126 other bags. How many individual bags are required inside your single shiny gold bag? */ package day7 data class BagRule(val amount: Int, val type: String) data class Bag(val type: String, val rules: Set<BagRule>) fun main() { val input = AdventOfCode.file("day7/input").lines().filter { it.isNotBlank() } val bags = input.map { bag(it) } println("solution part one: ${bags.search("shiny gold").count()}") println("solution part two: ${bags.searchAndCount("shiny gold") - 1}") } fun bagType(rule: String): String { return rule.split("bag").first().trim() } fun bagRules(rule: String): Set<BagRule> { return mutableSetOf<BagRule>().apply { rule .replace("bags", "bag") .replace(",", "") .replace(".", "") .split("bag").onEach { if (it.length > 2) { it.trim().split(" ") .takeIf { !it.contains("no") && !it.contains("other") } ?.let { add(BagRule(it.first().toInt(), it.takeLast(2).joinToString(" "))) } } } } } fun bag(rule: String): Bag { val split = rule.split("contain") return Bag(type = bagType(split[0]), rules = bagRules(split[1])) } fun List<Bag>.search(bagOfInterest: String): Set<String> { return map { mutableSetOf<String>().apply { if (it.rules.map { it.type }.contains(bagOfInterest)) { add(it.type) addAll(search(it.type)) } } }.flatten().toSet() } fun List<Bag>.searchAndCount(bagOfInterest: String): Int { var bags = 1 first { it.type == bagOfInterest }.rules.forEach { bags += (it.amount * searchAndCount(it.type)) } return bags }
0
Kotlin
0
1
a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f
5,324
adventofcode-2020
MIT License
src/main/Day01.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day01 import utils.readInput data class Reader(val elves: List<List<Int>> = listOf(), val elf: List<Int> = listOf()) { fun read(line: String): Reader = when { line.isBlank() -> Reader(complete()) else -> Reader(elves, elf + line.toInt()) } fun complete(): List<List<Int>> = when { elf.isEmpty() -> elves else -> elves + listOf(elf) } } fun part1(input: List<String>): Int = readCalories(input).maxOf { it.sum() } fun part2(input: List<String>): Int = readCalories(input).map { it.sum() }.sortedDescending().take(3).sum() private fun readCalories(input: List<String>) = input.fold(Reader(), Reader::read).complete() fun main() { val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
825
aoc-2022
Apache License 2.0
AdventOfCode/Challenge2023Day02.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.test.assertEquals class Challenge2023Day02 { private fun solve( gameConfig: GameConfig, file: String, ): Int { val games = File(file).bufferedReader().readLines() val validGamesIdList = mutableListOf<Int>() val allowedCubeColors = gameConfig.cubes.map { it.color } for (game in games) { val rounds = game.split(":")[1].split(";") var invalidGame = false for (round in rounds) { if (invalidGame) break val drawnCubes = round.split(",") for (cube in drawnCubes) { if (invalidGame) break val color = Regex("([a-z]+)").find(cube)?.groupValues?.first() val amount = Regex("(\\d+)").find(cube)?.groupValues?.first()?.toInt() if (color !in allowedCubeColors) { invalidGame = true break } val currentCube = gameConfig.cubes.find { it.color == color } if ((currentCube?.maxAmount ?: 0) < amount!!) { invalidGame = true break } } } if (!invalidGame) { val idRegex = Regex("(\\d+):") val gameId = idRegex.find(game)?.groupValues?.get(1)?.toInt() validGamesIdList.add(gameId!!) } } return validGamesIdList.sum() } data class GameConfig(val cubes: List<CubeConfig>) data class CubeConfig( val color: String, val maxAmount: Int, ) @Test fun test() { val cubes = mutableListOf<CubeConfig>() // Example cubes: 12 red cubes, 13 green cubes, and 14 blue cubes.add(CubeConfig("red", 12)) cubes.add(CubeConfig("green", 13)) cubes.add(CubeConfig("blue", 14)) val exampleSolution = solve(GameConfig(cubes), "./AdventOfCode/Data/Day02-1-Test-Data.txt") println("Solution Example: $exampleSolution") assertEquals(8, exampleSolution) val cubesChallenge = mutableListOf<CubeConfig>() // Example cubes: 12 red cubes, 13 green cubes, and 14 blue cubesChallenge.add(CubeConfig("red", 12)) cubesChallenge.add(CubeConfig("green", 13)) cubesChallenge.add(CubeConfig("blue", 14)) val challangeSolution = solve(GameConfig(cubesChallenge), "./AdventOfCode/Data/Day02-1.txt") println("Solution 1: $challangeSolution") } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
2,629
KotlinCodeJourney
MIT License
src/Day01.kt
mikemac42
573,071,179
false
{"Kotlin": 45264}
fun part1MostCalories(input: String): Int { var currentFood = 0 var maxFood = 0 input.lines().forEach { line -> if (line.isBlank()) { if (currentFood > maxFood) { maxFood = currentFood } currentFood = 0 } else { currentFood += line.toInt() } } if (currentFood > maxFood) { maxFood = currentFood } return maxFood } fun part2MostCalories(input: String): Int { var currentFood = 0 val topElves = mutableListOf<Int>() input.lines().forEach { line -> if (line.isBlank()) { topElves.add(currentFood) if (topElves.size == 4) { topElves.remove(topElves.min()) } currentFood = 0 } else { currentFood += line.toInt() } } topElves.add(currentFood) if (topElves.size == 4) { topElves.remove(topElves.min()) } return topElves.sum() }
0
Kotlin
1
0
909b245e4a0a440e1e45b4ecdc719c15f77719ab
858
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2016/day8/BoardGamer.kt
arnab
75,525,311
false
null
package aoc2016.day8 data class Cell(val x: Int, val y: Int, var on: Boolean = false) { fun draw() = if (on) "#" else "-" } data class Board(val size: Pair<Int, Int>) { val cells: List<List<Cell>> by lazy { IntRange(0, size.second - 1).map { x-> IntRange(0, size.first - 1).map { y-> Cell(x, y) } } } // "rect 3x3" private val rectInstrMatcher = Regex("""rect (\d+)x(\d+)""") // "rotate row y=0 by 4" private val rotateRowInstrMatcher = Regex("""rotate row y=(\d+) by (\d+)""") // "rotate column x=1 by 1" private val rotateColInstrMatcher = Regex("""rotate column x=(\d+) by (\d+)""") fun apply(instructionText: String): Board { val rectMatch = rectInstrMatcher.matchEntire(instructionText) if (rectMatch != null) { val (a, b) = rectMatch.destructured applyRectInstruction(a.toInt(), b.toInt()) } val rotateRowMatch = rotateRowInstrMatcher.matchEntire(instructionText) if (rotateRowMatch != null) { val (row, shift) = rotateRowMatch.destructured applyRotateRowInstruction(row.toInt(), shift.toInt()) } val rotateColMatch = rotateColInstrMatcher.matchEntire(instructionText) if (rotateColMatch != null) { val (col, shift) = rotateColMatch.destructured applyRotateColInstruction(col.toInt(), shift.toInt()) } return this } private fun applyRectInstruction(a: Int, b: Int) { IntRange(0, b - 1).forEach { x -> IntRange(0, a - 1).forEach { y -> cells[x][y].on = true } } } private fun applyRotateRowInstruction(row: Int, shift: Int) { val size = cells[row].size val rowOriginal = cells[row].map { it.copy() } cells[row].forEachIndexed { i, cell -> val indexBeingShifted = (size - shift + i) % size cell.on = rowOriginal[indexBeingShifted].on } } private fun applyRotateColInstruction(col: Int, shift: Int) { val size = cells.size val columnOriginal = cells.map { row -> row[col] }.map { it.copy() } cells.forEachIndexed { i, row -> val indexBeingShifted = (size - shift + i) % size cells[i][col].on = columnOriginal[indexBeingShifted].on } } fun draw() { cells.forEach { row -> println() println(row.map(Cell::draw).joinToString(" ")) } } } object BoardGamer { fun run(X: Int, Y: Int, instructions: List<String>): Board { var board = Board(Pair(X, Y)) instructions.forEach { println("After instruction \"$it\":") board = board.apply(it) board.draw() } return board } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,848
adventofcode
MIT License
games-core/src/main/kotlin/net/zomis/games/Map2D.kt
talsewell
309,196,629
true
{"Kotlin": 395303, "Vue": 83692, "JavaScript": 27193, "Java": 17130, "CSS": 3871, "HTML": 1358, "Dockerfile": 228}
package net.zomis.games import net.zomis.Best import net.zomis.games.dsl.Point private fun flipX(start: Position): Position { return Position(start.sizeX - 1 - start.x, start.y, start.sizeX, start.sizeY) } private fun flipY(start: Position): Position { return Position(start.x, start.sizeY - 1 - start.y, start.sizeX, start.sizeY) } private fun rotate(start: Position): Position { return Position(start.sizeY - 1 - start.y, start.x, start.sizeY, start.sizeX) } data class Position(val x: Int, val y: Int, val sizeX: Int, val sizeY: Int) { fun next(): Position? { if (x == sizeX - 1) { return if (y == sizeY - 1) null else Position(0, y + 1, sizeX, sizeY) } return Position(this.x + 1, this.y, this.sizeX, this.sizeY) } fun transform(transformation: Transformation): Position { return transformation.transform(this) } } enum class TransformationType(val transforming: (Position) -> Position, val reverse: (Position) -> Position) { FLIP_X(::flipX, ::flipX), FLIP_Y(::flipY, ::flipY), ROTATE(::rotate, { start -> rotate(rotate(rotate(start))) }), ; } enum class Transformation(private val transformations: List<TransformationType>) { NO_CHANGE(listOf()), FLIP_X(listOf(TransformationType.FLIP_X)), FLIP_Y(listOf(TransformationType.FLIP_Y)), ROTATE_90(listOf(TransformationType.ROTATE)), ROTATE_180(listOf(TransformationType.ROTATE, TransformationType.ROTATE)), ROTATE_270(listOf(TransformationType.ROTATE, TransformationType.ROTATE, TransformationType.ROTATE)), ROTATE_90_FLIP_X(listOf(TransformationType.ROTATE, TransformationType.FLIP_X)), ROTATE_90_FLIP_Y(listOf(TransformationType.ROTATE, TransformationType.FLIP_Y)), ; fun transform(position: Position): Position { return transformations.fold(position) { pos, trans -> trans.transforming(pos) } } fun reverseTransform(position: Position): Position { return transformations.reversed().fold(position) { pos, trans -> trans.reverse(pos) } } private val referencePoints = arrayOf( Position(3, 2, 5, 5), Position(4, 0, 5, 5) ) fun apply(transformation: Transformation): Transformation { val simplestTransformation = Transformation.values().filter {result -> referencePoints.all {p -> transformation.transform(this.transform(p)) == result.transform(p) } } return simplestTransformation.single() } } class Map2D<T>(val sizeX: Int, val sizeY: Int, val getter: (x: Int, y: Int) -> T, val setter: (x: Int, y: Int, value: T) -> Unit = {_,_,_->}) { private fun originalPossibleTransformations(): MutableSet<Transformation> { val possibleTransformations = Transformation.values().toMutableSet() if (sizeX != sizeY) { // Rotating 90 or 270 degrees only works if both width or height is the same possibleTransformations.remove(Transformation.ROTATE_90) possibleTransformations.remove(Transformation.ROTATE_270) } return possibleTransformations } fun standardizedTransformation(valueFunction: (T) -> Int): Transformation { // keep a Set<Transformation>, start with all of them // loop through Transformations and find ones with the extremes // the goal is that of all the possible transformations, the result should be the one with the lowest/highest value // start in the possible fields for the target map upper-left corner // then continue, line by line, beginning with increasing X and then increase Y val possibleTransformations = originalPossibleTransformations() var position: Position? = Position(0, 0, sizeX, sizeY) while (possibleTransformations.size > 1 && position != null) { val best = Best<Transformation> { transformation -> val originalPos = transformation.reverseTransform(position!!) val originalT = getter(originalPos.x, originalPos.y) valueFunction(originalT).toDouble() } possibleTransformations.forEach { best.next(it) } possibleTransformations.retainAll(best.getBest()) position = position.next() } val transformation = possibleTransformations.first() // map can be symmetric so don't use .single return transformation } fun symmetryTransformations(equalsFunction: (T, T) -> Boolean): Set<Transformation> { val possibleTransformations = originalPossibleTransformations() return possibleTransformations.filter { transformation -> positions().all { pos -> val other = transformation.transform(pos) equalsFunction(getter(pos.x, pos.y), getter(other.x, other.y)) } }.toSet() } fun transform(transformation: Transformation) { val rotated = Map2DX(sizeX, sizeY) { x, y -> val pos = Position(x, y, sizeX, sizeY) val oldPos = transformation.reverseTransform(pos) getter(oldPos.x, oldPos.y) } (0 until sizeY).forEach {y -> (0 until sizeX).forEach {x -> setter(x, y, rotated.grid[y][x]) } } } fun positions(): Sequence<Position> { return (0 until sizeY).asSequence().flatMap { y -> (0 until sizeX).asSequence().map { x -> Position(x, y, sizeX, sizeY) } } } fun standardize(valueFunction: (T) -> Int) { this.transform(this.standardizedTransformation(valueFunction)) } } interface Map2DPoint<T> { val x: Int val y: Int var value: T fun rangeCheck(map: Map2DX<T>): Map2DPoint<T>? } class Map2DPointImpl<T>( override val x: Int, override val y: Int, private val getter: (x: Int, y: Int) -> T, private val setter: (x: Int, y: Int, value: T) -> Unit ): Map2DPoint<T> { override var value: T get() = getter(x, y) set(value) { setter(x, y, value) } override fun rangeCheck(map: Map2DX<T>): Map2DPoint<T>? { return this.takeUnless { x < 0 || x >= map.sizeX || y < 0 || y >= map.sizeY } } } class Map2DX<T>(val sizeX: Int, val sizeY: Int, val factory: (x: Int, y: Int) -> T) { val grid: MutableList<MutableList<T>> = (0 until sizeY).map { y -> (0 until sizeX).map { x -> factory(x, y) }.toMutableList() }.toMutableList() fun set(x: Int, y: Int, value: T) { grid[y][x] = value } fun get(x: Int, y: Int): T = grid[y][x] fun point(x: Int, y: Int): Map2DPoint<T> { return Map2DPointImpl(x, y, this::get, this::set) } fun point(point: Point): Map2DPoint<T> { return point(point.x, point.y) } fun points(): Iterable<Point> = grid.indices.flatMap { y -> grid[y].indices.map { x -> Point(x, y) } } fun all(): Iterable<Map2DPoint<T>> = points().map { point(it.x, it.y) } fun asMap2D(): Map2D<T> { return Map2D(sizeX, sizeY, { x, y -> grid[y][x] }) {x, y, v -> grid[y][x] = v } } fun standardize(value: (T) -> Int): Map2DX<T> { asMap2D().standardize(value) return this } override fun toString(): String { return "Map2D(grid=$grid)" } }
0
Kotlin
0
0
f1447cca699325a37cc7f02a67fca2aa4e2d12c8
7,365
Server2
MIT License
year2020/day03/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day03/part2/Year2020Day03Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Time to check the rest of the slopes - you need to minimize the probability of a sudden arboreal stop, after all. Determine the number of trees you would encounter if, for each of the following slopes, you start at the top-left corner and traverse the map all the way to the bottom: - Right 1, down 1. - Right 3, down 1. (This is the slope you already checked.) - Right 5, down 1. - Right 7, down 1. - Right 1, down 2. In the above example, these slopes would find 2, 7, 3, 4, and 2 tree(s) respectively; multiplied together, these produce the answer 336. */ package com.curtislb.adventofcode.year2020.day03.part2 import com.curtislb.adventofcode.common.number.Fraction import com.curtislb.adventofcode.common.number.productOf import com.curtislb.adventofcode.year2020.day03.trees.TreeField import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 3, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val file = inputPath.toFile() val field = TreeField(file.readText()) val slopes = listOf( Fraction.valueOf(-1, 1), Fraction.valueOf(-1, 3), Fraction.valueOf(-1, 5), Fraction.valueOf(-1, 7), Fraction.valueOf(-2, 1) ) return slopes.productOf { field.countTreesAlongSlope(it).toLong() } } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,467
AdventOfCode
MIT License
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day23.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle class Day23(val input: Input) : Puzzle() { private val order by lazy { input.string().map { it - '0' - 1 } } override fun part1(): String { val index = createIndex(order, 9) play(index, order[0], 100) return createPart1Result(index, index[0]) } private tailrec fun createPart1Result(index: IntArray, head: Int, acc: String = ""): String = if (head == 0) acc else createPart1Result(index, index[head], acc + (head + 1)) override fun part2(): Long { val index = createIndex(order, 1_000_000) play(index, order[0], 10_000_000) return (index[0].toLong() + 1) * (index[index[0]].toLong() + 1) } private fun createIndex(initialCups: List<Int>, size: Int): IntArray { val allCups = IntArray(size) { index -> if (index < initialCups.size) initialCups[index] else index } val result = IntArray(size) allCups.forEachIndexed { index, label -> result[label] = allCups[(index + 1) % allCups.size] } return result } private fun play(index: IntArray, first: Int, turns: Int) { fun previousLabel(label: Int) = (label + index.size - 1) % index.size var current = first repeat(turns) { val pick1 = index[current] val pick2 = index[pick1] val pick3 = index[pick2] var destinationLabel = previousLabel(current) while (pick1 == destinationLabel || pick2 == destinationLabel || pick3 == destinationLabel) { destinationLabel = previousLabel(destinationLabel) } val old = index[destinationLabel] index[destinationLabel] = pick1 index[current] = index[pick3] index[pick3] = old current = index[current] } } }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
1,962
adventofcode-kotlin
MIT License
src/Day05.kt
peterphmikkelsen
573,069,935
false
{"Kotlin": 7834}
fun main() { val stacks = mutableListOf( ArrayDeque(listOf('T', 'D', 'W', 'Z', 'V', 'P')), ArrayDeque(listOf('L', 'S', 'W', 'V', 'F', 'J', 'D')), ArrayDeque(listOf('Z', 'M', 'L', 'S', 'V', 'T', 'B', 'H')), ArrayDeque(listOf('R', 'S', 'J')), ArrayDeque(listOf('C', 'Z', 'B', 'G', 'F', 'M', 'L', 'W')), ArrayDeque(listOf('Q', 'W', 'V', 'H', 'Z', 'R', 'G', 'B')), ArrayDeque(listOf('V', 'J', 'P', 'C', 'B', 'D', 'N')), ArrayDeque(listOf('P', 'T', 'B', 'Q')), ArrayDeque(listOf('H', 'G', 'Z', 'R', 'C')), ) fun part1(input: List<String>): String { for (instruction in input) { if (!instruction.contains("move")) continue val (amount, from, to) = instruction.getClearInstructions() repeat(amount) { stacks[to - 1].addLast(stacks[from - 1].removeLast()) } } return buildString { stacks.forEach { this.append(it.last()) } } } fun part2(input: List<String>): String { for (instruction in input) { if (!instruction.contains("move")) continue val (amount, from, to) = instruction.getClearInstructions() val fromStack = stacks[from - 1] val cratesToMove = fromStack.takeLast(amount) repeat(amount) { fromStack.removeLast() } stacks[to - 1].addAll(cratesToMove) } return buildString { stacks.forEach { this.append(it.last()) } } } val input = readInput("Day05") // println(part1(input)) println(part2(input)) } private fun String.getClearInstructions(): Triple<Int, Int, Int> { val (amount, from, to) = "\\d+".toRegex().findAll(this).map { it.value.toInt() }.toList() return Triple(amount, from, to) }
0
Kotlin
0
0
374c421ff8d867a0bdb7e8da2980217c3455ecfd
1,862
aoc-2022
Apache License 2.0
solutions/src/NumberOfEnclaves.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/number-of-enclaves/ */ class NumberOfEnclaves { fun numEnclaves(grid: Array<IntArray>): Int { var numEnclaves = 0 val visited = mutableSetOf<Pair<Int,Int>>() for (i in grid.indices) { for (j in grid[0].indices) { val enclave = dfsEnclave(Pair(i,j),visited,grid) if (enclave != -1) { numEnclaves+=enclave } } } return numEnclaves } private fun dfsEnclave(space: Pair<Int,Int>, visited: MutableSet<Pair<Int,Int>>, grid: Array<IntArray>) : Int { if (visited.contains(space)) { return 0 } if (space.first !in grid.indices || space.second !in grid[0].indices) { return -1 } if (grid[space.first][space.second] == 0) { return 0 } visited.add(space) val moves = listOf( dfsEnclave(Pair(space.first+1,space.second),visited,grid), dfsEnclave(Pair(space.first-1,space.second),visited,grid), dfsEnclave(Pair(space.first,space.second+1),visited,grid), dfsEnclave(Pair(space.first,space.second-1),visited,grid) ) return if (moves.any { it == -1 }) { -1 } else { 1+moves.sum() } } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,389
leetcode-solutions
MIT License
src/main/kotlin/com/ginsberg/advent2016/Day08.kt
tginsberg
74,924,040
false
null
/* * Copyright (c) 2016 by <NAME> */ package com.ginsberg.advent2016 /** * Advent of Code - Day 8: December 8, 2016 * * From http://adventofcode.com/2016/day/8 * */ class Day08(input: List<String>, val height: Int = 6, val width: Int = 50) { private val digits = Regex("""^\D*(\d+)\D*(\d+)\D*$""") private val screen = Array(height) { Array(width, { false }) } init { input.forEach { interpretCommand(it) } } /** * How many pixels should be lit? */ fun solvePart1(): Int = screen.fold(0) { carry, next -> carry + next.count { it } } /** * What code is the screen trying to display? */ fun solvePart2(): String = screen.map { it.map { if (it) "#" else " " }.joinToString("") }.joinToString("\n") // This is all side-effects, ew. fun interpretCommand(command: String) { val (a, b) = getTheDigits(command) when { command.startsWith("rect") -> { (0 until b).forEach { x -> (0 until a).forEach { y -> screen[x][y] = true } } } command.startsWith("rotate row") -> screen[a] = rotate(screen[a], b) command.startsWith("rotate column") -> { val rotated = rotate(colToRow(a), b) (0 until height).forEach { screen[it][a] = rotated[it] } } } } private fun colToRow(col: Int): Array<Boolean> = (0 until height).map { screen[it][col] }.toTypedArray() private fun rotate(row: Array<Boolean>, by: Int): Array<Boolean> = (row.takeLast(by) + row.dropLast(by)).toTypedArray() fun getTheDigits(line: String): Pair<Int, Int> = digits.matchEntire(line)?.destructured?.let { Pair(it.component1().toInt(), it.component2().toInt()) } ?: Pair(0, 0) }
0
Kotlin
0
3
a486b60e1c0f76242b95dd37b51dfa1d50e6b321
1,922
advent-2016-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindLucky.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode private const val MAX_ARR_SIZE = 500 fun interface FindLuckyStrategy { operator fun invoke(arr: IntArray): Int } class FindLuckyStraightForward : FindLuckyStrategy { override operator fun invoke(arr: IntArray): Int { val cnt = IntArray(MAX_ARR_SIZE + 1) for (a in arr) { ++cnt[a] } for (i in MAX_ARR_SIZE downTo 1) { if (cnt[i] == i) { return i } } return -1 } } class FindLuckyMap : FindLuckyStrategy { override operator fun invoke(arr: IntArray): Int { val freq: MutableMap<Int, Int> = HashMap() for (a in arr) { freq[a] = 1 + freq.getOrDefault(a, 0) // Accumulate the occurrence of a. } var ans = -1 for ((key, value) in freq) { if (key == value) { ans = ans.coerceAtLeast(key) } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,573
kotlab
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day21/Common.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day21 internal data class Grid(val grid: List<List<Char>>) { internal fun traverse(maxSteps: Long, useInf: Boolean = false): TraverseResult { var coords = mutableSetOf(findStart()) var steps = 0L while (steps < maxSteps) { val nextCoords = mutableSetOf<Pos>() coords.forEach { nextCoords.addAll( if (useInf) findNextCoordsInf(it) else findNextCoords(it) ) } coords = nextCoords steps++ } return TraverseResult(coords, rows = grid.size.toLong(), cols = grid[0].size.toLong()) } private fun findStart(): Pos { grid.indices.forEach { row -> val col = grid[row].indexOf('S') if (col != -1) return Pos(row.toLong(), col.toLong()) } throw Exception("Cannot find a start, probably an invalid grid") } private fun findNextCoordsInf(pos: Pos): List<Pos> = findCrossCombs(pos) .mapNotNull { if (getInf(it) == '#') null else it } private fun findNextCoords(pos: Pos): List<Pos> = findCrossCombs(pos) .mapNotNull { if (it.row < 0 || it.row >= grid.size || it.col < 0 || it.col >= grid[0].size) null else if (grid[it.row.toInt()][it.col.toInt()] == '#') null else it } private fun getInf(pos: Pos): Char { var row = pos.row.toInt() % grid.size var col = pos.col.toInt() % grid[0].size if (row < 0) row += grid.size if (col < 0) col += grid[0].size return grid[row][col] } private fun findCrossCombs(pos: Pos): Array<Pos> = arrayOf( pos.copy(row = pos.row - 1), pos.copy(row = pos.row + 1), pos.copy(col = pos.col - 1), pos.copy(col = pos.col + 1), ) internal fun print(coords: Collection<Pos>? = null, addSeparator: Boolean = true) { if (addSeparator) println("--------------------") grid.forEachIndexed { row, items -> items.forEachIndexed { col, item -> if (coords != null && coords.contains(Pos(row.toLong(), col.toLong()))) { print('O') } else { print(item) } } println() } } } internal data class TraverseResult( val coords: Set<Pos>, val rows: Long, val cols: Long, ) { val clampedCoords: Set<Pos> = coords.filter { it.row >= 0 && it.col >= 0 && it.row < rows && it.col < cols }.toSet() } internal data class Pos(val row: Long = 0L, val col: Long = 0L) internal fun readInput(testCase: String): Grid { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Cannot read an input, probably it is invalid") val grid = mutableListOf<List<Char>>() while (true) { val rawLine = reader.readLine() ?: break if (rawLine.trim().isEmpty()) continue grid.add(rawLine.trim().toList()) } return Grid(grid) } internal fun findCoeffs(p0: Pos, p1: Pos, p2: Pos): Coeffs { val x1 = p0.row.toDouble() val x2 = p1.row.toDouble() val x3 = p2.row.toDouble() val y1 = p0.col.toDouble() val y2 = p1.col.toDouble() val y3 = p2.col.toDouble() val a = y1 / ((x1 - x2) * (x1 - x3)) + y2 / ((x2 - x1) * (x2 - x3)) + y3 / ((x3 - x1) * (x3 - x2)) val b = (-y1 * (x2 + x3) / ((x1 - x2) * (x1 - x3)) - y2 * (x1 + x3) / ((x2 - x1) * (x2 - x3)) - y3 * (x1 + x2) / ((x3 - x1) * (x3 - x2))) val c = (y1 * x2 * x3 / ((x1 - x2) * (x1 - x3)) + y2 * x1 * x3 / ((x2 - x1) * (x2 - x3)) + y3 * x1 * x2 / ((x3 - x1) * (x3 - x2))) return Coeffs(a, b, c) } data class Coeffs(val a: Double, val b: Double, val c: Double)
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
4,054
advent-of-code-2023
MIT License
core/src/main/kotlin/org/jetbrains/research/kex/state/transformer/Optimizer.kt
Saloed
227,350,941
true
{"Kotlin": 1844577, "Python": 10439, "Java": 5186, "Shell": 168}
package org.jetbrains.research.kex.state.transformer import org.jetbrains.research.kex.state.* import org.jetbrains.research.kex.state.predicate.ConstantPredicate import org.jetbrains.research.kex.state.predicate.EqualityPredicate import org.jetbrains.research.kex.state.predicate.Predicate import org.jetbrains.research.kex.state.term.ConstBoolTerm import org.jetbrains.research.kex.state.term.term object Optimizer : Transformer<Optimizer> { override fun transformChain(ps: ChainState): PredicateState { val base = transform(ps.base) val curr = transform(ps.curr) return when { base.evaluatesToFalse || curr.evaluatesToFalse -> falseState() base.evaluatesToTrue && curr.evaluatesToTrue -> trueState() base.evaluatesToTrue -> curr curr.evaluatesToTrue -> base else -> mergeChain(base, curr) } } override fun transformBasicState(ps: BasicState): PredicateState = when { ps.evaluatesToFalse -> falseState() ps.evaluatesToTrue -> trueState() else -> ps.filterNot { it is ConstantPredicate }.simplify() } override fun transformNegation(ps: NegationState): PredicateState { val nested = transform(ps.predicateState) return when { nested.evaluatesToFalse -> trueState() nested.evaluatesToTrue -> falseState() else -> simplifyNegation(nested) } } private fun simplifyNegation(ps: PredicateState): PredicateState { if (ps !is BasicState) return NegationState(ps) val equalities = ps.predicates.filterIsInstance<EqualityPredicate>() if (equalities != ps.predicates) return NegationState(ps) val boolEqualities = equalities.filter { it.rhv is ConstBoolTerm } if (boolEqualities != ps.predicates) return NegationState(ps) val simplifiedPredicates = boolEqualities.map { val rhv = it.rhv as ConstBoolTerm val newRhv = term { const(!rhv.value) } EqualityPredicate(it.lhv, newRhv, it.type, it.location) } val newState = ChoiceState(simplifiedPredicates.map { it.wrap() }) return transform(newState) } override fun transformChoice(ps: ChoiceState): PredicateState { val choices = ps.choices.map { transform(it) } if (choices.any { it.evaluatesToTrue }) return trueState() val nonFalseChoices = choices.filterNot { it.evaluatesToFalse } if (nonFalseChoices.isEmpty()) return falseState() return mergeChoices(nonFalseChoices) } private fun mergeChain(first: PredicateState, second: PredicateState): PredicateState = when { first is BasicState && second is BasicState -> makeBasic(first.predicates + second.predicates) first is ChainState && first.curr is BasicState && second is BasicState -> { val merged = makeBasic(first.curr.predicates + second.predicates) ChainState(first.base, merged) } first is BasicState && second is ChainState && second.base is BasicState -> { val merged = makeBasic(first.predicates + second.base.predicates) ChainState(merged, second.curr) } else -> ChainState(first, second) } private fun mergeChoices(choices: List<PredicateState>) = when { choices.any { it is ChoiceState } -> choices.flatMap { when (it) { is ChoiceState -> it.choices else -> listOf(it) } } else -> choices }.let { ChoiceState(it) } private fun makeBasic(predicates: List<Predicate>) = BasicState(predicates).simplify() }
1
Kotlin
0
0
6ead750e33c91afafaa7d315a979396b391a5093
3,677
kex
Apache License 2.0
src/Day02.kt
thelmstedt
572,818,960
false
{"Kotlin": 30245}
import java.io.File fun main() { fun part1(file: File) = file .readText() .lineSequence() .map { when (it) { "A X" -> 3 + 1 "A Y" -> 6 + 2 "A Z" -> 0 + 3 "B X" -> 0 + 1 "B Y" -> 3 + 2 "B Z" -> 6 + 3 "C X" -> 6 + 1 "C Y" -> 0 + 2 "C Z" -> 3 + 3 else -> error(it) } } .sum() fun part2(file: File) = file .readText() .lineSequence() .map { when (it) { "A X" -> 3 + 0 "A Y" -> 1 + 3 "A Z" -> 2 + 6 "B X" -> 1 + 0 "B Y" -> 2 + 3 "B Z" -> 3 + 6 "C X" -> 2 + 0 "C Y" -> 3 + 3 "C Z" -> 1 + 6 else -> error(it) } } .sum() println(part1(File("src", "Day02_test.txt"))) println(part1(File("src", "Day02.txt"))) println(part2(File("src", "Day02_test.txt"))) println(part2(File("src", "Day02.txt"))) }
0
Kotlin
0
0
e98cd2054c1fe5891494d8a042cf5504014078d3
1,168
advent2022
Apache License 2.0
src/day4/first/Solution.kt
verwoerd
224,986,977
false
null
package day4.first import tools.timeSolution fun main() = timeSolution { println(isValidPassword(111111)) println(isValidPassword(<PASSWORD>)) println(isValidPassword(123789)) val (min, max) = readLine()!!.split("-").map { it.toInt() } val valid = mutableSetOf<Int>() for (i in min..max) { if (isValidPassword(i)){valid.add(i)} } println("Found possbile passwords in range: ${valid.size}") } fun isValidPassword(number: Int): Boolean = neverDecreases(number) && atleastOneDoubleSequential(number) fun neverDecreases(number: Int) = (number / 100_000 % 10 <= number / 10_000 % 10) && (number / 10_000 % 10 <= number / 1000 % 10) && (number / 1000 % 10 <= number / 100 % 10) && (number / 100 % 10 <= number / 10 % 10) && (number / 10 % 10 <= number % 10) fun atleastOneDoubleSequential(number: Int) =(number / 100_000 % 10 == number / 10_000 % 10) || (number / 10_000 % 10 == number / 1000 % 10) || (number / 1000 % 10 == number / 100 % 10) || (number / 100 % 10 == number / 10 % 10) || (number / 10 % 10 == number % 10)
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
1,075
AoC2019
MIT License
src/main/kotlin/P014_LongestCollatzSequence.kt
perihanmirkelam
291,833,878
false
null
/** * P14-Longest Collatz sequence * The following iterative sequence is defined for the set of positive integers: * n → n/2 (n is even) * n → 3n + 1 (n is odd) * Using the rule above and starting with 13, we generate the following sequence: * 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 * It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. * Which starting number, under one million, produces the longest chain? * NOTE: Once the chain starts the terms are allowed to go above one million. */ fun p14() { var term: Long var termCount: Int var greatestTermCount = 0 var greatest = 0L repeat(1_000_000) { termCount = 1 term = it.toLong() while (term > 1) { term = if (term % 2 == 0L) term / 2 else 3 * term + 1 termCount++ } if(termCount > greatestTermCount) { greatest = it.toLong() greatestTermCount = termCount } } println("A14: $greatest") }
0
Kotlin
1
3
a24ac440871220c87419bfd5938f80dc22a422b2
1,159
ProjectEuler
MIT License
src/main/kotlin/alg03sorting/S3ShellSort.kt
deemson
349,702,470
false
null
package alg03sorting import alg03indexable.Indexable import alg03indexable.swap /** * Shell sort is similar to previous algorithm (S2InsertionSort). * Insertion sort (S2InsertionSort) moves a single item at a time, thus being slow * when sorting an array that requires a lot of swaps. * Shell sort tries to compensate this by gradually sorting the array * in a similar fashion, but with bigger steps (>1). Step is equal to 1 * at the very end of a Shell sorting algorithm, efficiently becoming * an insertion sort when the array is almost sorted. * <p> * The worst-case number of compares used by shell sort with 3x+1 sequence is O(N^1.5). */ object S3ShellSort : Sort { override fun <T> sort(indexable: Indexable<T>, comparator: Comparator<T>) { var step = 1 // Choosing the biggest step < a.length from Knuth's shellsort step sequence (3*x + 1). while (step < indexable.size / 3) { // 1, 4, 13, 40, 121, 364, ... step = 3 * step + 1 } while (step >= 1) { // Make an insertion sort for all of the steps in the sequence. // The outer loop is still incremented by 1 each iteration. for (outerIndex in step until indexable.size) { // However, the inner loop is decremented by 'step'. for (innerIndex in outerIndex downTo step step step) { // We swap (i.e. move items closer to the start of the array) // until the item finds it's place (not less than the item to the left - step). // When step == 1 and all items have found their place, the array is sorted. if (comparator.compare(indexable[innerIndex], indexable[innerIndex - step]) >= 0) { break } indexable.swap(innerIndex, innerIndex - step) } } step /= 3 } } }
0
Kotlin
0
0
a4bba4dfa962302114065032facefdf98585cfd7
1,958
algorithms
MIT License
src/main/kotlin/aoc2020/day8/InfiniteLoop.kt
arnab
75,525,311
false
null
package aoc2020.day8 import java.lang.IllegalArgumentException object InfiniteLoop { data class Program( val instructions: List<Pair<String, Int>>, val currentState: State ) { companion object { fun parse(rawInstructions: String): Program = rawInstructions.split("\n") .map { it.parseInstruction() } .let { instructions -> Program(instructions, State.init()) } } data class State( val currentInstruction: Int, val currentAccumulatedValue: Int, val seenInstructions: Set<Int> ) { companion object { fun init() = State(0,0, emptySet()) } } fun eval(): State = evalSafely(currentState) private fun evalSafely(state: State): State { val allInstructionsProcessed = state.currentInstruction >= this.instructions.size val instructionAlreadyEvaluated = state.seenInstructions.contains(state.currentInstruction) if (allInstructionsProcessed || instructionAlreadyEvaluated) return state val nextState = evalInstruction(this.instructions[state.currentInstruction], state) return evalSafely(nextState) } fun detectAndRepair(): State? { generateAllPossibleInstructions(this.instructions).forEach { instructions -> val program = Program(instructions, State.init()) try { // If we successfully execute the program, we are done! return program.evalAndAbortOnLoops(program.currentState) } catch (e: IllegalArgumentException) { println("Dang... Still failing... Let's try the next set of tweaked instruction") } } return null } private fun generateAllPossibleInstructions( instructions: List<Pair<String, Int>> ): Sequence<List<Pair<String, Int>>> { val allInstructionSets = mutableListOf<List<Pair<String, Int>>>() for (i in instructions.indices) { val (operator, value) = instructions[i] if (operator in listOf("nop", "jmp")) { val newOperator = if (operator == "nop") "jmp" else "nop" instructions.toMutableList() .apply { this[i] = Pair(newOperator, value) } .also { allInstructionSets.add(it) } } } return allInstructionSets.asSequence() } private fun evalAndAbortOnLoops(state: State): State { val instructionAlreadyEvaluated = state.seenInstructions.contains(state.currentInstruction) if (instructionAlreadyEvaluated) { throw IllegalArgumentException("Instr #${state.currentInstruction} already evaluated: ${state.seenInstructions}") } val allInstructionsProcessed = state.currentInstruction >= this.instructions.size if (allInstructionsProcessed) return state val nextState = evalInstruction(this.instructions[state.currentInstruction], state) return evalAndAbortOnLoops(nextState) } private fun evalInstruction(instruction: Pair<String, Int>, state: State): State = instruction.let { (operator, value) -> when(operator) { "nop" -> state.copy( seenInstructions = state.seenInstructions + state.currentInstruction, currentInstruction = state.currentInstruction + 1 ) "acc" -> state.copy( seenInstructions = state.seenInstructions + state.currentInstruction, currentInstruction = state.currentInstruction + 1, currentAccumulatedValue = state.currentAccumulatedValue + value ) "jmp" -> state.copy( seenInstructions = state.seenInstructions + state.currentInstruction, currentInstruction = state.currentInstruction + value ) else -> throw IllegalArgumentException("Unknown operator: $operator") } } } } private fun String.parseInstruction() = this.split(" ").let { (operation, value) -> Pair(operation, value.toInt()) }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
4,442
adventofcode
MIT License
src/day01/Day01.kt
GrinDeN
574,680,300
false
{"Kotlin": 9920}
package day01 import readInput import splitWhen fun main() { fun part1(input: List<String>): Int { val values = input.splitWhen { it == "" } println(values) val calories = values.stream().map { it -> it.sumOf { el -> el.toInt() } }.toList() println(calories) return calories.max() } fun part2(input: List<String>): Int { val values = input.splitWhen { it == "" } println(values) val calories = values.stream().map { it -> it.sumOf { el -> el.toInt() } }.toList().sortedDescending() println(calories) return calories.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f25886a7a3112c330f80ec2a3c25a2ff996d8cf8
876
aoc-2022
Apache License 2.0
src/main/kotlin/day25_sea_cucumber/SeaCucumber.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day25_sea_cucumber /** * It's a torus! */ fun main() { util.solve(386, ::partOne) // util.solve(::partTwo) } private const val OPEN = '.' private const val EAST = '>' private const val SOUTH = 'v' fun partOne(input: String): Int { val width = input.indexOf('\n') var g = input .filter { it != '\n' } .toCharArray() val height = g.size / width var tickCount = 0 while (true) { var moves = 0 var next = g.copyOf() // move east for ((i, c) in g.withIndex()) { if (c != EAST) continue val x = (i % width + 1) % width val y = i / width val j = y * width + x if (g[j] == OPEN) { next[j] = EAST next[i] = OPEN moves++ } } g = next next = g.copyOf() // move south for ((i, c) in g.withIndex()) { if (c != SOUTH) continue val x = i % width val y = (i / width + 1) % height val j = y * width + x if (g[j] == OPEN) { next[j] = SOUTH next[i] = OPEN moves++ } } g = next ++tickCount if (moves == 0) break } return tickCount } fun partTwo(input: String) = input.trim().length
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
1,376
aoc-2021
MIT License
src/main/kotlin/fp/kotlin/example/chapter08/solution/8_17_sequenceTree.kt
funfunStory
101,662,895
false
null
package fp.kotlin.example.chapter08.solution import fp.kotlin.example.chapter04.solution.curried import fp.kotlin.example.chapter08.Node import fp.kotlin.example.chapter08.Tree import fp.kotlin.example.chapter08.apply import fp.kotlin.example.chapter08.pure /** * * 연습문제 8-17 * * Tree 에도 동작하는 ``sequenceA`` 함수를 추가하고 테스트 해보자. * */ fun main() { val treeList: Cons<Node<Int>> = Cons(Node(1), Cons(Node(2), Cons(Node(3), Nil))) require(sequenceA(treeList) == Node(Cons(1, Cons(2, Cons(3, Nil))))) val treeList2: Cons<Node<Int>> = Cons(Node(1, listOf(Node(2), Node(3))), Cons(Node(2), Cons(Node(3), Nil))) require(sequenceA(treeList2) == Node(Cons(1, Cons(2, Cons(3, Nil))), listOf( Node(Cons(2, Cons(2, Cons(3, Nil)))), Node(Cons(3, Cons(2, Cons(3, Nil)))) ) ) ) } private fun <T> cons() = { x: T, xs: FunList<T> -> Cons(x, xs) } private fun <T> sequenceA(treeList: FunList<Node<T>>): Node<FunList<T>> = when (treeList) { Nil -> Node(Nil) is Cons -> Tree.pure(cons<T>().curried()) apply treeList.head apply sequenceA( treeList.tail) }
1
Kotlin
23
39
bb10ea01d9f0e1b02b412305940c1bd270093cb6
1,217
fp-kotlin-example
MIT License
AdventOfCode/Challenge2023Day03.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.test.assertEquals class Challenge2023Day03 { private fun solve1(schema: List<String>): Int { val numberList = mutableListOf<Int>() var formerLine: String? = null var currentLine: String var nextLine: String? val nummerRegex = Regex("(\\d+)") for (lineNumber in schema.indices) { if (lineNumber > 0) { formerLine = schema[lineNumber - 1] } currentLine = schema[lineNumber] nextLine = if (schema.last() == schema[lineNumber]) { null } else { schema[lineNumber + 1] } nummerRegex.findAll(currentLine).forEach { match -> val startIndex = match.range.first val endIndex = match.range.last if (isNextToSymbol(formerLine, currentLine, nextLine, Pair(startIndex, endIndex))) { numberList.add(match.value.toInt()) } } } return numberList.sum() } private fun isNextToSymbol( formerLine: String?, currentLine: String, nextLine: String?, positionToCheck: Pair<Int, Int>, ): Boolean { val beginPointer = if (positionToCheck.first - 1 >= 0) positionToCheck.first - 1 else 0 val endPointer = if (positionToCheck.second + 1 <= currentLine.length) positionToCheck.second + 1 else currentLine.length val subSequenceEndPointer = if (endPointer + 1 <= currentLine.length) endPointer + 1 else currentLine.length if (formerLine != null) { for (char in formerLine.subSequence(beginPointer, subSequenceEndPointer)) { if (char.isSymbol()) return true } } if (beginPointer > 0 && currentLine[positionToCheck.first - 1].isSymbol()) return true if (endPointer < currentLine.length && currentLine[positionToCheck.second + 1].isSymbol()) return true if (nextLine != null) { for (char in nextLine.subSequence(beginPointer, subSequenceEndPointer)) { if (char.isSymbol()) return true } } return false } private fun Char.isSymbol(): Boolean { return (this != '.' && !this.isLetterOrDigit()) } @Test fun test() { val lines = File("./AdventOfCode/Data/Day03-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution1 = solve1(lines) println("Example solution 1: $exampleSolution1") assertEquals(4361, exampleSolution1) val linesReal = File("./AdventOfCode/Data/Day03-1-Data.txt").bufferedReader().readLines() val solution1 = solve1(linesReal) println("Solution 1: $solution1") assertEquals(546563, solution1) } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
2,885
KotlinCodeJourney
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfWays.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 /** * 2147. Number of Ways to Divide a Long Corridor * @see <a href="https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/">Source</a> */ fun interface NumberOfWays { operator fun invoke(corridor: String): Int } class NumberOfWaysDP : NumberOfWays { override operator fun invoke(corridor: String): Int { var res: Long = 1 var j: Long = 0 var k: Long = 0 val mod = MOD + 7 for (i in corridor.indices) { if (corridor[i] == 'S') { if (++k > 2 && k % 2 == 1L) res = res * (i - j) % mod j = i.toLong() } } return if (k % 2 == 0L && k > 0) res.toInt() else 0 } companion object { private const val MOD = 1e9.toLong() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,420
kotlab
Apache License 2.0
src/shreckye/coursera/algorithms/Course 3 Programming Assignment #1 Question 1 & 2.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.io.File val filename = args[0] data class Job(val weight: Int, val length: Int) val (numJobs, jobs) = File(filename).inputStream().bufferedReader().use { val numJobs = it.readLine().toInt() val jobs = it.lineSequence().map { it.splitToInts().run { Job(get(0), get(1)) } }.toList() numJobs to jobs } // Schedule jobs and return the sum of weighted completion times fun scheduleJobs(jobs: List<Job>, comparator: Comparator<Job>): Long { val scheduledJobs = jobs.sortedWith(comparator) var completionTime = 0 var sumWeightedCompletionTimes = 0L for (scheduledJob in scheduledJobs) { completionTime += scheduledJob.length sumWeightedCompletionTimes += scheduledJob.weight * completionTime } return sumWeightedCompletionTimes /*// Do the same work in functional programming return scheduledJobs.fold(0 to 0L) { (lastCompletionTime, lastSumWeightedCompletionTimes), (length, weight) -> val completionTime = lastCompletionTime + length completionTime to lastSumWeightedCompletionTimes + weight * completionTime }.second*/ } println( "1. " + scheduleJobs(jobs, compareBy<Job> { it.weight - it.length }.thenBy(Job::weight).reversed()) ) println( "2. " + scheduleJobs(jobs, Comparator<Job> { o1, o2 -> o1.weight * o2.length - o2.weight * o1.length }.reversed()) )
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
1,397
coursera-stanford-algorithms-solutions-kotlin
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions13.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 /** * 机器人在一个矩阵中运动,当机器人当某一个格子的横纵坐标各位的值相加 * 小于等于k时机器人可以进入该格子,求问机器人可以进入多少个格子 */ fun test13() { println(movingCount(5, 10, 10)) println(movingCount(15, 20, 20)) println(movingCount(10, 1, 100)) println(movingCount(10, 1, 10)) println(movingCount(15, 100, 1)) println(movingCount(15, 10, 1)) println(movingCount(12, 1, 1)) } fun movingCount(k: Int, row: Int, col: Int): Int { require(k >= 0 && row >= 0 && col >= 0) { "输入的数据必须全部大于0" } var count = 0 val booleanMatrix = Array<BooleanArray>(row) { BooleanArray(col) { true } } fun check(x: Int, y: Int): Boolean { var number = 0 var indexX = x var indexY = y while (indexX != 0) { number += indexX % 10 indexX /= 10 } while (indexY != 0) { number += indexY % 10 indexY /= 10 } return number <= k } fun find(x: Int, y: Int) { if (!booleanMatrix[x][y]) return if (check(x, y)) { booleanMatrix[x][y] = false count++ if (x < row - 1) { find(x+1, y) } if (x > 0) { find(x-1, y) } if (y < col - 1) { find(x, y+1) } if (y > 0) { find(x, y-1) } } else { booleanMatrix[x][y] = false } } find(0, 0) return count }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,377
Algorithm
Apache License 2.0
src/main/kotlin/d25/D25_1.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d25 import input.Input data class Wire( val v1: String, val v2: String ) fun parseWires(lines: List<String>): List<Wire> { return lines.flatMap { line -> val parts = line.split(": ") val from = parts[0] val toMany = parts[1].split(" ") toMany.map { Wire(from, it) } } } fun findHeaviestConnection(node: String, nodeConnections: Map<String, Set<Pair<String, Int>>>): String { val connections = nodeConnections[node]!! return connections.maxBy { it.second }.first } fun joinNodes( supernode: String, node: String, nodeConnections: MutableMap<String, Set<Pair<String, Int>>>, separator: Char ): String { val newConnections = ( nodeConnections[supernode]!!.filter { it.first != node } + nodeConnections[node]!!.filter { it.first != supernode } ) val joinedNewConnections = mutableSetOf<Pair<String, Int>>() for (i in newConnections.indices) { var joined = false val conn1 = newConnections[i] for (j in (i + 1)..newConnections.lastIndex) { val conn2 = newConnections[j] if (conn1.first == conn2.first) { val newConnection = Pair(conn1.first, conn1.second + conn2.second) joinedNewConnections.add(newConnection) joined = true break } } if (!joined) joinedNewConnections.add(conn1) } val newSupernode = "$supernode$separator$node" nodeConnections[newSupernode] = joinedNewConnections nodeConnections.remove(supernode) nodeConnections.remove(node) nodeConnections.forEach { entry -> val updatedConnections = entry.value .map { conn -> if (conn.first == supernode || conn.first == node) Pair(newSupernode, nodeConnections[newSupernode]!!.first { it.first == entry.key }.second) else conn } .toSet() nodeConnections[entry.key] = updatedConnections } return newSupernode } fun findCut(nodeConnections: Map<String, Set<Pair<String, Int>>>): Triple<String, String, Int> { val mutableNodeConnections = nodeConnections.toMutableMap() var supernode = mutableNodeConnections.keys.first() while (mutableNodeConnections.size > 2) { val heaviestConnectedNode = findHeaviestConnection(supernode, mutableNodeConnections) supernode = joinNodes(supernode, heaviestConnectedNode, mutableNodeConnections, ',') } return Triple( supernode, mutableNodeConnections.keys.first { it != supernode }, mutableNodeConnections[supernode]!!.first().second ) } fun getStartingNodeConnections(wires: List<Wire>): Map<String, Set<Pair<String, Int>>> { val rawNodes = wires.flatMap { listOf(it.v1, it.v2) }.toSet() val nodeConnections = mutableMapOf<String, Set<Pair<String, Int>>>() rawNodes.forEach { node -> val connectedTo = wires.mapNotNull { if (it.v1 == node) it.v2 else if (it.v2 == node) it.v1 else null } nodeConnections[node] = connectedTo.map { Pair(it, 1) }.toSet() } return nodeConnections } fun getCorrectCut(startingNodeConnections: Map<String, Set<Pair<String, Int>>>): Pair<String, String>? { val nodeConnections = startingNodeConnections.toMutableMap() while (nodeConnections.size > 1) { val minCut = findCut(nodeConnections) val node1 = nodeConnections.keys.first { minCut.first.endsWith(it) } val node2 = nodeConnections.keys.first { minCut.second.endsWith(it) } joinNodes(node1, node2, nodeConnections, '-') if (minCut.third == 3) { return Pair(minCut.first, minCut.second) } } return null } fun main() { val lines = Input.read("input.txt") val wires = parseWires(lines) val nodeConnections = getStartingNodeConnections(wires) val correctCut = getCorrectCut(nodeConnections) if (correctCut == null) { println("No solution found") return } println( correctCut.first.split(",", "-").size * correctCut.second.split(",", "-").size ) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
4,262
aoc2023-kotlin
MIT License
Retos/Reto #2 - EL PARTIDO DE TENIS [Media]/kotlin/nlarrea.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
/* * Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado. * El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien * gane cada punto del juego. * * - Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja. * - Ante la secuencia [P1, P1, P2, P2, P1, P2, P1, P1], el programa mostraría lo siguiente: * 15 - Love * 30 - Love * 30 - 15 * 30 - 30 * 40 - 30 * Deuce * Ventaja P1 * Ha ganado el P1 * - Si quieres, puedes controlar errores en la entrada de datos. * - Consulta las reglas del juego si tienes dudas sobre el sistema de puntos. */ fun main() { tennisMatch(listOf("P1", "P1", "P2", "P2", "P1", "P2", "P1", "P1")) tennisMatch(listOf("P1", "P1", "P2", "P2", "P1", "P2", "P1", "P1", "P2")) tennisMatch(listOf("P2", "P3", "P1", "P1", "P2", "P1", "P2", "P2")) tennisMatch(listOf("P2", "P2", "P1", "P1", "P2", "P1", "P2", "P2")) } class Player() { val scores : List<String> = listOf("Love", "15", "30", "40") var score : String = "Love" var value : Int = 0 fun updateScore() { if (this.value < 4) { this.score = scores[this.value] } else { this.score = scores[3] } } } fun tennisMatch(points:List<String>) { val player1 = Player() val player2 = Player() var endMatch:Boolean = false println("\nRESULTADO DEL PARTIDO:\n") for (point in points) { if (endMatch) { println("\nYA HAY GANADOR!\nNo se tendrán en cuenta los puntos restantes!\n") break } if (point == "P1") { player1.value++ player1.updateScore() } else if (point == "P2") { player2.value++ player2.updateScore() } else { println("El dato no es correcto.") return } endMatch = checkWinner(player1, player2) } } fun checkWinner(p1:Player, p2:Player) : Boolean { if (p1.value == 3 && p2.value == 3) { println("Deuce") } else if (p1.value >= 4 || p2.value >= 4) { val pointsDifference : Int = p1.value - p2.value if (pointsDifference == 0) println("Deuce") else if (pointsDifference == 1) println("Ventaja P1") else if (pointsDifference == -1) println("Ventaja P2") else if (pointsDifference >= 2) { println("Ha ganado el P1") return true } else { println("Ha ganado el P2") return true } } else { println(p1.score + " - " + p2.score) } return false }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
2,672
retos-programacion-2023
Apache License 2.0
combinatorics/src/main/kotlin/com/nickperov/stud/combinatorics/experiment/PermutationsCalculatorExperiment.kt
nickperov
327,780,009
false
null
package com.nickperov.stud.combinatorics.experiment import com.nickperov.stud.combinatorics.CombinatorialUtils import java.util.* /** * Test sample to try different approaches to calculate permutations */ object PermutationsCalculatorExperiment { /** * Provides all permutations of the elements in the given array. * recursive implementation, uses array invariant of pre-calculated size * returns array of arrays */ @JvmStatic fun <T> getAllPermutationsV1(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = CombinatorialUtils.CombinationsInvariant(Array(CombinatorialUtils.calculateNumberOfPermutationsInt(elements.size)) { listOf<T>() }, 0) val used = BooleanArray(elements.size) collectAllPermutations(result, used, elements, arrayListOf()) return result.value } private fun <T> collectAllPermutations(result: CombinatorialUtils.CombinationsInvariant<T>, used: BooleanArray, elements: Array<T>, selection: MutableList<T>) { if (selection.size == elements.size) { result.value[result.index] = selection.toList() result.index += 1 } else { for (i in used.indices) { if (!used[i]) { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) collectAllPermutations(result, usedCopy, elements, selectionCopy) } } } } /** * Provides all permutations of the elements in the given array. * recursive implementation, uses list invariant * returns array of arrays * * Default one - look into utils class */ @JvmStatic fun <T> getAllPermutationsV2(elements: Array<T>): Array<List<T>> { return CombinatorialUtils.getAllPermutations(elements) } /** * Provides all permutations of the elements in the given array. * recursive implementation, optimized (reduced number of array copy operations), uses array invariant of pre-calculated size * returns array of arrays */ @JvmStatic fun <T> getAllPermutationsV3(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = CombinatorialUtils.CombinationsInvariant(Array(CombinatorialUtils.calculateNumberOfPermutationsInt(elements.size)) { listOf<T>() }, 0) val used = BooleanArray(elements.size) collectAllPermutations(result, used, elements, arrayListOf(), used.size) return result.value } private fun <T> collectAllPermutations(result: CombinatorialUtils.CombinationsInvariant<T>, used: BooleanArray, elements: Array<T>, selection: MutableList<T>, count: Int) { if (selection.size == elements.size) { result.value[result.index] = selection.toList() result.index += 1 } else { var k = 1 for (i in used.indices) { if (!used[i]) { if (k++ == count) { // Do not copy arrays used[i] = true selection.add(elements[i]) collectAllPermutations(result, used, elements, selection, count - 1) } else { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) collectAllPermutations(result, usedCopy, elements, selectionCopy, count - 1) } } } } } /** * Provides all permutations of the elements in the given array. * non-recursive implementation, optimized (reduced number of array copy operations), uses array of pre-calculated size * returns array of arrays */ @JvmStatic fun <T> getAllPermutationsV4(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = CombinatorialUtils.CombinationsInvariant(Array(CombinatorialUtils.calculateNumberOfPermutationsInt(elements.size)) { listOf<T>() }, 0) val stack: Deque<RecursiveState<T>> = ArrayDeque(elements.size) var state: RecursiveState<T>? = RecursiveState(BooleanArray(elements.size), arrayListOf(), elements.size, 0, 1) stack.push(state) MAIN_LOOP@ while (true) { if (state == null) { break } else { val used = state.used val selection = state.selection val count = state.count var k = state.currCount var i = state.index while (i < elements.size) { if (!used[i]) { if (k++ == count) { // Do not copy arrays used[i] = true selection.add(elements[i]) // Update state index state?.index = i + 1 state?.currCount = k if (selection.size == elements.size) { // Save the result result.value[result.index] = selection.toList() result.index += 1 break } state = RecursiveState(used, selection, count - 1, 0, 1) stack.push(state) continue@MAIN_LOOP } else { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) // Update state index and count state?.index = i + 1 state?.currCount = k state = RecursiveState(usedCopy, selectionCopy, count - 1, 0, 1) stack.push(state) continue@MAIN_LOOP } } i++ // Update state index and count state?.index = i state?.currCount = k } stack.remove() state = stack.peek() } } return result.value } data class RecursiveState<T>(val used: BooleanArray, val selection: MutableList<T>, val count: Int, var index: Int, var currCount: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RecursiveState<*> if (!used.contentEquals(other.used)) return false if (selection != other.selection) return false if (count != other.count) return false if (index != other.index) return false if (currCount != other.currCount) return false return true } override fun hashCode(): Int { var result = used.contentHashCode() result = 31 * result + selection.hashCode() result = 31 * result + count result = 31 * result + index result = 31 * result + currCount return result } } }
0
Kotlin
0
0
6696f5d8bd73ce3a8dfd4200f902e2efe726cc5a
7,809
Algorithms
MIT License
app/src/test/java/com/terencepeh/leetcodepractice/BestTimeToBuyAndSellStock.kt
tieren1
560,012,707
false
{"Kotlin": 26346}
package com.terencepeh.leetcodepractice /** * Created by <NAME> on 7/9/22. */ // o(n2) fun maxProfitBruteForce(prices: IntArray): Int { var maxProfit = 0 for (i in 0 until prices.size - 1) { for (j in i until prices.size) { val profit = prices[j] - prices[i] if (profit > maxProfit) { maxProfit = profit } } } return maxProfit } // O(n) fun maxProfitTwoPointer(prices: IntArray): Int { var left = 0 var right = 1 var maxProfit = 0 while (right < prices.size) { if (prices[left] < prices[right]) { val profit = prices[right] - prices[left] maxProfit = kotlin.math.max(maxProfit, profit) } else { left = right } right += 1 } return maxProfit } fun maxProfit(prices: IntArray): Int { var minPrice = Integer.MAX_VALUE var maxProfit = 0 for (i in prices.indices) { if (prices[i] < minPrice) { minPrice = prices[i] } else { val profit = prices[i] - minPrice maxProfit = kotlin.math.max(maxProfit, profit) } } return maxProfit } fun main() { val input1 = intArrayOf(7, 1, 5, 3, 6, 4) val input2 = intArrayOf(7, 6, 4, 3, 1) println("Prices input1 = ${maxProfitBruteForce(input1)}") println("Prices input2 = ${maxProfitBruteForce(input2)}") println("Prices input1 = ${maxProfitTwoPointer(input1)}") println("Prices input2 = ${maxProfitTwoPointer(input2)}") println("Prices input1 = ${maxProfit(input1)}") println("Prices input2 = ${maxProfit(input2)}") }
0
Kotlin
0
0
427fa2855c01fbc1e85a840d0be381cbb4eec858
1,654
LeetCodePractice
MIT License
18.kt
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
fun main() { val up = Pair(0, -1); val right = Pair(1, 0); val down = Pair(0, 1); val left = Pair(-1, 0) fun move(pos: Pair<Int, Int>, dir: Pair<Int, Int>, n: Int): Pair<Int, Int> = Pair(pos.first + dir.first * n, pos.second + dir.second * n) fun result(len: Long, corners: List<Pair<Int, Int>>): Long { var result: Long = 0 for (i in 1..<(corners.size - 1)) result += corners[i].first.toLong() * (corners[i + 1].second.toLong() - corners[i - 1].second.toLong()) return result / 2 + len / 2 + 1 } var pos = Pair(0, 0); var pos2 = Pair(0, 0) val corners = ArrayList<Pair<Int, Int>>(); val corners2 = ArrayList<Pair<Int, Int>>() var len1 = 0; var len2: Long = 0 corners.add(Pair(0, 0)) corners2.add(Pair(0, 0)) do { val l = readlnOrNull() ?: break; val line = l.split(' ') val n = line[1].toInt() when (line[0][0]) { 'U' -> pos = move(pos, up, n); 'D' -> pos = move(pos, down, n); 'L' -> pos = move(pos, left, n); 'R' -> pos = move(pos, right, n) } corners.add(pos) len1 += n val n2 = line[2].substring(2, 7).toInt(16) when (line[2][7]) { '3' -> pos2 = move(pos2, up, n2); '1' -> pos2 = move(pos2, down, n2); '2' -> pos2 = move(pos2, left, n2); '0' -> pos2 = move(pos2, right, n2) } len2 += n2 corners2.add(pos2) } while (true) println(listOf(result(len1.toLong(), corners), result(len2, corners2))) }
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
1,508
aoc2023
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem848/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem848 /** * LeetCode page: [848. Shifting Letters](https://leetcode.com/problems/shifting-letters/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the length of s and the size of shifts; */ fun shiftingLetters(s: String, shifts: IntArray): String { val netShifts = getFinalNetShifts(shifts) val ans = StringBuilder(s.length) for (index in s.indices) { val shiftedLetter = getShifted(s[index], netShifts[index]) ans.append(shiftedLetter) } return ans.toString() } private fun getFinalNetShifts(shifts: IntArray): IntArray { val netShifts = shifts.clone() netShifts[netShifts.lastIndex] %= 26 for (index in shifts.lastIndex - 1 downTo 0) { netShifts[index] = (netShifts[index] + netShifts[index + 1]) % 26 } return netShifts } private fun getShifted(lowercase: Char, netShift: Int): Char { require(lowercase.isLowerCase() && netShift < 26) val shiftFromA = (lowercase - 'a' + netShift).let { if (it >= 26) it - 26 else it } return 'a' + shiftFromA } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,218
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/de/pgebert/aoc/days/Day10.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day class Day10(input: String? = null) : Day(10, "Pipe Maze", input) { data class Cell( val x: Int, val y: Int, val char: Char, val weight: Int ) data class Point(val x: Int, val y: Int) override fun partOne() = findLoop().maxOf { it.weight } override fun partTwo() = findLoop().countEnclosed() private fun findLoop(): MutableSet<Cell> { val visited = mutableSetOf<Cell>() val queue = ArrayDeque<Cell>() queue += getInitial() while (queue.isNotEmpty()) { val cell = queue.removeFirst() visited.add(cell) val successors = cell.getSuccessors() successors.forEach { successor -> val visitedCell = visited.firstOrNull { it.x == successor.x && it.y == successor.y } if (visitedCell != null) { if (successor.weight < visitedCell.weight) { visited.remove(visitedCell) queue.add(successor) } } else { queue.add(successor) } } } return visited } private fun getInitial(): Cell { for (x in inputList.indices) { for (y in inputList[x].indices) { if (inputList[x][y] == 'S') return Cell(x, y, 'S', 0) } } throw Exception("Can not find start") } private fun Set<Cell>.countEnclosed(): Int { var enclosed = 0 val loop = map { Point(it.x, it.y) } for (x in inputList.indices) { var inside = false for (y in inputList[x].indices) { val current = inputList[x][y] val next = inputList[x].drop(y + 1).firstOrNull { it != '-' } if (Point(x, y) in loop) { if (current == '|' || (current == 'F' && next == 'J') || (current == 'L' && next == '7')) { inside = !inside } } else if (inside) { enclosed++ } } } return enclosed } private fun Cell.getSuccessors(): List<Cell> { val left = inputList[x].getOrNull(y - 1) val right = inputList[x].getOrNull(y + 1) val top = inputList.getOrNull(x - 1)?.get(y) val bottom = inputList.getOrNull(x + 1)?.get(y) return buildList { if (char == 'S') { if (right != null && right in "-J7") add(Cell(x, y + 1, right, weight + 1)) if (left != null && left in "-LF") add(Cell(x, y - 1, left, weight + 1)) if (top != null && top in "|F7") add(Cell(x - 1, y, top, weight + 1)) if (bottom != null && bottom in "|LJ") add(Cell(x + 1, y, bottom, weight + 1)) } else if (char == '|') { if (top != null && top in "|F7") add(Cell(x - 1, y, top, weight + 1)) if (bottom != null && bottom in "|LJ") add(Cell(x + 1, y, bottom, weight + 1)) } else if (char == '-') { if (right != null && right in "-J7") add(Cell(x, y + 1, right, weight + 1)) if (left != null && left in "-LF") add(Cell(x, y - 1, left, weight + 1)) } else if (char == 'L') { if (right != null && right in "-J7") add(Cell(x, y + 1, right, weight + 1)) if (top != null && top in "|F7") add(Cell(x - 1, y, top, weight + 1)) } else if (char == 'J') { if (left != null && left in "-LF") add(Cell(x, y - 1, left, weight + 1)) if (top != null && top in "|F7") add(Cell(x - 1, y, top, weight + 1)) } else if (char == '7') { if (left != null && left in "-LF") add(Cell(x, y - 1, left, weight + 1)) if (bottom != null && bottom in "|LJ") add(Cell(x + 1, y, bottom, weight + 1)) } else if (char == 'F') { if (right != null && right in "-J7") add(Cell(x, y + 1, right, weight + 1)) if (bottom != null && bottom in "|LJ") add(Cell(x + 1, y, bottom, weight + 1)) } } } }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
4,256
advent-of-code-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountConsistentStrings.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 /** * 1684. Count the Number of Consistent Strings * @see <a href="https://leetcode.com/problems/count-the-number-of-consistent-strings/">Source</a> */ fun interface CountConsistentStrings { operator fun invoke(allowed: String, words: Array<String>): Int } class CountConsistentStringsMap : CountConsistentStrings { override operator fun invoke(allowed: String, words: Array<String>): Int { var ans = 0 val map = HashSet<Char>() for (ch in allowed.toCharArray()) { map.add(ch) } var c: Int for (s in words) { c = 0 for (ch in s.toCharArray()) { if (!map.contains(ch)) { c++ } } if (c == 0) { ans++ } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,479
kotlab
Apache License 2.0
src/day11/Day11.kt
tschens95
573,743,557
false
{"Kotlin": 32775}
package day11 import readText fun main() { val inspectingMap = mutableListOf<Int>() fun mapToMonkey(it: String): Monkey { val lines = it.split("\n") val operator = lines[2].split("=")[1].trim().substring(4, 5) val operand = lines[2].split(operator)[1].trim() val operation = if (operand == "old") { when (operator) { "+" -> { i: Int -> i + i } "*" -> { i: Int -> i * i } else -> throw RuntimeException("Error") } } else { val parsedOperand = operand.toInt() when (operator) { "+" -> { i: Int -> i + parsedOperand } "*" -> { i: Int -> i * parsedOperand } else -> throw RuntimeException("Error") } } val test = lines[3].split("divisible by")[1].trim().toInt() val trueMap = lines[4].trim().split(" ")[5].toInt() val falseMap = lines[5].trim().split(" ")[5].toInt() val items = lines[1].trim().split(":")[1].trim().split(",") .map { it.trim().toInt() }.toMutableList() return Monkey( id = lines[0].substring(7, 8).toInt(), items = items, operation = operation, test = { i: Int -> i.mod(test) == 0 }, targetMonkey = { b: Boolean -> if (b) trueMap else falseMap } ) } fun part1(input: List<String>): Int { val monkeys = input.map { mapToMonkey(it) } // init counting map for (i in monkeys.indices) { inspectingMap.add(i, 0) } for (i in 1..20) { for (m in monkeys) { val itemIterator = m.items.iterator() while (itemIterator.hasNext()) { inspectingMap[m.id]++ val item = itemIterator.next() val newItem = m.operation(item) val boredItem = newItem.div(3) val test = m.test(boredItem) monkeys[m.targetMonkey(test)].items.add(boredItem) itemIterator.remove() } } } inspectingMap.sortDescending() println(inspectingMap) return inspectingMap[0] * inspectingMap[1] } val testInput = "Monkey 0:\n" + " Starting items: 79, 98\n" + " Operation: new = old * 19\n" + " Test: divisible by 23\n" + " If true: throw to monkey 2\n" + " If false: throw to monkey 3\n" + "\n" + "Monkey 1:\n" + " Starting items: 54, 65, 75, 74\n" + " Operation: new = old + 6\n" + " Test: divisible by 19\n" + " If true: throw to monkey 2\n" + " If false: throw to monkey 0\n" + "\n" + "Monkey 2:\n" + " Starting items: 79, 60, 97\n" + " Operation: new = old * old\n" + " Test: divisible by 13\n" + " If true: throw to monkey 1\n" + " If false: throw to monkey 3\n" + "\n" + "Monkey 3:\n" + " Starting items: 74\n" + " Operation: new = old + 3\n" + " Test: divisible by 17\n" + " If true: throw to monkey 0\n" + " If false: throw to monkey 1" println(part1(testInput.split("\n\n"))) println(part1(readText("11").split("\r\n\r\n"))) }
0
Kotlin
0
2
9d78a9bcd69abc9f025a6a0bde923f53c2d8b301
3,618
AdventOfCode2022
Apache License 2.0
codeforces/round614/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round614 import kotlin.math.abs fun main() { val (x0, y0, ax, ay, bx, by) = readLongs() val (xs, ys, t) = readLongs() val points = mutableListOf(x0 to y0) while (true) { val (x, y) = ax * points.last().first + bx to ay * points.last().second + by if (xs + ys + t < x + y) break points.add(x to y) } val best = points.indices.mapNotNull { i -> points.indices.mapNotNull { j -> (abs(j - i) + 1).takeIf { dist(xs to ys, points[i]) + dist(points[i], points[j]) <= t } }.maxOrNull() }.maxOrNull() ?: 0 println(best) } private fun dist(a: Pair<Long, Long>, b: Pair<Long, Long>): Long = abs(a.first - b.first) + abs(a.second - b.second) private operator fun <E> List<E>.component6(): E = get(5) private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readLongs() = readStrings().map { it.toLong() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
876
competitions
The Unlicense
src/main/kotlin/g1901_2000/s1960_maximum_product_of_the_length_of_two_palindromic_substrings/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1960_maximum_product_of_the_length_of_two_palindromic_substrings // #Hard #String #Hash_Function #Rolling_Hash // #2023_06_21_Time_247_ms_(100.00%)_Space_37.5_MB_(100.00%) class Solution { fun maxProduct(s: String): Long { val n = s.length if (n == 2) { return 1 } val len = manaCherS(s) val left = LongArray(n) var max = 1 left[0] = max.toLong() for (i in 1..n - 1) { if (len[(i - max - 1 + i) / 2] > max) { max += 2 } left[i] = max.toLong() } max = 1 val right = LongArray(n) right[n - 1] = max.toLong() for (i in n - 2 downTo 0) { if (len[(i + max + 1 + i) / 2] > max) { max += 2 } right[i] = max.toLong() } var res: Long = 1 for (i in 1 until n) { res = Math.max(res, left[i - 1] * right[i]) } return res } private fun manaCherS(s: String): IntArray { val len = s.length val p = IntArray(len) var c = 0 var r = 0 for (i in 0 until len) { val mirror = 2 * c - i if (i < r) { p[i] = Math.min(r - i, p[mirror]) } var a = i + (1 + p[i]) var b = i - (1 + p[i]) while (a < len && b >= 0 && s[a] == s[b]) { p[i]++ a++ b-- } if (i + p[i] > r) { c = i r = i + p[i] } } for (i in 0 until len) { p[i] = 1 + 2 * p[i] } return p } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,723
LeetCode-in-Kotlin
MIT License
src/day_9/kotlin/Day9.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
import kotlin.math.absoluteValue import kotlin.math.sign // AOC Day 9 // Simulating the tail movement is done by storing its relative position to the head. // This enables not having to simulate the head itself and is easier to work with. // So if we want to move the head we actually have to move the tails relative position opposite of the heads direction. class Tail { private var position = Vector2D(x = 0, y = 0) private var positionRelative = Vector2D(x = 0, y = 0) val uniquePositions = mutableSetOf<Vector2D>() fun moveHead(vector: Vector2D): Vector2D { positionRelative += !vector return correct() } private val isTailTouching get() = positionRelative.x.absoluteValue <= 1 && positionRelative.y.absoluteValue <= 1 private val isTailSameRow get() = positionRelative.y == 0 private val isTailSameColnum get() = positionRelative.x == 0 private fun correct(): Vector2D { if (isTailTouching) return Vector2D(x = 0, y = 0) val correctionVector = if (isTailSameRow) { when (positionRelative.x.sign) { +1 -> Vector2D(x = -1, y = 0) -1 -> Vector2D(x = +1, y = 0) else -> throw AssertionError("Tail relative x position sign was neither 1 nor -1") } } else if (isTailSameColnum) { when (positionRelative.y.sign) { +1 -> Vector2D(x = 0, y = -1) -1 -> Vector2D(x = 0, y = +1) else -> throw AssertionError("Tail relative y position sign was neither 1 nor -1") } } else { Vector2D(x = -positionRelative.x.sign, y = -positionRelative.y.sign) } return move(correctionVector) } private fun move(vector: Vector2D): Vector2D { uniquePositions += position position += vector positionRelative += vector uniquePositions += position return vector } } fun part1(motions: List<Vector2D>) { val tail = Tail() motions.forEach { tail.moveHead(it) } val uniquePositionCount = tail.uniquePositions.size println("Part 1: The rope tail visited $uniquePositionCount unique positions") } fun part2(motions: List<Vector2D>) { val tails = List(size = 9) { Tail() } motions.forEach { motion -> var lastMoveVector: Vector2D = motion tails.forEach { tail -> lastMoveVector = tail.moveHead(!lastMoveVector) } } val lastTailUniquePositionCount = tails.last().uniquePositions.size println("Part 2: The rope tail visited $lastTailUniquePositionCount unique positions") } fun main() { val motions = getAOCInput { rawInput -> rawInput.trim().lines().flatMap { line -> val (directionRaw, timesRaw) = line.splitInTwo(" ") val times = timesRaw.toInt() val motion = when (directionRaw) { "U" -> Vector2D(x = 0, y = 1) "D" -> Vector2D(x = 0, y = -1) "R" -> Vector2D(x = 1, y = 0) "L" -> Vector2D(x = -1, y = 0) else -> throw IllegalArgumentException("Invalid direction") } List(size = times) { motion } } } part1(motions) part2(motions) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
3,254
AdventOfCode2022
MIT License
src/Day08.kt
b0n541
571,797,079
false
{"Kotlin": 17810}
fun main() { fun allTreesToTheLeftAreShorter(trees: Array<IntArray>, row: Int, column: Int): Boolean { val treeHeight = trees[row][column] for (i in column - 1 downTo 0) { if (trees[row][i] >= treeHeight) { return false } } return true } fun allTreesToTheRightAreShorter(trees: Array<IntArray>, row: Int, column: Int): Boolean { val treeHeight = trees[row][column] for (i in column + 1 until trees[0].size) { if (trees[row][i] >= treeHeight) { return false } } return true } fun allTreesToTheTopAreShorter(trees: Array<IntArray>, row: Int, column: Int): Boolean { val treeHeight = trees[row][column] for (i in row - 1 downTo 0) { if (trees[i][column] >= treeHeight) { return false } } return true } fun allTreesToTheBottomAreShorter(trees: Array<IntArray>, row: Int, column: Int): Boolean { val treeHeight = trees[row][column] for (i in row + 1 until trees.size) { if (trees[i][column] >= treeHeight) { return false } } return true } fun part1(input: List<String>): Int { val trees = input.map { it.toCharArray().map { treeHeight -> treeHeight.digitToInt() }.toIntArray() }.toTypedArray() var visibleTreesFromOutside = 0 for (row in 1 until input.size - 1) { for (column in 1 until input.first().length - 1) { if (allTreesToTheLeftAreShorter(trees, row, column) || allTreesToTheRightAreShorter(trees, row, column) || allTreesToTheTopAreShorter(trees, row, column) || allTreesToTheBottomAreShorter(trees, row, column) ) { visibleTreesFromOutside++ } } } return visibleTreesFromOutside + 2 * trees.size + 2 * (trees[0].size - 2) } fun visibleTreesToTheLeft(trees: Array<IntArray>, row: Int, column: Int): Int { val treeHeight = trees[row][column] var visibleTrees = 0 for (i in column - 1 downTo 0) { visibleTrees++ if (trees[row][i] >= treeHeight) { break } } return visibleTrees } fun visibleTreesToTheRight(trees: Array<IntArray>, row: Int, column: Int): Int { val treeHeight = trees[row][column] var visibleTrees = 0 for (i in column + 1 until trees[0].size) { visibleTrees++ if (trees[row][i] >= treeHeight) { break } } return visibleTrees } fun visibleTreesToTheTop(trees: Array<IntArray>, row: Int, column: Int): Int { val treeHeight = trees[row][column] var visibleTrees = 0 for (i in row - 1 downTo 0) { visibleTrees++ if (trees[i][column] >= treeHeight) { break } } return visibleTrees } fun visibleTreesToTheBottom(trees: Array<IntArray>, row: Int, column: Int): Int { val treeHeight = trees[row][column] var visibleTrees = 0 for (i in row + 1 until trees.size) { visibleTrees++ if (trees[i][column] >= treeHeight) { break } } return visibleTrees } fun part2(input: List<String>): Int { val trees = input.map { it.toCharArray().map { treeHeight -> treeHeight.digitToInt() }.toIntArray() }.toTypedArray() var maxScenicScore = 0 for (row in 1 until input.size - 1) { for (column in 1 until input.first().length - 1) { val visibleTreesLeft = visibleTreesToTheLeft(trees, row, column) val visibleTreesRight = visibleTreesToTheRight(trees, row, column) val visibleTreesTop = visibleTreesToTheTop(trees, row, column) val visibleTreesBottom = visibleTreesToTheBottom(trees, row, column) val currentScenicScore = visibleTreesLeft * visibleTreesRight * visibleTreesTop * visibleTreesBottom if (currentScenicScore > maxScenicScore) { maxScenicScore = currentScenicScore } } } return maxScenicScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val input = readInput("Day08") val resultTest1 = part1(testInput) println("Test 1: $resultTest1") check(resultTest1 == 21) val resultPart1 = part1(input) println("Part 1: $resultPart1") check(resultPart1 == 1789) val resultTest2 = part2(testInput) println("Test 2: $resultTest2") check(resultTest2 == 8) val resultPart2 = part2(input) println("Part 2: $resultPart2") check(resultPart2 == 314820) }
0
Kotlin
0
0
d451f1aee157fd4d47958dab8a0928a45beb10cf
5,051
advent-of-code-2022
Apache License 2.0
kotlin/1514-path-with-maximum-probability.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}
class Solution { fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double { val adj = HashMap<Int, ArrayList<Pair<Int, Double>>>().apply { for ((i, edge) in edges.withIndex()) { val (u, v) = edge this[u] = getOrDefault(u, ArrayList<Pair<Int, Double>>()).apply { add(v to succProb[i]) } this[v] = getOrDefault(v, ArrayList<Pair<Int, Double>>()).apply { add(u to succProb[i]) } } } val visited = HashSet<Int>() val minHeap = PriorityQueue<Pair<Int, Double>>{ a, b -> if (a.second < b.second) 1 else -1 } with (minHeap) { add(start to 1.0) while (isNotEmpty()) { val (node, currProb) = poll() visited.add(node) if (node == end) return currProb adj[node]?.forEach { if (it.first !in visited) { add(it.first to currProb * it.second) } } } } return 0.0 } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,149
leetcode
MIT License
src/main/kotlin/problems/SubtreeOfAnotherTree.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
package problems import models.TreeNode /** * Leetcode : easy * * Given the roots of two binary trees root and subRoot, return true if * there is a subtree of root with the same structure and node values of * subRoot and false otherwise. * A subtree of a binary tree is a tree that consists of a node in tree * and all of this node's descendants. The tree could also be considered as a * subtree of itself. * * Input: root = [3,4,5,1,2], subRoot = [4,1,2] * Output: true * * Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] * Output: false * * Constraints: * The number of nodes in the root tree is in the range [1, 2000]. * The number of nodes in the subRoot tree is in the range [1, 1000]. * -104 <= root.val <= 104 * -104 <= subRoot.val <= 104 */ object SubtreeOfAnotherTree { fun isSubtree(root: TreeNode<Int>?, subRoot: TreeNode<Int>?): Boolean { if (subRoot == null) return true if (root == null) return false // These above conditions will not happen as per constraints // but written just to give a holistic solution if (sameTree(root, subRoot)) return true // in a tricky corner case maybe the `val`s are same but a subtree of the current node // is same as the other tree e.g, [1,1] & [1] return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) } private fun sameTree(root: TreeNode<Int>?, subRoot: TreeNode<Int>?): Boolean { if (root==null && subRoot==null) return true if ((root!=null && subRoot!=null) && (root.data == subRoot.data)) return sameTree(root.left, subRoot.left) && sameTree(root.right, subRoot.right) // if one of them is null & the other is not then clearly they're not same // so return false return false } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,889
data-structures
MIT License
src/main/kotlin/me/peckb/aoc/_2016/calendar/day08/Day08.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2016.calendar.day08 import me.peckb.aoc._2016.calendar.day08.Day08.Operation.Rect import me.peckb.aoc._2016.calendar.day08.Day08.Operation.RotateColumn import me.peckb.aoc._2016.calendar.day08.Day08.Operation.RotateRow import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day08 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::operation) { input -> val screen = Array(6) { Array(50) { OFF } } screen.applyOperations(input) screen.sumOf { row -> row.count { it == ON } } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::operation) { input -> val screen = Array(6) { Array(50) { OFF } } screen.applyOperations(input) screen.joinToString("\n") { it.joinToString("") } } private fun operation(line: String): Operation { val parts = line.split(" ") when (parts[0]) { "rect" -> return parts[1].split("x").map { it.toInt() }.let { Rect(it.first(), it.last()) } "rotate" -> { val index = parts[2].substringAfter("=").toInt() val count = parts[4].toInt() when (parts[1]) { "column" -> return RotateColumn(index, count) "row" -> return RotateRow(index, count) } } } throw IllegalArgumentException("Unknown Operation: $line") } sealed class Operation { data class Rect(val width: Int, val height: Int) : Operation() data class RotateColumn(val index: Int, val count: Int) : Operation() data class RotateRow(val index: Int, val count: Int) : Operation() } private fun Array<Array<Char>>.applyOperations(input: Sequence<Operation>) { input.forEach { operation -> when (operation) { is Rect -> { repeat(operation.height) { y -> repeat(operation.width) { x -> this[y][x] = ON } } } is RotateColumn -> { val newColumn = Array(this.size) { OFF } repeat(this.size) { y -> val itemToRotate = this[y][operation.index] val newPos = (y + operation.count) % this.size newColumn[newPos] = itemToRotate } newColumn.indices.forEach { y -> this[y][operation.index] = newColumn[y] } } is RotateRow -> { val newRow = Array(this[0].size) { OFF } repeat(this[0].size) { x -> val itemToRotate = this[operation.index][x] val newPos = (x + operation.count) % this[0].size newRow[newPos] = itemToRotate } newRow.indices.forEach { x -> this[operation.index][x] = newRow[x] } } } } } companion object { const val ON = '#' const val OFF = ' ' } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,897
advent-of-code
MIT License
src/main/kotlin/tr/emreone/adventofcode/days/Day11.kt
EmRe-One
434,793,519
false
{"Kotlin": 44202}
package tr.emreone.adventofcode.days object Day11 { class Password(var password: String) { fun incrementPassword() { val length = password.length var index = length - 1 while (index >= 0) { val c = password[index] if (c == 'z') { password = password.substring(0, index) + 'a' + password.substring(index + 1) } else { password = password.substring(0, index) + (c + 1) + password.substring(index + 1) break } index-- } } private fun isValid(): Boolean { // check first: // Passwords may not contain the letters i, o, or l, // as these letters can be mistaken for other characters and are therefore confusing. if (this.password.contains("""(i|o|l)""".toRegex())) { return false } // check second: // Passwords must contain at least two different, non-overlapping pairs of letters, // like aa, bb, or zz. val pairs = this.password .windowed(2) { "${it[0]}${it[1]}" } .filter { it[0] == it[1] } .groupBy { it } if (pairs.size < 2) { return false } // check third: // Passwords must include one increasing straight of at least three letters, // like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. val triple = this.password .windowed(3) .count { (it[0] <= 'x') && (it[0] + 1 == it[1]) && (it[1] + 1 == it[2]) } if (triple == 0) { return false } return true } fun findNextValidPassword() { while(!isValid()) { incrementPassword() } } } fun part1(input: String): String { val pw = Password(input) pw.findNextValidPassword() return pw.password } fun part2(input: String): String { val pw = Password(input) pw.findNextValidPassword() pw.incrementPassword() pw.findNextValidPassword() return pw.password } }
0
Kotlin
0
0
57f6dea222f4f3e97b697b3b0c7af58f01fc4f53
2,404
advent-of-code-2015
Apache License 2.0
src/Day04.kt
marvingrewe
573,069,044
false
{"Kotlin": 6473}
import kotlin.system.measureTimeMillis fun main() { val day = "Day04" fun toRange(it: String) = it.split("-").map(String::toInt).let { (lower, upper) -> lower..upper } fun List<String>.checkRangesFor(rangePredicate: (IntRangePair) -> Boolean) = count { it.split(",").map(::toRange).let { (left, right) -> rangePredicate(left to right) } } fun part1(input: List<String>): Int { return input.checkRangesFor(IntRangePair::rangeContains) } fun part2(input: List<String>): Int { return input.checkRangesFor(IntRangePair::rangeOverlaps) } val testInput = readInput(day + "_test") val input = readInput(day) var result: Any println("Test 1 solved in ${measureTimeMillis { result = part1(testInput) }}ms with result: $result, expected: 2") println("Test 2 solved in ${measureTimeMillis { result = part2(testInput) }}ms with result: $result, expected: 4") println("Part 1 solved in ${measureTimeMillis { result = part1(input) }}ms with result: $result") println("Part 2 solved in ${measureTimeMillis { result = part2(input) }}ms with result: $result") }
0
Kotlin
0
0
adec59f236b5f92cfcaf9e595fb913bf0010ac41
1,137
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day24/Day24ImmuneSystemSimulator.kt
Zordid
160,908,640
false
null
package day24 import shared.extractAllInts import shared.measureRuntime import shared.readPuzzle enum class OpponentType(private val s: String) { ImmuneSystem("Immune System"), Infection("Infection"); override fun toString() = s } data class ImmuneGroup( val type: OpponentType, val id: Int, val initialUnits: Int, val hitPoints: Int, val attackDamage: Int, val attackType: String, val immunities: Set<String>, val weaknesses: Set<String>, val initiative: Int ) { val name = "$type group $id" fun boostedBy(boost: Int) = copy(attackDamage = attackDamage + boost) companion object { private val weakRegex = Regex("weak to (\\w+[\\w, ]*)") private val immunityRegex = Regex("immune to (\\w+[\\w, ]*)") private val attackTypeRegex = Regex("does \\d+ (\\w+) damage") fun fromString(s: String, type: OpponentType, id: Int): ImmuneGroup { val (units, hitPoints, attackDamage, initiative) = s.extractAllInts().toList() val weaknesses = weakRegex.findAll(s) .map { it.groupValues[1] }.singleOrNull()?.split(", ")?.toSet() val immunities = immunityRegex.findAll(s) .map { it.groupValues[1] }.singleOrNull()?.split(", ")?.toSet() val attackType = attackTypeRegex.findAll(s) .map { it.groupValues[1] }.single() return ImmuneGroup( type, id, units, hitPoints, attackDamage, attackType, immunities ?: emptySet(), weaknesses ?: emptySet(), initiative ) } } } fun extractArmy(puzzle: List<String>, type: OpponentType) = puzzle.dropWhile { it != "$type:" }.drop(1).takeWhile { it.isNotEmpty() } .mapIndexed { idx, l -> ImmuneGroup.fromString(l, type, idx + 1) } class ImmuneSystemSimulator( immuneSystem: List<ImmuneGroup>, infection: List<ImmuneGroup>, immuneBoost: Int = 0, private val verbose: Boolean = false ) { private val all = immuneSystem.map { it.boostedBy(immuneBoost) } + infection private val groupsWithUnits = mutableMapOf<ImmuneGroup, Int>() private val ImmuneGroup.units: Int get() = groupsWithUnits[this] ?: initialUnits private val ImmuneGroup.effectivePower: Int get() = units * attackDamage private val ImmuneGroup.isAlive: Boolean get() = units > 0 private val targetComparator = compareBy<Map.Entry<ImmuneGroup, Int>>( { it.value }, { it.key.effectivePower }, { it.key.initiative }).reversed()!! private fun ImmuneGroup.chooseTarget(potentialTargets: List<ImmuneGroup>) = potentialTargets .associateWith { attackDamage(it) } .filter { it.value > 0 }.entries .onEach { (target, damage) -> if (verbose) println("$name would deal defending group ${target.id} $damage damage") } .sortedWith(targetComparator) .firstOrNull()?.key private fun ImmuneGroup.attack(target: ImmuneGroup) { val damage = attackDamage(target) val unitsLost = damage / target.hitPoints if (verbose) println("$name attacks defending group ${target.id} killing $unitsLost units") groupsWithUnits[target] = target.units - unitsLost } private fun ImmuneGroup.attackDamage(target: ImmuneGroup): Int { val isImmune = target.immunities.contains(attackType) val isWeak = target.weaknesses.contains(attackType) return when { isImmune -> 0 isWeak -> effectivePower * 2 else -> effectivePower } } private val selectionComparator = compareBy<ImmuneGroup>({ it.effectivePower }, { it.initiative }).reversed() private val attackComparator = compareBy<Map.Entry<ImmuneGroup, ImmuneGroup>> { it.key.initiative }.reversed() private val alive: List<ImmuneGroup> get() = all.filter { it.isAlive } private fun targetSelection(): Map<ImmuneGroup, ImmuneGroup> { val attackTargets = mutableMapOf<ImmuneGroup, ImmuneGroup>() alive.sortedWith(selectionComparator).forEach { attacker -> val potentialTargets = alive.filter { (it.type != attacker.type) && !attackTargets.values.contains(it) } attacker.chooseTarget(potentialTargets)?.also { attackTargets[attacker] = it } } if (verbose) println() return attackTargets } private fun attack(attackTargets: Map<ImmuneGroup, ImmuneGroup>) { attackTargets.entries.sortedWith(attackComparator).forEach { (attacker, target) -> if (attacker.isAlive) { attacker.attack(target) } } } fun fight(): Pair<String, Int> { var statistics = buildStatistics() var round = 1 while (statistics.keys.size > 1) { if (verbose) println("\nRound ${round++}") attack(targetSelection()) val newStats = buildStatistics() if (statistics == newStats) { if (verbose) println("Tie after $round rounds") return "Tie" to 0 } statistics = newStats } val survivor = statistics.keys.single() val remaining = statistics.values.single() if (verbose) println("\n$survivor wins with $remaining remaining units after $round rounds") return survivor.toString() to remaining } private fun buildStatistics() = alive.associateBy( { it.type }, { k -> alive.filter { it.type == k.type }.sumOf { it.units } }) } fun part1(puzzle: List<String>, verbose: Boolean = false): Int { val immuneSystem = extractArmy(puzzle, OpponentType.ImmuneSystem) val infection = extractArmy(puzzle, OpponentType.Infection) return ImmuneSystemSimulator(immuneSystem, infection, verbose = verbose).fight().second } fun part2(puzzle: List<String>): Any { val immuneSystem = extractArmy(puzzle, OpponentType.ImmuneSystem) val infection = extractArmy(puzzle, OpponentType.Infection) for (boost in (1..Int.MAX_VALUE)) { val result = ImmuneSystemSimulator(immuneSystem, infection, boost).fight() if (result.first == OpponentType.ImmuneSystem.toString()) { println("Boost $boost was needed!") return result.second } } return "Couldn't find a suitable boostedBy!" } fun main() { val puzzle = readPuzzle(24) measureRuntime { println(part1(puzzle)) println(part2(puzzle)) } }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
6,729
adventofcode-kotlin-2018
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2021/Day13.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 13 - Transparent Origami * Problem Description: http://adventofcode.com/2021/day/13 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day13/ */ package com.ginsberg.advent2021 class Day13(input: List<String>) { private val paper: Set<Point2d> = parsePoints(input) private val instructions: List<Point2d> = parseInstructions(input) fun solvePart1(): Int = paper.crease(instructions.first()).size fun solvePart2(): Unit = instructions.fold(paper) { paper, instruction -> paper.crease(instruction) }.printout() private fun Set<Point2d>.printout() { (0..this.maxOf { it.y }).forEach { y -> (0..this.maxOf { it.x }).forEach { x -> print(if (Point2d(x, y) in this) "#" else " ") } println() } } private fun Set<Point2d>.crease(instruction: Point2d): Set<Point2d> = if (instruction.x != 0) this.map { it.copy(x = it.x.creaseAt(instruction.x)) }.toSet() else this.map { it.copy(y = it.y.creaseAt(instruction.y)) }.toSet() private fun Int.creaseAt(crease: Int): Int = if (this < crease) this else (crease * 2) - this private fun parsePoints(input: List<String>): Set<Point2d> = input.takeWhile { it.isNotEmpty() } .map { it.split(",") } .map { Point2d(it.first().toInt(), it.last().toInt()) } .toSet() private fun parseInstructions(input: List<String>): List<Point2d> = input.takeLastWhile { it.isNotEmpty() } .map { it.split("=") } .map { if (it.first().endsWith("y")) { Point2d(0, it.last().toInt()) } else { Point2d(it.last().toInt(), 0) } } }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,877
advent-2021-kotlin
Apache License 2.0