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
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[41]缺失的第一个正数.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。 //请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。 // // // // 示例 1: // // //输入:nums = [1,2,0] //输出:3 // // // 示例 2: // // //输入:nums = [3,4,-1,1] //输出:2 // // // 示例 3: // // //输入:nums = [7,8,9,11,12] //输出:1 // // // // // 提示: // // // 1 <= nums.length <= 5 * 105 // -231 <= nums[i] <= 231 - 1 // // Related Topics 数组 // 👍 1106 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun firstMissingPositive(nums: IntArray): Int { //算法 原地 Hash [1,N] 区间 // 也就是 遍历一次让 位置 0 存放 1 1存放 2 以此类推 //第二次遍历数组 当前 位置 0 值不等于 0+1 则返回该位置的 index +1 //否则最后返回 数组长度+1 代表最小整数 for( i in nums.indices){ while (nums[i] >= 1 && nums[i] <= nums.size && nums[nums[i]-1] != nums[i]){ //交换到正确的位置 swapNum(nums,i,nums[i]-1) } } //第一次遍历 尽可能排放在正确位置 for (i in nums.indices){ if (nums[i] -1 != i){ return i+1 } } return nums.size+1 } private fun swapNum(nums: IntArray, i: Int, j: Int) { var temp = nums[i] nums[i] = nums[j] nums[j] = temp } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,635
MyLeetCode
Apache License 2.0
src/main/kotlin/_0017_LetterCombinationsOfAPhoneNumber.kt
ryandyoon
664,493,186
false
null
import java.lang.StringBuilder // https://leetcode.com/problems/letter-combinations-of-a-phone-number fun letterCombinations(digits: String): List<String> { val combinations = mutableListOf<String>() val digitToChars = mapOf( '2' to charArrayOf('a', 'b', 'c'), '3' to charArrayOf('d', 'e', 'f'), '4' to charArrayOf('g', 'h', 'i'), '5' to charArrayOf('j', 'k', 'l'), '6' to charArrayOf('m', 'n', 'o'), '7' to charArrayOf('p', 'q', 'r', 's'), '8' to charArrayOf('t', 'u', 'v'), '9' to charArrayOf('w', 'x', 'y', 'z') ) if (digits.isNotEmpty()) { buildCombinations(digits, 0, StringBuilder(), combinations, digitToChars) } return combinations } private fun buildCombinations( digits: String, index: Int, combination: StringBuilder, combinations: MutableList<String>, digitToChars: Map<Char, CharArray> ) { if (index == digits.length) { combinations.add(combination.toString()) return } for (char in digitToChars.getValue(digits[index])) { combination.append(char) buildCombinations(digits, index + 1, combination, combinations, digitToChars) combination.setLength(combination.length - 1) } }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,263
leetcode-kotlin
MIT License
2021/src/Day09.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
// https://adventofcode.com/2021/day/9 fun main() { class Table(cols: Int, rows: Int, numbers: Array<Int>) { val cols = cols val rows = rows val numbers = numbers fun computeBasins() { val lowPointIndices = computeLowPoints() val basinSizes = mutableListOf<Int>() val basins = mutableListOf<List<Pair<Int, Int>>>() val basinIndices = mutableListOf<Int>() lowPointIndices.forEach { val basin = computeBasin(it) basinSizes.add(basin.size) basins.add(basin.map { indexToPoint(it) }) basinIndices.addAll(basin) } numbers.forEachIndexed { index, v -> if (index % cols == 0) { println("") print("${index / rows }: ") } if (lowPointIndices.contains(index)) { print(" ^$v^ ") } else if (basinIndices.contains(index)) { print(" *$v* ") } else print(" $v ") } println() println("Result: ${basinSizes.sortedDescending().take(3).fold(1) { acc, i -> acc * i }}") } fun computeBasin(index : Int, currentBasin : List<Int> = listOf()) : List<Int> { var newBasin = currentBasin.toMutableList() newBasin.add(index) getNeighbours(index).filter { it.second < 9 }.forEach { if (!newBasin.contains(it.first)) { newBasin = computeBasin(it.first, newBasin).toMutableList() } } return newBasin } fun computeLowPoints() : List<Int> { var result = 0 val lowPointIndices = mutableListOf<Int>() val surelyNotLowPointIndices = mutableMapOf<Int, Boolean>() numbers.forEachIndexed { i, value -> if (surelyNotLowPointIndices.getOrDefault(i, false)) return@forEachIndexed if (value == 0) { lowPointIndices.add(i) result++ getNeighbours(i).forEach { surelyNotLowPointIndices[it.first] = true } return@forEachIndexed } if (value < 9) { val neighbours = getNeighbours(i) if (neighbours.all { it.second > value }) { lowPointIndices.add(i) result += value + 1 neighbours.forEach { surelyNotLowPointIndices[it.first] = true } } } } return lowPointIndices } // Returns list of pairs of <Index, Value> fun getNeighbours(index : Int) : List<Pair<Int, Int>> { val point = indexToPoint(index) val x = point.first val y = point.second return listOf( Pair(x - 1, y), Pair(x + 1, y), Pair(x, y - 1), Pair(x, y + 1) ).filter { it.first >= 0 && it.first < cols && it.second >= 0 && it.second < rows }.map { Pair(pointToIndex(it.first, it.second), get(it.first, it.second)!!) } } fun pointToIndex(x : Int, y : Int) : Int { return y * cols + x } fun indexToPoint(index : Int) : Pair<Int, Int> { return Pair(index % cols, index / cols) } fun get(x : Int, y : Int) : Int? { return numbers.elementAtOrNull(y * cols + x) } } fun part1() { val numbers = mutableListOf<Int>() var cols = -1 var rows = 0 for (line in readInput("Day09")) { cols = line.length rows++ numbers.addAll(line.split("").filter { it.isNotEmpty() }.map { it.toInt() }) } val t = Table(cols, rows, numbers.toTypedArray()) t.computeLowPoints() } fun part2() { val numbers = mutableListOf<Int>() var cols = -1 var rows = 0 for (line in readInput("Day09")) { cols = line.length rows++ numbers.addAll(line.split("").filter { it.isNotEmpty() }.map { it.toInt() }) } val t = Table(cols, rows, numbers.toTypedArray()) t.computeBasins() } part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
3,778
advent-of-code
Apache License 2.0
src/main/kotlin/days/Day15.kt
andilau
433,504,283
false
{"Kotlin": 137815}
package days import java.util.* @AdventOfCodePuzzle( name = "Chiton", url = "https://adventofcode.com/2021/day/15", date = Date(day = 15, year = 2021) ) class Day15(val input: List<String>) : Puzzle { override fun partOne() = SimpleCave.parse(input).totalRisk() override fun partTwo() = ExtendedCave(SimpleCave.parse(input)).totalRisk() private fun Grid.totalRisk( from: Point = Point(0, 0), to: Point = Point(width - 1, height - 1) ): Int { val visited = mutableSetOf<Point>() val queue = PriorityQueue<RiskAtPoint>() queue.add(RiskAtPoint(from, 0)) while (true) { val riskyPoint = queue.remove() if (riskyPoint.point in visited) continue visited.add(riskyPoint.point) if (riskyPoint.point == to) return riskyPoint.risk this.neighborsAt(riskyPoint.point) .forEach { n -> queue.add(RiskAtPoint(n, riskyPoint.risk + this[n])) } } } interface Grid { val width: Int val height: Int operator fun get(at: Point): Int fun neighborsAt(at: Point): List<Point> } data class SimpleCave(val cells: List<List<Int>>) : Grid { override val width get() = cells.first().size override val height get() = cells.size override fun get(at: Point): Int = cells[at.y][at.x] override fun neighborsAt(at: Point) = buildList { if (at.x > 0) add(Point(at.x - 1, at.y)) if (at.y > 0) add(Point(at.x, at.y - 1)) if (at.x < width - 1) add(Point(at.x + 1, at.y)) if (at.y < height - 1) add(Point(at.x, at.y + 1)) } companion object { fun parse(input: List<String>): Grid { val cells = input.map { line -> line.map { it.digitToInt() } } return SimpleCave(cells) } } } data class ExtendedCave(val parent: Grid) : Grid { override val width get() = parent.width * 5 override val height get() = parent.height * 5 override fun get(at: Point): Int { val parentAt = Point(at.x % parent.width, at.y % parent.height) val risk = parent[parentAt] + (at.x / parent.width + at.y / parent.height) return (risk - 1) % 9 + 1 } override fun neighborsAt(at: Point) = buildList { if (at.x > 0) add(Point(at.x - 1, at.y)) if (at.y > 0) add(Point(at.x, at.y - 1)) if (at.x < width - 1) add(Point(at.x + 1, at.y)) if (at.y < height - 1) add(Point(at.x, at.y + 1)) } } data class RiskAtPoint(val point: Point, val risk: Int) : Comparable<RiskAtPoint> { override fun compareTo(other: RiskAtPoint) = risk.compareTo(other.risk) } }
0
Kotlin
0
0
b3f06a73e7d9d207ee3051879b83e92b049a0304
2,833
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/triplets/Triplets.kt
slobanov
200,526,003
false
null
package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.triplets import java.util.* fun triplets(a: IntArray, b: IntArray, c: IntArray): Long { val (aSorted, aSize) = sortUniqueToSize(a) val (bSorted, bSize) = sortUniqueToSize(b) val (cSorted, cSize) = sortUniqueToSize(c) val totalSize = aSize + bSize + cSize var aIndex = 0 var bIndex = 0 var cIndex = 0 var tripletsCnt = 0L while ((aIndex + bIndex + cIndex) < totalSize) { if (bIndex == bSize) break val p = aSorted.getOrMaxValue(aIndex) val q = bSorted.getOrMaxValue(bIndex) val r = cSorted.getOrMaxValue(cIndex) when { (p <= q) && (p <= r) -> aIndex++ (r <= q) && (r <= p) -> cIndex++ else -> { bIndex++ tripletsCnt += aIndex.toLong() * cIndex.toLong() } } } return tripletsCnt } private fun IntArray.getOrMaxValue(index: Int) = if (index < size) get(index) else Int.MAX_VALUE private fun sortUniqueToSize(array: IntArray): Pair<IntArray, Int> { val sortedUnique = array.sorted().distinct().toIntArray() return sortedUnique to sortedUnique.size } fun main() { val scan = Scanner(System.`in`) scan.nextLine().split(" ") fun readIntArray(): IntArray = scan.nextLine().split(" ").map { it.trim().toInt() }.toIntArray() val a = readIntArray() val b = readIntArray() val c = readIntArray() val ans = triplets(a, b, c) println(ans) }
0
Kotlin
0
0
2cfdf851e1a635b811af82d599681b316b5bde7c
1,542
kotlin-hackerrank
MIT License
src/day13/Parser.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day13 import PeekableIterator import peekable import readInput /** * */ class Packets (val data: List<Pair<List<Any>, List<Any>>>) { val unsorted: List<List<Any>> get () { return mutableListOf<List<Any>>().apply { data.forEach { val (a, b) = it add (a) add (b) } } } fun sorted (additional: List<List<Any>> = listOf()): List<List<Any>> { return mutableListOf<List<Any>> ().apply { addAll (unsorted) addAll (additional) }.sortedWith { a, b -> compare (a, b) } } companion object { fun parse (input: String): Packets { val list = mutableListOf<Pair<List<Any>, List<Any>>> () val pairs = input.split ("\n\n") pairs.forEach { val (a, b) = it.split ("\n") list.add (Pair (parsePacket (a), parsePacket (b))) } return Packets (list) } fun parsePacket (str: String): List<Any> { val toker = Tokenizer (str).peekable() return parsePacket (toker) } fun parsePacket (toker: PeekableIterator<Token>): List<Any> { val list = mutableListOf<Any> () var token = toker.next () if (token !is Token.LEFT_BRACKET) { throw IllegalArgumentException ("Unexpected token: $token") } while (true) { token = toker.peek () when (token) { is Token.LEFT_BRACKET -> list.add (parsePacket (toker)) is Token.RIGHT_BRACKET -> { toker.next () break } is Token.NUMBER -> { toker.next () list.add (token.value) } is Token.COMMA -> { toker.next () } } } return list } } } fun loadPackets (example: Boolean): Packets { val input = readInput (13, example) return Packets.parse (input) } fun main (args: Array<String>) { val example = true // Tokenization test val dump = { str: String -> val tokens = Tokenizer (str).asSequence() println ("str\n " + tokens.joinToString(", ")) } val input = readInput (13, example).split ("\n\n") input.forEach { packets -> val (a, b) = packets.split ("\n") dump (a) dump (b) } // Parsing test val dump2 = { str: String -> val packets = Packets.parsePacket (str) println ("$str\n$packets\n---") } input.forEach { packets -> val (a, b) = packets.split ("\n") dump2 (a) dump2 (b) } return } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
2,921
advent_of_code_2022
Apache License 2.0
src/main/kotlin/days/Day11.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days @AdventOfCodePuzzle( name = "Monkey in the Middle", url = "https://adventofcode.com/2022/day/11", date = Date(day = 11, year = 2022) ) class Day11(val input: String) : Puzzle { private val monkeys = input.split("\n\n").map { Monkey.from(it.lines()) } override fun partOne(): Int = monkeys.deepCopy().run(20, 3).twoMostActiveMnkeysInspectedMultiplied().toInt() override fun partTwo(): Long = monkeys.deepCopy().run(10_000, 1).twoMostActiveMnkeysInspectedMultiplied() private fun List<Monkey>.run(times: Int, relief: Int): List<Monkey> { val monkeys = this val lcm = this.map { it.test.toLong() }.let { divisors -> lcm(divisors[0], divisors[1], divisors.drop(2)) } repeat(times) { _ -> for (monkey in monkeys) { with(monkey) { while (true) { val worry = worries.removeFirstOrNull() ?: break inspected++ val opWorry = op(worry) val reducedWorry = if (relief > 1) opWorry / relief else opWorry val modWorry = reducedWorry % lcm val index = if (modWorry % test == 0L) throwTrue else throwFalse monkeys[index].worries.addLast(modWorry) } } } } return monkeys } private fun List<Monkey>.twoMostActiveMnkeysInspectedMultiplied() = map { it.inspected.toLong() }.sortedByDescending { it }.take(2).reduce { a, b -> a * b } private fun List<Monkey>.deepCopy() = map { it.copy(worries = ArrayDeque(it.worries)) } data class Monkey( val id: Int, val worries: ArrayDeque<Long>, val op: (Long) -> Long, val test: Int, val throwTrue: Int, val throwFalse: Int, var inspected: Int = 0 ) { companion object { fun from(it: List<String>): Monkey { assert(it.size == 6) val id = it[0].substringAfter("Monkey ").substringBefore(":").toInt() val worries: ArrayDeque<Long> = it[1].substringAfter("Starting items: ").split(", ").map { it.toLong() }.let { ArrayDeque(it.toList()) } val stringOp = it[2].substringAfter("Operation: new = ") val op: (Long) -> Long = when { stringOp.startsWith("old * old") -> { a -> a * a } stringOp.startsWith("old * ") -> { a -> stringOp.substringAfter("old * ").toLong() * a } stringOp.startsWith("old + ") -> { a -> stringOp.substringAfter("old + ").toLong() + a } else -> error("Input?: $stringOp") } val test = it[3].substringAfter("Test: divisible by ").toInt() val throwTrue = it[4].substringAfter("If true: throw to monkey ").toInt() val throwFalse = it[5].substringAfter("If false: throw to monkey ").toInt() return Monkey(id, worries, op, test, throwTrue, throwFalse) } } } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
3,196
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/Day06.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
// not very efficient but it works for this assignment private fun List<Any>.isUnique(): Boolean { this.forEachIndexed { indexOuter, valueOuter -> this.forEachIndexed { indexInner, valueInner -> if (indexInner != indexOuter && valueInner == valueOuter) return false } } return true } private fun String.firstIndexAfterUniqueStreamOfCharacters(size: Int): Int { val buffer = ArrayDeque<Char>() this.forEachIndexed { index, cur -> if (buffer.size < size) { buffer.addFirst(cur) return@forEachIndexed } if (buffer.isUnique()) { return index } else { buffer.addFirst(cur) buffer.removeLast() } } throw IllegalArgumentException("No unique stream found") } fun main() { fun part1(input: List<String>): List<Int> { return input.map { signal -> signal.firstIndexAfterUniqueStreamOfCharacters(4) } } fun part2(input: List<String>): List<Int> { return input.map { signal -> signal.firstIndexAfterUniqueStreamOfCharacters(14) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == listOf(7, 5, 6, 10, 11)) check(part2(testInput) == listOf(19, 23, 23, 29, 26)) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
1,472
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/g2801_2900/s2818_apply_operations_to_maximize_score/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2818_apply_operations_to_maximize_score // #Hard #Array #Math #Greedy #Stack #Monotonic_Stack #Number_Theory // #2023_12_06_Time_727_ms_(100.00%)_Space_57.4_MB_(100.00%) import java.util.ArrayDeque import java.util.Deque import java.util.PriorityQueue import kotlin.math.min @Suppress("NAME_SHADOWING") class Solution { fun maximumScore(nums: List<Int?>, k: Int): Int { // count strictly using nums.get(i) as the selected num var k = k val dp = IntArray(nums.size) // [val, index] val pq = PriorityQueue { o1: IntArray, o2: IntArray -> Integer.compare( o2[0], o1[0] ) } val monoStack: Deque<IntArray> = ArrayDeque() dp.fill(1) for (i in 0..nums.size) { var score = Int.MAX_VALUE if (i < nums.size) { score = PRIME_SCORES[nums[i]!!] } // when an element is poped, its right bound is confirmed: (i - left + 1) * (right - i + // 1) while (monoStack.isNotEmpty() && monoStack.peekFirst()[0] < score) { val popIndex = monoStack.pollFirst()[1] val actualRightIndexOfPopedElement = i - 1 dp[popIndex] *= actualRightIndexOfPopedElement - popIndex + 1 } // when an element is pushed, its left bound is confirmed: (i - left + 1) * (right - i + // 1) if (i < nums.size) { val peekIndex = if (monoStack.isEmpty()) -1 else monoStack.peekFirst()[1] val actualLeftIndexOfCurrentElement = peekIndex + 1 dp[i] *= i - actualLeftIndexOfCurrentElement + 1 monoStack.offerFirst(intArrayOf(score, i)) pq.offer(intArrayOf(nums[i]!!, i)) } } var result: Long = 1 while (k > 0) { val pair = pq.poll() val `val` = pair[0] val index = pair[1] val times = min(k.toDouble(), dp[index].toDouble()).toInt() val power = pow(`val`.toLong(), times) result *= power result %= MOD.toLong() k -= times } return result.toInt() } private fun pow(`val`: Long, times: Int): Long { if (times == 1) { return `val` % MOD } val subProblemRes = pow(`val`, times / 2) var third = 1L if (times % 2 == 1) { third = `val` } return subProblemRes * subProblemRes % MOD * third % MOD } companion object { private const val N = 100000 private val PRIME_SCORES = computePrimeScores() private const val MOD = 1000000000 + 7 private fun computePrimeScores(): IntArray { val primeCnt = IntArray(N + 1) for (i in 2..N) { if (primeCnt[i] == 0) { var j = i while (j <= N) { primeCnt[j]++ j += i } } } return primeCnt } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,143
LeetCode-in-Kotlin
MIT License
kotlin/src/main/kotlin/com/tolchev/algo/matrix/200NumberOfIslands.kt
VTolchev
692,559,009
false
{"Kotlin": 53858, "C#": 47939, "Java": 1802}
package com.tolchev.algo.matrix class NumberOfIslands { private val DEFAULT_ISLAND = -1 fun numIslands(grid: Array<CharArray>): Int { var islands = Array<IntArray>(grid.size){ IntArray(grid[0].size){DEFAULT_ISLAND} } var topIsland : Int var leftIsland : Int var islandCount = 0 var groups = LinkedHashMap<Int, Int>() for (row in grid.indices){ for (col in grid[0].indices){ if (grid[row][col] == '0'){ continue } topIsland = if (row ==0) DEFAULT_ISLAND else islands[row-1][col] leftIsland = if (col ==0) DEFAULT_ISLAND else islands[row][col-1] if (topIsland == DEFAULT_ISLAND && leftIsland == DEFAULT_ISLAND){ islands[row][col] = islandCount groups[islandCount] = islandCount islandCount++ } else if (topIsland == DEFAULT_ISLAND && leftIsland != DEFAULT_ISLAND){ islands[row][col] = leftIsland } else if (leftIsland == DEFAULT_ISLAND && topIsland!= DEFAULT_ISLAND){ islands[row][col] = topIsland } else{ if (leftIsland != topIsland ){ val maxIsland = Math.max(leftIsland, topIsland) val minGroup = Math.min(groups[leftIsland]!!, groups[topIsland]!!) islands[row][col] = minGroup groups[maxIsland] = minGroup } else{ islands[row][col] = leftIsland } } } } var correctGroups = arrayListOf<Int>() for (group in groups){ var parentGroup = group.value while (parentGroup != groups[parentGroup]){ parentGroup = groups[parentGroup]!! } correctGroups.add(parentGroup) } return correctGroups.distinct().size } }
0
Kotlin
0
0
c3129f23e4e7ba42b44f9fb4af39a95f4a762550
2,120
algo
MIT License
src/test/kotlin/Day19.kt
FredrikFolkesson
320,692,155
false
null
import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertTrue typealias Rule = Triple<List<Int>, List<Int>, String> class Day19 { @Test fun `test parse rules`() { val rule: Rule = Triple(listOf(4, 1, 5), listOf(), "") assertEquals(mapOf<Int, Rule>(0 to rule), parseRules("0: 4 1 5")) println( parseRules( "0: 4 1 5\n" + "1: 2 3 | 3 2\n" + "2: 4 4 | 5 5\n" + "3: 4 5 | 5 4\n" + "4: \"a\"\n" + "5: \"b\"" ) ) } private fun parseRules(input: String): Map<Int, Rule> { return input.lines().map { val key = it.substringBefore(":").toInt() val value = it.substringAfter(": ") if (value.contains(" | ")) { value.split(" | ")[0] Pair( key, Triple( value.split(" | ")[0].split(" ").map { it.toInt() }, value.split(" | ")[1].split(" ").map { it.toInt() }, "" ) ) } else { if (value.contains("\"")) { Pair(key, Triple(listOf<Int>(), listOf<Int>(), value.replace("\"", ""))) } else { Pair(key, Triple(value.split(" ").map { it.toInt() }, listOf<Int>(), "")) } } }.toMap() } @Test fun `test matching`() { val allRules = parseRules( "0: 4 1 5\n" + "1: 2 3 | 3 2\n" + "2: 4 4 | 5 5\n" + "3: 4 5 | 5 4\n" + "4: \"a\"\n" + "5: \"b\"" ) val rules = allRules.get(0)!! assertTrue(matchesRule("aaaabbb", allRules, rules, listOf())) } @Test fun `test part 1 and 2`() { val fileAsString = readFileAsString("/Users/fredrikfolkesson/git/advent-of-code/inputs/input-day19.txt") // val fileAsString = "0: 4 1 5\n" + // "1: 2 3 | 3 2\n" + // "2: 4 4 | 5 5\n" + // "3: 4 5 | 5 4\n" + // "4: \"a\"\n" + // "5: \"b\"\n\n"+ // "aaaabb\naaabab\nabbabb\nabbbab\naabaab\naabbbb\nabaaab\nababbb" val allRules = parseRules(fileAsString.split("\n\n")[0]) println(allRules) println(fileAsString.split("\n\n")[1] .lines() .count { // matchesRulesNew(it, listOf(allRules[0]!!), allRules) matchesRule(it, allRules, allRules[8]!!, listOf(allRules[11]!!)) }) } // I do not know why this one does not work. private fun matchesRule(input: String, allRules: Map<Int, Rule>, rule: Rule, restOfRules: List<Rule>): Boolean { //Längden 1 är sista gången, då vi har vår sista regel if (input.length == 1) { return restOfRules.isEmpty() && input.first().toString() == rule.third } if (restOfRules.isEmpty()) { return false } if (rule.third.isNotEmpty()) { return if (input.first().toString() == rule.third) { matchesRule(input.drop(1), allRules, restOfRules.first(), restOfRules.drop(1)) } else { false } } val nextRules = rule.first.map { allRules.get(it)!! } + restOfRules val resultOfFirst = matchesRule(input, allRules, nextRules.first(), nextRules.drop(1)) var resultOfSecond = false if (rule.second.isNotEmpty()) { val nextRulesSecond = rule.second.map { allRules.get(it)!! } + restOfRules resultOfSecond = matchesRule(input, allRules, nextRulesSecond.first(), nextRulesSecond.drop(1)) } return resultOfFirst || resultOfSecond } fun matchesRulesNew(msg: String, rules: List<Rule>, allRules: Map<Int, Rule>): Boolean { if (msg.length == 0) { return rules.isEmpty() } if (rules.isEmpty()) { return false } val first = rules.first() if (first.third.isNotEmpty()) { return if (msg.startsWith(first.third)) { matchesRulesNew(msg.drop(1), rules.drop(1), allRules) } else { false } } val resultOfFirst = matchesRulesNew(msg, first.first.map { allRules.get(it)!! } + rules.drop(1), allRules) var resultOfSecond = false if (first.second.isNotEmpty()) { resultOfSecond = matchesRulesNew(msg, first.second.map { allRules.get(it)!! } + rules.drop(1), allRules) } return resultOfFirst || resultOfSecond } }
0
Kotlin
0
0
79a67f88e1fcf950e77459a4f3343353cfc1d48a
4,881
advent-of-code
MIT License
src/Day01.kt
shoebham
573,035,954
false
{"Kotlin": 9305}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var sum =0; var ans:Int=0; val sortedList = mutableListOf<Int>() for(x in input){ println("x="+x) if(x==""){ sum=0; } else{ val num = x.toInt(); sum+=num; ans = max(sum,ans); } } return ans; } fun part2(input: List<String>): Int { var sum =0; var ans:Int=0; var sortedSet = mutableSetOf<Int>() for((i,x) in input.withIndex()){ if(x==""){ ans = max(sum,ans) sortedSet.add(sum) sum=0; } else{ val num = x.toInt(); sum+=num; } } if(input[input.lastIndex-1]==""){ sum=0 sum+=input.last().toInt() sortedSet.add(sum) } val sortedList = sortedSet.sorted() val lastElement= sortedList.last() val lastIndex= sortedList.lastIndexOf(lastElement) ans = lastElement+sortedList.elementAt(lastIndex-1)+sortedList.elementAt(lastIndex-2) return ans; } // test if implementation meets criteria from the description, like: val input = readInput("Day01") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f9f0e0540c599a8661bb2354ef27086c06a3c9ab
1,426
advent-of-code-2022
Apache License 2.0
src/Day05.kt
ixtryl
575,312,836
false
null
import java.util.* object DAY05 { fun run(fileName: String, crane: Crane): String { val lines = readInput(fileName) val stacks: MutableMap<Int, MutableList<Char>> = getInitialStacks(lines) val operations: List<Operation> = getOperations(lines) val finalStacks = crane.build(stacks, operations) var result = ""; finalStacks.values.forEach { print(it[0]) } println() finalStacks.values.forEach { result += it[0] } return result } private fun getInitialStacks(lines: List<String>): SortedMap<Int, MutableList<Char>> { val stacks: MutableMap<Int, MutableList<Char>> = mutableMapOf() for (line in lines) { if (line.contains("[")) { var currentStack = 1 var currentChar = 1 while (currentChar < line.length) { val box = line[currentChar] if (box.isLetter()) { val stack: MutableList<Char> = stacks.getOrPut(currentStack) { mutableListOf() } stack.add(box) } currentStack++ currentChar += 4 } } } // stacks.toSortedMap().keys.forEach { println(stacks.get(it)) } return stacks.toSortedMap() } private fun getOperations(lines: List<String>): List<Operation> { val operations = mutableListOf<Operation>() for (line in lines) { if (line.startsWith("move")) { val parts = line.split(" ") operations.add( Operation( Integer.parseInt(parts[1]), Integer.parseInt(parts[3]), Integer.parseInt(parts[5]) ) ) } } return operations } interface Crane { fun build( stacks: MutableMap<Int, MutableList<Char>>, operations: List<Operation> ): MutableMap<Int, MutableList<Char>> } class Crane9000() : Crane { override fun build( stacks: MutableMap<Int, MutableList<Char>>, operations: List<Operation> ): MutableMap<Int, MutableList<Char>> { operations.forEach { op -> val source = stacks.getOrPut(op.sourceStack) { mutableListOf() } val target = stacks.getOrPut(op.targetStack) { mutableListOf() } for (i in 1..op.count) { target.add(0, source.removeFirst()) } } return stacks } } class Crane9001() : Crane { override fun build( stacks: MutableMap<Int, MutableList<Char>>, operations: List<Operation> ): MutableMap<Int, MutableList<Char>> { operations.forEach { op -> val source = stacks.getOrPut(op.sourceStack) { mutableListOf() } val target = stacks.getOrPut(op.targetStack) { mutableListOf() } val temp = mutableListOf<Char>() for (i in 1..op.count) { temp.add(0, source.removeFirst()) } for (i in 1..op.count) { target.add(0, temp.removeFirst()) } } return stacks } } class Operation(val count: Int, val sourceStack: Int, val targetStack: Int) } fun main() { if (DAY05.run("Day05", DAY05.Crane9000()) != "ZWHVFWQWW") { throw RuntimeException("Fail: Expected ZWHVFWQWW") } if (DAY05.run("Day05", DAY05.Crane9001()) != "HZFZCCWWV") { throw RuntimeException("Fail: Expected HZFZCCWWV") } }
0
Kotlin
0
0
78fa5f6f85bebe085a26333e3f4d0888e510689c
3,766
advent-of-code-kotlin-2022
Apache License 2.0
src/Day02.kt
BHFDev
572,832,641
false
null
import java.lang.Error fun main() { fun part1(input: List<String>): Int { return input.sumOf {shapes -> val myShape = shapes[2] val opponentsShape = shapes[0] when (myShape) { 'X' -> 1 + when (opponentsShape) { 'C' -> 6 'A' -> 3 else -> 0 } 'Y' -> 2 + when (opponentsShape) { 'A' -> 6 'B' -> 3 else -> 0 } 'Z' -> 3 + when (opponentsShape) { 'B' -> 6 'C' -> 3 else -> 0 } else -> throw Error() } } } fun part2(input: List<String>): Int { return input.sumOf {shapes -> val myShape = shapes[2] val opponentsShape = shapes[0] (when (opponentsShape) { 'A' -> when (myShape) { 'X' -> 3 + 0 'Y' -> 1 + 3 else -> 2 + 6 } 'B' -> when (myShape) { 'X' -> 1 + 0 'Y' -> 2 + 3 else -> 3 + 6 } 'C' -> when (myShape) { 'X' -> 2 + 0 'Y' -> 3 + 3 else -> 1 + 6 } else -> throw Error() }).toInt() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b158069483fa02636804450d9ea2dceab6cf9dd7
1,758
aoc-2022-in-kotlin
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2022/Day11.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals object Day11 : AbstractDay() { @Test fun part1() { assertEquals(10605, part1(testInput)) assertEquals(54036, part1(puzzleInput)) } @Test fun part2() { assertEquals(2713310158, part2(testInput)) assertEquals(13237873355, part2(puzzleInput)) } private fun part1(input: List<String>): Long { return compute(parse(input), 20) { it.floorDiv(3) } } private fun part2(input: List<String>): Long { val monkeys = parse(input) val lcm = monkeys.map { it.divisor }.fold(1L) { acc, i -> acc * i } return compute(parse(input), 10000) { it % lcm } } private fun compute(monkeys: List<Monkey>, rounds: Int, adjustment: Adjustment): Long { repeat(rounds) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.inspections++ item.worryLevel = adjustment(monkey.operation(item.worryLevel)) if (item.worryLevel % monkey.divisor == 0L) { monkeys[monkey.trueMonkey].items.add(item) } else { monkeys[monkey.falseMonkey].items.add(item) } } monkey.items.clear() } } return monkeys.map { it.inspections }.sortedDescending().take(2).reduce(Long::times) } private fun parse(input: List<String>): List<Monkey> { return input.filter { it.isNotBlank() }.chunked(6).map { Monkey.of(it) } } data class Item( var worryLevel: Long, ) class Monkey( val items: MutableList<Item>, val operation: (Long) -> Long, val divisor: Long, val trueMonkey: Int, val falseMonkey: Int, var inspections: Long = 0, ) { companion object { fun of(lines: List<String>): Monkey { val items = extractItems(lines[1]) val operation = extractOperation(lines[2]) val divisor = extractDivisor(lines[3]) val (trueMonkey, falseMonkey) = extractTargetMonkeys(lines[4], lines[5]) return Monkey(items.toMutableList(), operation, divisor, trueMonkey, falseMonkey) } private fun extractItems(s: String): List<Item> { return s.split(": ")[1].split(",").map { it.trim().toLong() }.map { Item(it) } } private fun extractOperation(s: String): (Long) -> Long { val opStr = s.split(" = ")[1].split(" ") val a = opStr[0].toLongOrNull() val b = opStr[2].toLongOrNull() val operation: (Long, Long) -> Long = when (opStr[1]) { "*" -> Long::times "+" -> Long::plus else -> throw IllegalArgumentException() } return { val opA = a ?: it val opB = b ?: it operation(opA, opB) } } private fun extractDivisor(s: String): Long { return s.split(" ").last().toLong() } private fun extractTargetMonkeys(trueMonkey: String, falseMonkey: String): Pair<Int, Int> { return Pair( trueMonkey.split(" ").last().toInt(), falseMonkey.split(" ").last().toInt(), ) } } } } private typealias Adjustment = (Long) -> Long
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
3,677
aoc
Apache License 2.0
2022/src/main/kotlin/de/skyrising/aoc2022/day12/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day12 import de.skyrising.aoc.* private fun parseInput(input: PuzzleInput): Triple<IntGrid, Vec2i, Vec2i> { val height = input.byteLines.size val width = input.byteLines[0].remaining() val data = IntArray(width * height) val grid = IntGrid(width, height, data) var start: Vec2i? = null var end: Vec2i? = null for (y in 0 until height) { val line = input.byteLines[y] for (x in 0 until width) { grid[x, y] = when (line[x].toInt().toChar()) { 'S' -> { start = Vec2i(x, y) 0 } 'E' -> { end = Vec2i(x, y) 25 } else -> line[x] - 'a'.code } } } return Triple(grid, start!!, end!!) } @PuzzleName("Hill Climbing Algorithm") fun PuzzleInput.part1(): Any { val g = Graph<Vec2i, Nothing>() val (grid, start, end) = parseInput(this) grid.forEach { x, y, i -> for (n in Vec2i(x, y).fourNeighbors()) { if (grid.contains(n) && grid[n] <= i + 1) { g.edge(Vec2i(x, y), n, 1) } } } val path = g.dijkstra(start, end) ?: return -1 return path.size } fun PuzzleInput.part2(): Any { val g = Graph<Vec2i, Nothing>() val (grid, _, end) = parseInput(this) grid.forEach { x, y, i -> for (n in Vec2i(x, y).fourNeighbors()) { if (grid.contains(n) && grid[n] <= i + 1) { g.edge(n, Vec2i(x, y), 1) } } } val ends = g.getVertexes().filterTo(mutableSetOf()) { v -> grid[v] == 0 } val path = g.dijkstra(end, ends::contains) ?: return -1 return path.size }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,764
aoc
MIT License
src/Day03.kt
kthun
572,871,866
false
{"Kotlin": 17958}
fun main() { fun Char.characterValue(): Int = when { isLowerCase() -> code - 'a'.code + 1 else -> code - 'A'.code + 27 } fun part1(input: List<String>): Int = input.sumOf { line -> val midPoint = line.length / 2 val compartmentA = line.substring(0, midPoint) val compartmentB = line.substring(midPoint) val match = compartmentA.find { it in compartmentB }!! match.characterValue() } fun part2(input: List<String>): Int = input.chunked(3).sumOf { lines -> val match = lines[0].find { it in lines[1] && it in lines[2] }!! match.characterValue() } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5452702e4e20ef2db3adc8112427c0229ebd1c29
869
aoc-2022
Apache License 2.0
src/Day02_part2.kt
rdbatch02
575,174,840
false
{"Kotlin": 18925}
data class Move_Part2( val points: Int, val beats: String, val losesTo: String ) { companion object { fun rock() = Move_Part2(points = 1, beats = "C", losesTo = "B") fun paper() = Move_Part2(points = 2, beats = "A", losesTo = "C") fun scissors() = Move_Part2(points = 3, beats = "B", losesTo = "A") } } fun main() { val availableMoves: Map<String, Move_Part2> = mapOf( "A" to Move_Part2.rock(), "B" to Move_Part2.paper(), "C" to Move_Part2.scissors() ) fun parseData(input: List<String>): List<Pair<Move_Part2, String>> { return input.map { val round = it.split(" ") Pair(availableMoves[round.first()] ?: throw NotImplementedError(), round.last()) } } fun part2(input: List<String>): Int { val rounds = parseData(input) var totalScore = 0 rounds.forEach { totalScore += when (it.second) { // I need to win "X" -> availableMoves[it.first.beats]?.points ?: throw NotImplementedError() // I need to draw "Y" -> 3 + it.first.points // I need to lose "Z" -> 6 + (availableMoves[it.first.losesTo]?.points ?: throw NotImplementedError()) else -> throw NotImplementedError()// Shouldn't get here, but keeping it for clarity on the above conditions } } return totalScore } val input = readInput("Day02") println("Part 2 - " + part2(input)) }
0
Kotlin
0
1
330a112806536910bafe6b7083aa5de50165f017
1,551
advent-of-code-kt-22
Apache License 2.0
src/Day05.kt
hubikz
573,170,763
false
{"Kotlin": 8506}
import java.io.File fun main() { fun base(input: String, orderTaken: (moved: List<String>) -> List<String>): String { val (creates, moves: String) = input.split("\n\n") val zm = mutableListOf<MutableList<String>>() creates.lines().last().chunked(4).map{ it.trim() }.map { zm.add(mutableListOf()) } creates.lines().take(creates.lines().size-1).map { it.chunked(4).withIndex().map { (index, value ) -> if (value.trim().isNotEmpty()) zm[index].add(value.trim('[', ']', ' ')) } } for (move in moves.lines()) { val result = move.split(" ") val nbr = result[1].toInt() val from = result[3].toInt()-1 val to = result[5].toInt()-1 zm[to].addAll(0, orderTaken(zm[from].take(nbr))) zm[from] = zm[from].drop(nbr).toMutableList() } return zm.joinToString("") { it[0] } } fun part1(input: String): String { return base(input) { orderTaken -> orderTaken.reversed() } } fun part2(input: String): String { return base(input) { orderTaken -> orderTaken } } // test if implementation meets criteria from the description, like: val testInput = File("src/Day05_test.txt").readText() check(part1(testInput) == "CMZ") val input = File("src/Day05.txt").readText() println("Part 1: ${part1(input)}") check(part2(testInput) == "MCD") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
902c6c3e664ad947c38c8edcb7ffd612b10e58fe
1,492
AoC2022
Apache License 2.0
src/Day07.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
private sealed class File { abstract val name: String abstract val size: Long abstract val parentDirectory: Directory } private class Directory( override val name: String, private val parentDirectoryOrNull: Directory? ) : File() { override val parentDirectory: Directory get() = parentDirectoryOrNull!! val files: MutableList<File> = mutableListOf() override val size get() = files.sumOf { it.size } override fun toString(): String { return """ $name (dir) ${files.joinToString("\n") { it.toString() }} """.trimUnevenIndent() } } private class LeafFile( override val name: String, override val size: Long, override val parentDirectory: Directory ): File() { override fun toString(): String { return "$name (file, size=$size)" } } private fun String.isCDInDirection(): Boolean = startsWith("$ cd") && !isCDOutDirection() private fun String.isCDOutDirection(): Boolean = this == "$ cd .." private fun String.isListInstruction(): Boolean = startsWith("$ ls") private fun String.parseFile(parentDirectory: Directory): File { val parts = split(" ") val name = parts[1] return if (parts[0] == "dir") { Directory(name, parentDirectory) } else { val size = parts[0].toLong() LeafFile(name, size, parentDirectory) } } private fun getDirectoryStructure(input: List<String>): Directory { val outerDirectory = Directory("/", null) var currentDirectory: Directory = outerDirectory input.drop(1) // skip first entry since that changes the directory to the outer directory .forEach { if (it.isCDInDirection()) { val directoryName = it.split(" ").last() currentDirectory = currentDirectory.files.first { it.name == directoryName } as Directory return@forEach } if (it.isCDOutDirection()) { currentDirectory = currentDirectory.parentDirectory return@forEach } if (it.isListInstruction()) return@forEach val file = it.parseFile(currentDirectory) currentDirectory.files.add(file) } return outerDirectory } fun main() { fun part1(input: List<String>): Long { val rootDirectory = getDirectoryStructure(input) var totalSize = 0L fun loopThrough(directory: Directory) { val directorySize = directory.size if (directorySize <= 100000) { // println("Add size for directory ${directory.name} ($directorySize)") totalSize += directorySize } directory.files.forEach { if (it is Directory) { loopThrough(it) } } } loopThrough(rootDirectory) return totalSize } fun part2(input: List<String>): Long { val rootDirectory = getDirectoryStructure(input) val totalSpace = 70000000L val requiredSpace = 30000000L val usedSpace = rootDirectory.size val unusedSpace = totalSpace - usedSpace val missingSpace = requiredSpace - unusedSpace var sizeOfDirectoryToDelete = Long.MAX_VALUE fun loopThrough(directory: Directory) { val directorySize = directory.size if (directorySize >= missingSpace) { if (sizeOfDirectoryToDelete > directorySize) { // println("Updated directory to remove: ${directory.name} (frees $directorySize size)") sizeOfDirectoryToDelete = directorySize } } directory.files.forEach { if (it is Directory) { loopThrough(it) } } } loopThrough(rootDirectory) return sizeOfDirectoryToDelete } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
4,261
advent-of-code-2022-kotlin
Apache License 2.0
src/day7/FindSubarrayWithSumK.kt
minielectron
332,678,510
false
{"Java": 127791, "Kotlin": 48336}
package day7 import kotlin.math.min // Problem: You are given with an datastructure.array [1,4,5,3,6,8,4,0,8] // 1. find the subarray of length 3 whose sum is equal to 12. // fixed length problem // 2. find the minimum subarray whose sum is equal to 12. // dynamic window size length problem // 3. find how many subarray whose sum is equal to 12. // dynamic window size length problem fun fixedSizeSubArraySum(arr : IntArray, targetSum : Int) : Int{ var runningSum = 0 val windowSize = 3 for ((index, value) in arr.withIndex()){ runningSum += value if (index >= windowSize-1){ if (runningSum == targetSum) { return index - (windowSize -1) } runningSum -= arr[index - (windowSize -1)] } } return -1 // If no datastructure.array found } fun minimumSubarrayWithTargetSum(arr: IntArray, targetSum: Int) : Int { // returns size of minimum subarray var windowSum = 0 var windowStart = 0 var minSubarraySize = Integer.MAX_VALUE arr.forEachIndexed{ windowEnd, value -> windowSum += value while (windowSum >= targetSum){ if (windowSum == targetSum){ minSubarraySize = min(minSubarraySize, windowEnd - windowStart + 1) } windowSum -= arr[windowStart] windowStart++ } } return minSubarraySize // If no subarray with given sum found } fun howManySubarrayWithSumK(arr: IntArray, targetSum: Int) : Int { // returns size of minimum subarray var windowSum = 0 var windowStart = 0 var count = 0 arr.forEachIndexed{ windowEnd, value -> windowSum += value while (windowSum >= targetSum){ if (windowSum == targetSum){ count++ } windowSum -= arr[windowStart] windowStart++ } } return count // If no subarray with given sum found } fun main(){ val arr = intArrayOf(1,4,5,3,6,8,4,0,8) // case 1: // val index = fixedSizeSubArraySum( arr, 12) // if (index != -1){ // println(arr.slice(index..index+2)) // }else{ // print("No subarray with given sum found.") // } // case 2: // val size = minimumSubarrayWithTargetSum(arr, 8) // if (size == Integer.MAX_VALUE){ // println("No subarray found") // }else{ // print("Size of datastructure.array whose sum is 12 : $size") // } // case 3: println(howManySubarrayWithSumK(arr, 12)) }
0
Java
0
0
f2aaff0a995071d6e188ee19f72b78d07688a672
2,526
data-structure-and-coding-problems
Apache License 2.0
src/main/kotlin/io/dp/UniquePathWithObstacles.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.dp import io.utils.runTests // https://leetcode.com/problems/unique-paths-ii/ class UniquePathWithObstacles { fun execute(input: Array<IntArray>): Int { if (input.isEmpty() || input.first().isEmpty()) return 0 val row = input.size val col = input.first().size val dp = createDpArray(input) initializeFirstColumn(col, dp) initializeFirstRow(row, dp) (1 until row).forEach { r -> (1 until col).forEach { c -> if (dp[r][c] != -1) { val top = dp[r - 1][c].let { if (it > 0) it else 0 } val left = dp[r][c - 1].let { if (it > 0) it else 0 } dp[r][c] = top + left } } } return dp.last().last().let { if (it < 0) 0 else it } } private fun createDpArray(input: Array<IntArray>): Array<IntArray> { return Array(input.size) { r -> IntArray(input.first().size) { c -> when { input[r][c] == 1 -> -1 else -> 0 } } } } private fun initializeFirstColumn(col: Int, dp: Array<IntArray>) { (0 until col).forEach { c -> if (dp.first()[c] != -1 && (c == 0 || dp.first()[c - 1] > 0)) { dp.first()[c] = 1 } } } private fun initializeFirstRow(row: Int, dp: Array<IntArray>) { (0 until row).forEach { r -> if (dp[r].first() != -1 && (r == 0 || dp[r - 1].first() > 0)) { dp[r][0] = 1 } } } } fun main() { runTests(listOf( // arrayOf( // intArrayOf(0, 1, 0, 0, 0), // intArrayOf(0, 0, 0, 1, 0), // intArrayOf(0, 0, 0, 0, 0) // ) to 3, // arrayOf( // intArrayOf(0, 0, 0), // intArrayOf(0, 1, 0), // intArrayOf(0, 0, 0) // ) to 2, arrayOf( intArrayOf(1, 0) ) to 0 )) { (input, value) -> value to UniquePathWithObstacles().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,861
coding
MIT License
AdventOfCodeDay01/src/linuxMain/kotlin/sample/Day01.kt
bdlepla
451,523,596
false
{"Kotlin": 153773}
package sample class Day01(lines: List<String>) { private val data = lines.map{it.toLong()}.sorted().asSequence() fun solvePart1() = getAllPairs(data) .filter{it.first + it.second == 2020L} .map{it.first * it.second} .first() fun solvePart1a() = // data is sorted() and that is the trick to only drop while sum < 2020 data.mapIndexedNotNull { idx, a -> data .drop(idx+1) .dropWhile {a + it < 2020L } .take(1) .firstOrNull{a + it == 2020L} ?.let{a * it} }.first() fun solvePart2() = getAllTriples(data) .filter{it.first + it.second + it.third == 2020L} .map{it.first * it.second * it.third} .first() fun solvePart2a() = data.mapIndexedNotNull { idx, a -> data .drop(idx+1) .mapIndexedNotNull{idx2, b -> data .drop(idx2+1) .dropWhile {a + b + it < 2020L } // this works because data is sorted() .take(1) .firstOrNull{a + b + it == 2020L} ?.let{a * b * it} }.firstOrNull() }.first() companion object { fun getAllPairs(list:Sequence<Long>):Sequence<Pair<Long, Long>> = sequence { val secondList = list.drop(1) if (secondList.count() > 0) { val first = list.first() yieldAll(secondList.map { Pair(first, it) }) yieldAll(getAllPairs(secondList)) } } fun getAllTriples(list:Sequence<Long>):Sequence<Triple<Long, Long, Long>> = sequence { val secondList = list.drop(1) if (secondList.count() > 0) { val first = list.first() yieldAll(getAllPairs(secondList).map{Triple(first, it.first, it.second)}) yieldAll(getAllTriples(secondList)) } } } }
0
Kotlin
0
0
043d0cfe3971c83921a489ded3bd45048f02ce83
2,119
AdventOfCode2020
The Unlicense
markdown/markdown/src/commonMain/kotlin/party/markdown/tree/MutableIntGraph+Cycles.kt
markdown-party
341,117,604
false
{"Kotlin": 619763, "Dockerfile": 723, "JavaScript": 715, "Shell": 646, "HTML": 237, "CSS": 133}
package party.markdown.tree private const val NoRoot = -1 /** Finds the root vertex of this graph, that is a vertex with no parent. */ private fun MutableIntGraph.findRoot(): Int { // Store the number of parents that reference each vertex. val parents = IntArray(size) for (i in 0 until size) { neighboursForEach(i) { parents[it]++ } } // Search for a unique vertex [v] for which parents[v] == 0. var root = NoRoot for (i in 0 until size) { if (parents[i] == 0 && root != NoRoot) return NoRoot if (parents[i] == 0) root = i } return root } /** * Performs an iterative DFS traversal, starting at the [root]. Visited nodes are marked in the * [visited] array. * * If a node is visited twice, this function returns false. It indicates that we are not in a tree. * * @param root the origin of the traversal. * @param visited a vector indicating whether a given node was traversed or not. */ private fun MutableIntGraph.treeDfs(root: Int, visited: BooleanArray): Boolean { val queue = ArrayDeque<Int>().apply { add(root) } while (queue.isNotEmpty()) { val head = queue.removeFirst() if (visited[head]) return false // we may have a DAG, but it's definitely not a tree. visited[head] = true neighboursForEach(head) { n -> queue.addFirst(n) } } return true } /** Returns true iff all the values in this `BooleanArray` are true. */ private fun BooleanArray.allTrue(): Boolean { for (b in this) if (!b) return false return true } /** * An iterative implementation that will check whether the given graph is a tree. The following * steps are performed : * * 1. The root of the tree is found. If it does not exist, return false. * 2. A DFS is performed to check that each node has exactly one parent. If not, return false. * 3. We check if all the nodes were traversed during the DFS. If not, return false. * * @return `true` iff this directed graph is a tree. */ internal fun MutableIntGraph.isTree(): Boolean { // Step 1. val root = findRoot() if (root == NoRoot) return false // Step 2. val visited = BooleanArray(size) val valid = treeDfs(root, visited) if (!valid) return false // Step 3. return visited.allTrue() }
0
Kotlin
3
53
0135c85488873c2e00720353aba3e6b4c0fcc83b
2,214
mono
MIT License
src/Day09_alternative.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
import kotlin.math.abs import kotlin.math.sign class KnotChain(private val id: Int, private var head: KnotChain? = null, private var tail: KnotChain? = null) { private val log = mutableSetOf<Pair<Int, Int>>() private var x = 0 private var y = 0 override fun toString(): String { return "#$id - head: ${head?.id()}, tail: ${tail?.id()}, end: ${tail().id()}" } fun id(): Int = id fun addTail() { val currentTail = tail() currentTail.tail = KnotChain(id + 1, currentTail) } fun tail(): KnotChain { if (tail != null) { return tail!!.tail() } return this } fun move(direction: KnotDirection) { when (direction) { KnotDirection.U -> y += 1 KnotDirection.D -> y -= 1 KnotDirection.R -> x += 1 KnotDirection.L -> x -= 1 } updateLog() tail?.follow() } fun follow() { doFollow() updateLog() tail?.follow() } fun countTailsUniquePositions(): Int { return tail().logCount() } private fun logCount(): Int = log.size private fun doFollow() { if (listOf(abs(head!!.x - x), abs(head!!.y - y)).max() < 2) return if (head!!.x == x) y += (head!!.y - y).sign else if (head!!.y == y) x += (head!!.x - x).sign else { x += (head!!.x - x).sign y += (head!!.y - y).sign } } private fun updateLog() { log.add(x to y) } companion object { fun create(chainLength: Int = 1): KnotChain { val head = KnotChain(0) repeat(chainLength) { head.addTail() } return head } } } enum class KnotDirection() { R, L, U, D } fun main() { fun part1(input: List<String>): Int { val head = KnotChain.create() for (m in input) { val (direction, steps) = m.split(" ") repeat(steps.toInt()) { head.move(KnotDirection.valueOf(direction)) } } return head.countTailsUniquePositions() } fun part2(input: List<String>): Int { val head = KnotChain.create(9) for (m in input) { val (direction, steps) = m.split(" ") repeat(steps.toInt()) { head.move(KnotDirection.valueOf(direction)) } } return head.countTailsUniquePositions() } val input = readInput("Day09") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input)}") check(part1(input) == 6339) check(part2(input) == 2541) }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
2,678
kotlin-advent-of-code-22
Apache License 2.0
src/week1/ThreeSum.kt
anesabml
268,056,512
false
null
package week1 import java.util.* import kotlin.system.measureNanoTime class ThreeSum { /** * Fix the first number and look for the other two by using the two sum algorithm (map) * Time complexity : O(n2) * Space complexity : O(n) */ fun threeSum(nums: IntArray): List<List<Int>> { val map = HashMap<Int, Int>() for (i in nums.indices) { map[nums[i]] = i } val result = mutableSetOf<List<Int>>() for (i in nums.indices) { val sum = 0 - nums[i] for (j in i + 1 until nums.size) { val y = sum - nums[j] if (map.containsKey(y) && map[y] != j && map[y] != i) { result.add(listOf(nums[i], nums[j], y).sorted()) } } } return result.toList() } /** * Fix the first number and look for the other two by using the two sum algorithm * Time complexity : O(n2) * Space complexity : O(1) */ fun threeSum2(nums: IntArray): List<List<Int>> { nums.sort() val result = mutableSetOf<List<Int>>() for (i in 0 until nums.size - 2) { var low = i + 1 var high = nums.size - 1 while (low < high) { val sum = nums[i] + nums[low] + nums[high] when { sum == 0 -> { result.add(listOf(nums[i], nums[low], nums[high])) low++ high-- } sum < 0 -> { low++ } else -> { high-- } } } } return result.toList() } } fun main() { val threeSum = ThreeSum() val input = intArrayOf(-1, 0, 1, 2, -1, -4) val firstSolutionTime = measureNanoTime { println(threeSum.threeSum(input)) } val secondSolutionTime = measureNanoTime { println(threeSum.threeSum2(input)) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
2,186
leetCode
Apache License 2.0
src/Day01.kt
llama-0
574,081,845
false
{"Kotlin": 6422}
fun main() { fun convertInputToInts(input: List<String>): List<Int> { val ints = mutableListOf<Int>() for (i in input) { if (i != "") { ints.add(i.toInt()) } else { ints.add(0) } } return ints } fun updateThreeMax(threeMax: MutableList<Int>, current: Int) { val min = threeMax.min() val index = threeMax.indexOf(min) if (threeMax.contains(0) || current > min) { threeMax[index] = current } } fun part1(input: List<String>): Int { var max = 0 var current = 0 val ints = convertInputToInts(input) for (i in ints) { if (i != 0) { current += i } else { max = maxOf(max, current) current = 0 } } return max } fun part2(input: List<String>): Int { val threeMax = MutableList(3) { 0 } var current = 0 val ints = convertInputToInts(input) for (i in ints) { if (i != 0) { current += i } else { updateThreeMax(threeMax, current) current = 0 } } updateThreeMax(threeMax, current) return threeMax.sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 24000) // check(part2(testInput) == 45000) val input = readInput("Day01") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a3a9a07be54a764a707ab25332a9f324cb84ac2a
1,635
AoC-2022
Apache License 2.0
src/ad/kata/aoc2021/day06/LanternfishPopulation.kt
andrej-dyck
433,401,789
false
{"Kotlin": 161613}
package ad.kata.aoc2021.day06 import ad.kata.aoc2021.PuzzleInput import ad.kata.aoc2021.extensions.plusNotNull import ad.kata.aoc2021.extensions.toIntsSequence import ad.kata.aoc2021.extensions.toMapMerging data class LanternfishPopulation(val state: Map<LanternfishTimer, Amount>) { private constructor(stateEntries: List<Pair<LanternfishTimer, Amount>>) : this(stateEntries.toMapMerging(List<Amount>::sum)) constructor(timers: Sequence<LanternfishTimer>) : this( timers.groupingBy { it }.eachCount().mapValues { Amount(it.value.toLong()) } ) fun totalAmount() = state.values.fold(Amount(0), Amount::plus) fun nextDay() = LanternfishPopulation( state .map { it.key.tick(daysCycle = SEVEN_DAYS) to it.value } .plusNotNull(newLanternfish()) ) private fun newLanternfish() = state[LanternfishTimer.Zero]?.let { amount -> LanternfishTimer(SEVEN_DAYS + 1) to amount } companion object { private const val SEVEN_DAYS = 7 } } fun LanternfishPopulation.simulateDays() = generateSequence(this) { it.nextDay() } fun LanternfishPopulation.afterDays(days: Int) = simulateDays().take(days + 1).last() @JvmInline value class Amount internal constructor(val value: Long) { init { require(value >= 0) } operator fun plus(other: Amount) = Amount(value + other.value) } internal fun List<Amount>.sum() = Amount(sumOf { it.value }) fun lanternfishPopulationFromInput(filename: String) = LanternfishPopulation( PuzzleInput(filename).lines().first() .toIntsSequence() .map { LanternfishTimer(it) } )
0
Kotlin
0
0
28d374fee4178e5944cb51114c1804d0c55d1052
1,663
advent-of-code-2021
MIT License
src/year2022/day09/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day09 import arrow.core.NonEmptyList import arrow.core.nonEmptyListOf import arrow.optics.Lens import arrow.optics.optics import io.kotest.matchers.shouldBe import kotlin.math.sign import utils.Point import utils.neighbors import utils.readInput import utils.x import utils.y fun main() { val testInput = readInput("09", "test_input").asInstructionSequence() val realInput = readInput("09", "input").asInstructionSequence() testInput.computeFinalState(2).visitedPoints.size .also(::println) shouldBe 13 realInput.computeFinalState(2).visitedPoints.size .let(::println) testInput.computeFinalState(10).visitedPoints.size .also(::println) shouldBe 1 realInput.computeFinalState(10).visitedPoints.size .let(::println) } private fun List<String>.asInstructionSequence(): Sequence<Char> { return asSequence() .map { it.split(" ") } .flatMap { (direction, quantity) -> generateSequence { direction.first() } .take(quantity.toInt()) } } private fun Sequence<Char>.computeFinalState(ropeLength: Int): State { val initialState = State( NonEmptyList(Point(), List(ropeLength - 1) { Point() }), emptySet(), ) return fold(initialState) { state, direction -> val newHeadPosition = moveState.getValue(direction)(state) val rope = state.rope.tail.fold(nonEmptyListOf(newHeadPosition)) { rope, oldPosition -> val newPreviousPosition = rope.last() val newPosition = if ( newPreviousPosition in oldPosition.neighbors(includeThis = true, includeDiagonal = true) ) oldPosition else Point( oldPosition.x + (newPreviousPosition.x - oldPosition.x).sign, oldPosition.y + (newPreviousPosition.y - oldPosition.y).sign ) rope + newPosition } State( rope, visitedPoints = state.visitedPoints + rope.last() ) } } @optics data class State( val rope: NonEmptyList<Point>, val visitedPoints: Set<Point>, ) { companion object } private val moveState: Map<Char, (State) -> Point> = buildMap { val newHeadComputation: (Lens<Point, Int>, map: (Int) -> Int) -> (State) -> Point = { lens, transform -> { lens.modify(it.rope.head, transform) } } put('U', newHeadComputation(Point.y, Int::dec)) put('D', newHeadComputation(Point.y, Int::inc)) put('R', newHeadComputation(Point.x, Int::inc)) put('L', newHeadComputation(Point.x, Int::dec)) }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,599
Advent-of-Code
Apache License 2.0
src/Day14.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
fun main() { val input = readInput("Day14") printTime { println(Day14.part1(input)) } printTime { println(Day14.part2(input)) } } class Day14 { companion object { fun part1(input: List<String>): Int { val pointMatrix = input.map { it.split(" -> ").map(::Point) } val points = pointMatrix.flatten() val minX = points.minOf { it.x } val maxX = points.maxOf { it.x } val maxY = points.maxOf { it.y } points.forEach { it.x -= minX } val lines = pointMatrix.map { it.windowed(2).map { (start, end) -> Line(start, end) } }.flatten() val map = (0..maxY).map { (minX..maxX).map { "." }.toTypedArray() }.toTypedArray() for (line in lines) { for (y in (line.start.y towards line.end.y)) { for (x in (line.start.x towards line.end.x)) { map[y][x] = "#" } } } map[0][500 - minX] = "+" // map.print() val quickSand = mutableListOf(Point(500 - minX, 0)) val stuckSand = mutableListOf<Point>() while (true) { try { for (sandIndex in (quickSand.lastIndex downTo 0)) { val sand = quickSand[sandIndex] while (true) { if (ifIsEmpty(map, sand.y + 1, sand.x)) { map[sand.y][sand.x] = "." map[++sand.y][sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x - 1)) { map[sand.y][sand.x] = "." map[++sand.y][--sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x + 1)) { map[sand.y][sand.x] = "." map[++sand.y][++sand.x] = "o" } else { stuckSand.add(sand) break } } } } catch (e: ArrayIndexOutOfBoundsException) { break } if (!quickSand.removeAll(stuckSand)) break quickSand.add(Point(500 - minX, 0)) } // map.print() return stuckSand.size } fun part2(input: List<String>): Int { val pointMatrix = input.map { it.split(" -> ").map(::Point) } val points = pointMatrix.flatten() val maxY = points.maxOf { it.y } val base = maxY + 2 val lines = pointMatrix.map { it.windowed(2).map { (start, end) -> Line(start, end) } }.flatten() val map = (0..base).map { (0..700).map { "." }.toTypedArray() }.toTypedArray() for (line in lines) { for (y in (line.start.y towards line.end.y)) { for (x in (line.start.x towards line.end.x)) { map[y][x] = "#" } } } map[base].fill("#") map[0][500] = "+" val quickSand = mutableListOf(Point(500, 0)) val stuckSand = mutableListOf<Point>() while (true) { try { for (sandIndex in (quickSand.lastIndex downTo 0)) { val sand = quickSand[sandIndex] while (true) { if (ifIsEmpty(map, sand.y + 1, sand.x)) { map[sand.y][sand.x] = "." map[++sand.y][sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x - 1)) { map[sand.y][sand.x] = "." map[++sand.y][--sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x + 1)) { map[sand.y][sand.x] = "." map[++sand.y][++sand.x] = "o" } else { stuckSand.add(sand) if (sand.y == 0) { map[0][sand.x] = "o" throw ArrayIndexOutOfBoundsException() } break } } } quickSand.removeAll(stuckSand) } catch (e: ArrayIndexOutOfBoundsException) { break } quickSand.add(Point(500, 0)) } // map.print() return stuckSand.size } private fun ifIsEmpty(map: Array<Array<String>>, y: Int = 0, x: Int = 0) = map[y][x] == "." } data class Point(var x: Int = 0, var y: Int = 0) { constructor(input: String) : this() { val (x, y) = input.split(',').map { it.toInt() } this.x = x this.y = y } } data class Line(val start: Point, val end: Point) } private fun <T> Array<Array<T>>.print() { this.forEach { it.forEach { print(it) }; println() }; println() }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
5,378
advent-of-code-22
Apache License 2.0
src/main/kotlin/dev/patbeagan/days/Day02.kt
patbeagan1
576,401,502
false
{"Kotlin": 57404}
package dev.patbeagan.days import dev.patbeagan.days.Day02.Move.* /** * [Day 2](https://adventofcode.com/2022/day/2) */ class Day02 : AdventDay<Int> { override fun part1(input: String) = parseInput1(input) .fold(0) { acc, each -> val movePoints = each.self.points val outcomePoints = Outcome.fromRound(each).points acc + outcomePoints + movePoints } override fun part2(input: String): Int = parseInput2(input) .fold(0) { acc, each -> val ensuringMoveFrom = each.second.getEnsuringMoveFrom(each.first) val movePoints = ensuringMoveFrom.points val outcomePoints = each.second.points acc + movePoints + outcomePoints } fun parseInput1(input: String): List<Round> = getLines(input) .map { s -> s.split(" ") .map { Move.from(it)!! } .let { Round(it[1], it[0]) } } fun parseInput2(input: String): List<Pair<Move, Outcome>> = getLines(input) .map { s -> s.split(" ") .let { Move.from(it[0])!! to Outcome.from(it[1])!! } } private fun getLines(input: String) = input .trim() .split("\n") /** * A single round of rock-paper-scissors. */ data class Round(val self: Move, val opponent: Move) /** * A single move. */ enum class Move(val points: Int) { Rock(1), Paper(2), Scissors(3); companion object { private val byToken = mapOf( "A" to Rock, "B" to Paper, "C" to Scissors, "X" to Rock, "Y" to Paper, "Z" to Scissors, ) fun from(input: String): Move? = byToken[input] } } /** * The outcome of a round. */ enum class Outcome(val points: Int) { Win(6), Tie(3), Loss(0); /** * Given an end state and the opponent's move, * this returns the move that you need to do to get to that end state */ fun getEnsuringMoveFrom(move: Move): Move = when (this) { Win -> winStates.first { it.opponent == move }.self Tie -> move Loss -> winStates.first { it.self == move }.opponent } companion object { private val byToken = mapOf( "X" to Loss, "Y" to Tie, "Z" to Win, ) fun from(input: String): Outcome? = byToken[input] fun fromRound(round: Round) = when { round.self == round.opponent -> Tie winStates.contains(round) -> Win else -> Loss } private val winStates = listOf( Round(Scissors, Paper), Round(Paper, Rock), Round(Rock, Scissors) ) } } }
0
Kotlin
0
0
4e25b38226bcd0dbd9c2ea18553c876bf2ec1722
2,984
AOC-2022-in-Kotlin
Apache License 2.0
src/Day12.kt
jrmacgill
573,065,109
false
{"Kotlin": 76362}
import utils.* import java.lang.Math.abs import java.lang.Math.min class Day12 { var dir = listOf<Point>(Point(-1,0), Point(1,0), Point(0,1),Point(0,-1)) fun go() { //private val rawInput: List<String> val grid: List<List<Char>> by lazy { readInput("dayTwelve").map { it.toList() }} var start = grid.searchIndices('S').first() var dist = path(grid, start) println(dist) var best = dist grid.searchIndices('a').forEach { p -> best = min(path(grid, p), best) } } fun path(grid: List<List<Char>>, start : Point) : Int { var end = grid.searchIndices('E').first() var dist = grid.mapValues { c -> 9999 }.toMutableGrid() var heights = grid.mapValues { c -> when(c) { 'S' -> 'a'.code - 'a'.code 'E' -> 'z'.code - 'a'.code else -> c.code - 'a'.code } } //println(heights) var prior = grid.mapValues { c -> Point(-1,-1) }.toMutableGrid() var q = mutableListOf<Point>() grid.mapValuesIndexed() { p,_ -> q.add(p) } var u = start dist[start] = 0 while (q.isNotEmpty()) { u = q.minBy { x -> dist[x] } q.remove(u) var current = heights[u] var neighbors = dir.map { p -> p + u }.filter { p -> (kotlin.math.abs(heights.getOrNull(p) ?: 1000) - current) < 2 } for (v in neighbors) { var alt = dist[u] + 1 if (alt < dist[v]) { dist[v] = alt prior[v] = u } } } println(dist[end]) return dist[end] } } fun main() { Day12().go() }
0
Kotlin
0
1
3dcd590f971b6e9c064b444139d6442df034355b
1,731
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d02/Day02.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d02 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.Tuple3 import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines // tuple order: (red, green, blue) fun parseGame(line: String): List<Tuple3<Int, Int, Int>> { val (_, draws) = line.split(": ", limit = 2) return draws.split("; ").map { draw -> val colorCounts = draw.split(", ").associate { val parts = it.split(" ") parts[1] to parts[0].toInt() } Tuple3(colorCounts["red"] ?: 0, colorCounts["green"] ?: 0, colorCounts["blue"] ?: 0) } } fun main() = timed { val games = (DATAPATH / "2023/day02.txt").useLines { lines -> lines.toList().map(::parseGame) } games.mapIndexed { idx, game -> // a game is possible if the max number of green dice observed was not more than 12 // and similarly for the other colors if (game.all { it._1 <= 12 && it._2 <= 13 && it._3 <= 14 }) { idx + 1 } else { 0 } } .sum() .also { println("Part one: $it") } games.sumOf { game -> // the minimum number of red dice making the game possible is the max of all observed red values // and the same goes for the other colors val minRed = game.maxOf { it._1 } val minGreen = game.maxOf { it._2 } val minBlue = game.maxOf { it._3 } minRed * minGreen * minBlue } .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,541
advent-of-code
MIT License
app/src/main/kotlin/me/leon/ext/math/Kgcd.kt
Leon406
381,644,086
false
{"Kotlin": 1392660, "JavaScript": 96128, "Java": 16541, "Batchfile": 4706, "Shell": 259, "CSS": 169}
package me.leon.ext.math import java.math.BigInteger object Kgcd { /** * @param a 第一个参数 * @param b 第二个参数 * @param x x的值,前两个组成的数组 * @param y y的值,前两个组成的数组 * @return 返回值为 {最大公约数,x的值,y的值} */ fun gcdext( a: BigInteger, b: BigInteger, x: Array<BigInteger>, y: Array<BigInteger> ): Array<BigInteger> { val result = Array<BigInteger>(3) { BigInteger.ONE } if (b == BigInteger.ZERO) { result[0] = a result[1] = x[0] result[2] = y[0] return result } val q = a / b val tx1 = x[0] - q * x[1] val ty1 = y[0] - q * y[1] val tx = arrayOf(x[1], tx1) val ty = arrayOf(y[1], ty1) return gcdext(b, a % b, tx, ty) } fun gcdext(a: BigInteger, b: BigInteger): Array<BigInteger> { val x = arrayOf(BigInteger.ONE, BigInteger.ZERO) val y = arrayOf(BigInteger.ZERO, BigInteger.ONE) return gcdext(a, b, x, y) } } fun crt(divideResults: List<DivideResult>): BigInteger { val modulusList = divideResults.map { it.quotient } val remainders = divideResults.map { it.remainder } return crt(remainders, modulusList) } fun crt(remainders: List<BigInteger>, modulusList: List<BigInteger>): BigInteger { val m = modulusList.reduce { acc, s -> acc * s } val lcmOfModulus = modulusList.reduce { acc, bigInteger -> acc.lcm(bigInteger) } return modulusList .map { m / it } .mapIndexed { index, mi -> remainders[index] * mi * mi.modInverse(modulusList[index]) } .sumOf { it } % lcmOfModulus } data class DivideResult(val remainder: BigInteger, val quotient: BigInteger) { constructor( remainder: String, quotient: String ) : this(remainder.toBigInteger(), quotient.toBigInteger()) }
4
Kotlin
236
1,218
dde1cc6e8e589f4a46b89e2e22918e8b789773e4
1,944
ToolsFx
ISC License
src/day02/Day02.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day02 import readInput fun main() { fun part1(input: List<String>): Int { var totalScore = 0 val shapes = parseInputPart1(input) shapes.windowed(2, 2) { (myShape, elvesShape) -> totalScore += myShape.shapeScore + myShape.match(elvesShape).matchScore } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 val (strategies, elvesShapes) = parseInputPart2(input) strategies.zip(elvesShapes) { strategy, elvesShape -> totalScore += strategy.counterChoose(elvesShape).shapeScore + strategy.matchScore } return totalScore } val testInput = readInput("day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02") println(part1(input)) // 12586 println(part2(input)) // 13193 } fun parseInputPart1(input: List<String>): List<Shape> = input.flatMap { it.split(' ').map(Shape::getShape).asReversed() } fun parseInputPart2(input: List<String>): Pair<List<MatchResult>, List<Shape>> { val elvesShapes = mutableListOf<Shape>() val counterStrategies = mutableListOf<MatchResult>() input.forEach { line -> val (shapeStr, strategyStr) = line.split(' ') elvesShapes += Shape.getShape(shapeStr) counterStrategies += MatchResult.resolve(strategyStr) } return counterStrategies to elvesShapes } sealed interface Shape { val shapeScore: Int fun match(shape: Shape): MatchResult fun winChoose(): Shape fun loseChoose(): Shape fun drawChoose(): Shape = this companion object { @JvmStatic fun getShape(c: String): Shape = when (c) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> error("Unknown shape.") } } } object Rock : Shape { override val shapeScore = 1 override fun match(shape: Shape): MatchResult = when (shape) { Rock -> Draw Paper -> Lose Scissors -> Win } override fun winChoose(): Shape = Paper override fun loseChoose(): Shape = Scissors } object Paper : Shape { override val shapeScore = 2 override fun match(shape: Shape): MatchResult = when (shape) { Rock -> Win Paper -> Draw Scissors -> Lose } override fun winChoose(): Shape = Scissors override fun loseChoose(): Shape = Rock } object Scissors : Shape { override val shapeScore: Int = 3 override fun match(shape: Shape): MatchResult = when (shape) { Rock -> Lose Paper -> Win Scissors -> Draw } override fun winChoose(): Shape = Rock override fun loseChoose(): Shape = Paper } sealed class MatchResult(val matchScore: Int) { abstract fun counterChoose(elvesShape: Shape): Shape companion object { @JvmStatic fun resolve(strategy: String): MatchResult = when (strategy) { "X" -> Lose "Y" -> Draw "Z" -> Win else -> error("Unknown strategy.") } } } object Win : MatchResult(6) { override fun counterChoose(elvesShape: Shape): Shape = elvesShape.winChoose() } object Lose : MatchResult(0) { override fun counterChoose(elvesShape: Shape): Shape = elvesShape.loseChoose() } object Draw : MatchResult(3) { override fun counterChoose(elvesShape: Shape): Shape = elvesShape.drawChoose() }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
3,622
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinCostTickets.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.min /** * 983. Minimum Cost For Tickets * https://leetcode.com/problems/minimum-cost-for-tickets/ */ fun interface MinCostTickets { operator fun invoke(days: IntArray, costs: IntArray): Int } /** * Approach 1: Dynamic Programming (Day Variant) */ class DPDayVariant : MinCostTickets { private lateinit var costs: IntArray private var memo: Array<Int?> = arrayOfNulls(LEAP_YEAR_DAYS) private var dayset: MutableSet<Int> = HashSet() override operator fun invoke(days: IntArray, costs: IntArray): Int { this.costs = costs for (d in days) dayset.add(d) return dp(1) } private fun dp(i: Int): Int { if (i > YEAR_DAYS) return 0 if (memo[i] != null) { return memo[i] ?: 0 } var ans: Int if (dayset.contains(i)) { ans = min( dp(i + 1) + costs[0], dp(i + 7) + costs[1], ) ans = min(ans, dp(i + THIRTY_DAYS) + costs[2]) } else { ans = dp(i + 1) } memo[i] = ans return ans } companion object { private const val THIRTY_DAYS = 30 private const val LEAP_YEAR_DAYS = 366 private const val YEAR_DAYS = 365 } } /** * Approach 2: Dynamic Programming (Window Variant) */ class DPWindowVariant : MinCostTickets { private lateinit var days: IntArray private lateinit var costs: IntArray private lateinit var memo: Array<Int?> private var durations = intArrayOf(ONE_DAY, ONE_WEEK, ONE_MONTH) override operator fun invoke(days: IntArray, costs: IntArray): Int { this.days = days this.costs = costs memo = arrayOfNulls(days.size) return dp(0) } private fun dp(i: Int): Int { if (i >= days.size) return 0 if (memo[i] != null) { return memo[i] ?: 0 } var ans = Int.MAX_VALUE var j = i for (k in 0..2) { while (j < days.size && days[j] < days[i] + durations[k]) { j++ } ans = min(ans, dp(j) + costs[k]) } memo[i] = ans return ans } companion object { private const val ONE_DAY = 1 private const val ONE_WEEK = 7 private const val ONE_MONTH = 30 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,985
kotlab
Apache License 2.0
src/main/kotlin/th/in/jamievl/adventofcode/d4/Day4.kt
jamievlin
578,295,680
false
{"Kotlin": 8145, "Starlark": 4278}
package th.`in`.jamievl.adventofcode.d4 import th.`in`.jamievl.adventofcode.common.readFromResource import java.lang.IllegalArgumentException import java.util.regex.Pattern import kotlin.math.min import kotlin.math.max data class AssignmentRange(val start: Int, val end: Int) { init { if (start > end) { throw IllegalArgumentException("Start cannot be less than end!") } } infix fun inside(other: AssignmentRange): Boolean = other.start <= start && end <= other.end /** * Checks if assignment range overlaps with [other]. * * As a note for the implementation, * if there is an overlap, say value a such that * `start <= a <= end], and `other.start <= a <= other.end`, * (for convenience, `ostart` means `other.start` and `oend` means `other.end`) * then, ordering `start` and `order.start` (and `end`, `order.end`), we get * `min(start,ostart) <= max(start,ostart) <= a <= min(end,oend) <= max(end,oend)` * * Hence, `max(start, ostart) <= min(end, oend)`. * * Likewise, if we have `max(start, ostart) <= min(end, oend)`, say there is a value `a` between them, then * `start <= max(start, ostart) <= a <= min(end, oend) <= end` * the same applies for ostart and oend, hence * `ostart <= max(start, ostart) <= a <= min(end, oend) <= oend` * * Thus, these 2 ranges overlap. */ infix fun overlaps(other: AssignmentRange): Boolean = max(start, other.start) <= min(end, other.end) companion object { private val matchRegex: Pattern = Pattern.compile("""(\d+)-(\d+)""") fun fromRangeString(inputString: String): AssignmentRange { val match = matchRegex.matcher(inputString.trim()) match.find() val start = match.group(1).toInt() val end = match.group(2).toInt() return AssignmentRange(start, end) } } } fun main() { var insideCount = 0 var overlapCount = 0 readFromResource("d4/d4_input.txt") { line -> val (assignRange1, assignRange2) = line.split(",").map { AssignmentRange.fromRangeString(it) } if (assignRange1 inside assignRange2 || assignRange2 inside assignRange1) { insideCount += 1 } if (assignRange1 overlaps assignRange2) { overlapCount += 1 } } println("inside count: $insideCount") println("overlap count: $overlapCount") }
0
Kotlin
0
0
4b0f5a8e6bcc411f1a76cfcd6d099872cf220e46
2,495
adventofcode-2022
MIT License
src/Day02RockPaperScissors.kt
zizoh
573,932,084
false
{"Kotlin": 13370}
// A, X -> Rock (1) // B, Y -> Paper (2) // C, Z -> Scissors (3) // lost (0) // draw (3) // win (6) // rock > scissors // scissors > paper // paper > rock // Part 2 // X lose // Y draw // Z win fun main() { val input: List<String> = readInput("input/day02") println("round one score: ${input.sumOf { roundOneScore(it) }}") println("round two score: ${input.sumOf { roundTwoScore(it) }}") } fun Char.selectForLoss(): String { return when (this) { 'A' -> "Z" 'B' -> "X" else -> "Y" } } fun Char.selectForDraw(): String { return when (this) { 'A' -> "X" 'B' -> "Y" else -> "Z" } } fun Char.selectForWin(): String { return when (this) { 'A' -> "Y" 'B' -> "Z" else -> "X" } } fun isDraw(selection: String) = selection == "A X" || selection == "B Y" || selection == "C Z" fun isLoss(selection: String) = selection == "A Z" || selection == "B X" || selection == "C Y" fun shapeScore(selection: String) = when (selection.last()) { 'X' -> 1 'Y' -> 2 else -> 3 } fun outcomeScore(selection: String) = when { isLoss(selection) -> 0 isDraw(selection) -> 3 else -> 6 } fun roundOneScore(selection: String) = shapeScore(selection) + outcomeScore(selection) fun roundTwoScore(selection: String): Int { val firstColumn = selection.first() return when { isToLose(selection.last()) -> 0 + shapeScore(firstColumn.selectForLoss()) isToDraw(selection.last()) -> 3 + shapeScore(firstColumn.selectForDraw()) else -> 6 + shapeScore(firstColumn.selectForWin()) } } fun isToLose(endRule: Char) = endRule == 'X' fun isToDraw(endRule: Char) = endRule == 'Y'
0
Kotlin
0
0
817017369d257cca648974234f1e4137cdcd3138
1,721
aoc-2022
Apache License 2.0
src/Day24.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
import java.io.File import kotlin.math.abs const val EPS = 1E-9 data class Point3(val x: Double, val y: Double, val z: Double) operator fun Point3.plus(p: Point3) = Point3(x + p.x, y + p.y, z + p.z) data class Line2(val a: Double, val b: Double, val c: Double) typealias Hail = Pair<Point3, Point3> fun main() { fun read(file: String) = readInput(file).map { line -> line.split(" @ ").map { p -> p.split(", ").map { it.toDouble() }.let { (x,y,z) -> Point3(x,y,z) } }.let { it[0] to it[1] } } fun solve1(file: String, range: ClosedFloatingPointRange<Double>): Int { val input = read(file) fun getLine(h: Pair<Point3, Point3>): Line2 { val (p1,d1) = h val p2 = p1 + d1 if (p1.x == p2.x) TODO() val m = (p2.y - p1.y) / (p2.x - p1.x) return Line2(m, -1.0, p1.y - m*p1.x) } fun intersect(h1: Hail, h2: Hail): Point3? { val (a1,b1,c1) = getLine(h1) val (a2,b2,c2) = getLine(h2) val d = a1 * b2 - a2*b1 if (abs(d) < EPS) return null return Point3((b1*c2 - b2*c1)/d, (c1*a2 - c2*a1)/d, 0.0) } var res = 0 for (i1 in input.indices) { for (i2 in i1+1 .. input.lastIndex) { val (h1, h2) = input[i1] to input[i2] val p = intersect(h1, h2) if (p != null) { val t1 = if (h1.second.x != 0.0) (p.x - h1.first.x) / h1.second.x else (p.y - h1.first.y) / h1.second.y val t2 = if (h2.second.x != 0.0) (p.x - h2.first.x) / h2.second.x else (p.y - h2.first.y) / h2.second.y if (p.x in range && p.y in range && t1 >= 0 && t2 >= 0) { res++ } } } } return res } // generate smt file for z3 fun solve2(file: String) { val input = read(file) val smt = File("$file.smt").printWriter() smt.println(""" (declare-const rx Int) (declare-const ry Int) (declare-const rz Int) (declare-const vx Int) (declare-const vy Int) (declare-const vz Int) """.trimIndent()) for (i in input.indices) { val (px,py,pz) = input[i].first val (vx,vy,vz) = input[i].second smt.println("(declare-const t$i Int)") fun add(c: Char, p: Double, v: Double) { val left = "(+ ${p.toLong()} (* ${v.toLong()} t$i))" val right = "(+ r$c (* v$c t$i))" smt.println("(assert (= $left $right))") } add('x', px, vx) add('y', py, vy) add('z', pz, vz) //println("$px ${if (sx>=0) "+" else ""} $sx * t$i = rx + vx * t$i") //println("$py ${if (sy>=0) "+" else ""} $sy * t$i = ry + vy * t$i") //println("$pz ${if (sz>=0) "+" else ""} $sz * t$i = rz + vz * t$i") } smt.println("(check-sat)") smt.println("(get-value (rx ry rz))") smt.close() println("z3 $file.smt") // or https://microsoft.github.io/z3guide/playground/Freeform%20Editing } assert(solve1("Day24t", 7.0..27.0) == 2) println(solve1("Day24", 200000000000000.0..400000000000000.0)) solve2("Day24t") solve2("Day24") }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
3,492
advent-of-code-kotlin
Apache License 2.0
kotlin/MyTest.kt
char16t
139,452,018
false
{"JavaScript": 1115281, "Jupyter Notebook": 722304, "Java": 362103, "Scala": 319717, "TypeScript": 214516, "HTML": 152089, "Handlebars": 61648, "C++": 35907, "PLpgSQL": 21952, "Clojure": 17487, "CSS": 17421, "SCSS": 11649, "Kotlin": 7383, "Shell": 6892, "Python": 6618, "Jinja": 4302, "Makefile": 4154, "C": 3782, "Dockerfile": 2215, "TeX": 1675, "CMake": 939, "Cap'n Proto": 614, "PowerShell": 370, "Batchfile": 139}
package training import io.kotlintest.specs.StringSpec import java.util.* import kotlin.collections.HashMap class MyTest : StringSpec({ "Test1" { val graph = listOf( // 1-st connected component listOf(1, 2), listOf(1, 3), listOf(2, 4), listOf(2, 5), listOf(3, 6), listOf(3, 7), // 2-nd connected component listOf(8, 9) ) fun bfs(root: Int, graph: List<List<Int>>): List<Int> { val answer = LinkedList<Int>() val queue = LinkedList<Int>() queue.add(root) val visited = HashMap<Int, Boolean>() visited[root] = true while (!queue.isEmpty()) { val element = queue.removeAt(0) answer.add(element) val neighbors = graph .filter { pair -> pair[0] != pair[1] && (pair[0] == element || pair[1] == element) } .map { pair -> if (pair[0] != element) pair[0] else pair[1] } .distinct() for (neighbor in neighbors) { if (visited.containsKey(neighbor) && !visited[neighbor]!! || !visited.containsKey(neighbor)) { visited[neighbor] = true queue.add(neighbor) } } } return answer } fun dfs(root: Int, graph: List<List<Int>>): List<Int> { val answer = LinkedList<Int>() val queue = LinkedList<Int>() queue.add(0, root) val visited = HashMap<Int, Boolean>() visited[root] = true while (!queue.isEmpty()) { val element = queue.removeAt(0) answer.add(element) val neighbors = graph .filter { pair -> pair[0] != pair[1] && (pair[0] == element || pair[1] == element) } .map { pair -> if (pair[0] != element) pair[0] else pair[1] } .distinct() for (neighbor in neighbors) { if (visited.containsKey(neighbor) && !visited[neighbor]!! || !visited.containsKey(neighbor)) { visited[neighbor] = true queue.add(0, neighbor) } } } return answer } fun topological_sort(root: Int, graph: List<List<Int>>): List<Int> { val answer = LinkedList<Int>() val queue = LinkedList<Int>() queue.add(0, root) val visited = HashMap<Int, Boolean>() visited[root] = true while (!queue.isEmpty()) { val element = queue.removeAt(0) answer.add(0, element) val neighbors = graph .filter { pair -> pair[0] != pair[1] && (pair[0] == element || pair[1] == element) } .map { pair -> if (pair[0] != element) pair[0] else pair[1] } .distinct() for (neighbor in neighbors) { if (visited.containsKey(neighbor) && !visited[neighbor]!! || !visited.containsKey(neighbor)) { visited[neighbor] = true queue.add(0, neighbor) } } } return answer } fun connected_components(graph: List<List<Int>>): List<List<Int>> { val visited = HashMap<Int, Boolean>() fun innerDfs(root: Int, graph: List<List<Int>>): List<Int> { val answer = LinkedList<Int>() val queue = LinkedList<Int>() queue.add(0, root) visited[root] = true while (!queue.isEmpty()) { val element = queue.removeAt(0) answer.add(element) val neighbors = graph .filter { pair -> pair[0] != pair[1] && (pair[0] == element || pair[1] == element) } .map { pair -> if (pair[0] != element) pair[0] else pair[1] } .distinct() for (neighbor in neighbors) { if (visited.containsKey(neighbor) && !visited[neighbor]!! || !visited.containsKey(neighbor)) { visited[neighbor] = true queue.add(0, neighbor) } } } return answer } val components = LinkedList<List<Int>>() val vertices = graph.flatten().distinct() for (vertice in vertices) { if (visited.containsKey(vertice) && !visited[vertice]!! || !visited.containsKey(vertice)) { components.add(innerDfs(vertice, graph)) } } return components } // https://neerc.ifmo.ru/wiki/index.php?title=%D0%98%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BE%D0%B1%D1%85%D0%BE%D0%B4%D0%B0_%D0%B2_%D0%B3%D0%BB%D1%83%D0%B1%D0%B8%D0%BD%D1%83_%D0%B4%D0%BB%D1%8F_%D0%BF%D0%BE%D0%B8%D1%81%D0%BA%D0%B0_%D0%BA%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82_%D1%81%D0%B8%D0%BB%D1%8C%D0%BD%D0%BE%D0%B9_%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D0%BE%D1%81%D1%82%D0%B8 fun strong_connected_components(root: Int, graph: List<List<Int>>): List<List<Int>> { val visited = HashMap<Int, Boolean>() fun innerDfs(root: Int, graph: List<List<Int>>): List<Int> { val answer = LinkedList<Int>() val queue = LinkedList<Int>() queue.add(0, root) visited[root] = true while (!queue.isEmpty()) { val element = queue.removeAt(0) answer.add(element) val neighbors = graph .filter { pair -> pair[0] != pair[1] && pair[0] == element } .map { it[1] } .distinct() for (neighbor in neighbors) { if (visited.containsKey(neighbor) && !visited[neighbor]!! || !visited.containsKey(neighbor)) { visited[neighbor] = true queue.add(0, neighbor) } } } return answer } val reversedGraph = graph.map { it.reversed() } val vertices = connected_components(graph).flatten() //.map { it.reversed() } //val vertices = dfs(root, graph) val components = LinkedList<List<Int>>() for (vertice in vertices) { if (visited.containsKey(vertice) && !visited[vertice]!! || !visited.containsKey(vertice)) { components.add(innerDfs(vertice, reversedGraph)) } } return components } println(bfs(1, graph)) println("---") println(dfs(1, graph)) println("---") println(topological_sort(1, graph)) println("---") println(connected_components(graph)) println("---") println(strong_connected_components(1, graph)) } })
0
JavaScript
0
0
3669a0b7536a0df61344cf8f69c2c6f0ba7a6ac8
7,383
incubator
The Unlicense
src/test/kotlin/year2015/Day6.kt
abelkov
47,995,527
false
{"Kotlin": 48425}
package year2015 import kotlin.test.Test import kotlin.test.assertEquals class Day6 { @Test fun part1() { val field = Array(1000) { Array(1000) { false } } val regex = """(?>turn )?(\w+) (\d+),(\d+) \w+ (\d+),(\d+)""".toRegex() readInput("year2015/Day6.txt").lines().forEach { line: String -> val matchResult = regex.matchEntire(line) val (command, x1, y1, x2, y2) = matchResult!!.groupValues.drop(1) for (x in x1.toInt()..x2.toInt()) { for (y in y1.toInt()..y2.toInt()) { when (command) { "on" -> field[x][y] = true "off" -> field[x][y] = false "toggle" -> field[x][y] = !field[x][y] else -> IllegalStateException() } } } } val count = field.sumOf { row -> row.sumOf { light -> if (light) 1L else 0 } } assertEquals(543903, count) } @Test fun part2() { val field = Array(1000) { Array(1000) { 0 } } val regex = """(?>turn )?(\w+) (\d+),(\d+) \w+ (\d+),(\d+)""".toRegex() readInput("year2015/Day6.txt").lines().forEach { line: String -> val matchResult = regex.matchEntire(line) val (command, x1, y1, x2, y2) = matchResult!!.groupValues.drop(1) for (x in x1.toInt()..x2.toInt()) { for (y in y1.toInt()..y2.toInt()) { when (command) { "on" -> field[x][y]++ "off" -> { field[x][y]-- field[x][y] = field[x][y].coerceAtLeast(0) } "toggle" -> field[x][y] += 2 else -> IllegalStateException() } } } } val count = field.sumOf { row -> row.sumOf { level -> level } } assertEquals(14687245, count) } }
0
Kotlin
0
0
0e4b827a742322f42c2015ae49ebc976e2ef0aa8
2,030
advent-of-code
MIT License
src/day07/Day07.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day07 import readLines const val MAX_SIZE = 100000L const val TOTAL_AVAILABLE_SIZE = 70000000L const val UPDATE_SIZE = 30000000L typealias Indexes = MutableList<Index> val empty: Indexes get() = mutableListOf() sealed interface Index { val name: String; val parent: Dir?; val size: Long } class File(override val name: String, override val parent: Dir, override val size: Long) : Index data class Dir(override val name: String, override val parent: Dir?, val indexes: Indexes) : Index { override val size: Long get() = indexes.sumOf { index -> index.size } } class Cursor(val root: Dir, var head: Dir = root) @DslMarker annotation class CursorDsl @CursorDsl val Root: Dir get() = Dir(name = "/", parent = null, indexes = empty) @CursorDsl val Dir.dirs: List<Dir> get() = indexes.filterIsInstance<Dir>() @CursorDsl val Dir.flatDirs: List<Dir> get() = dirs.map { listOf(it) + it.flatDirs }.flatten() @CursorDsl val Dir.spaceAfterUpdate: Long get() = UPDATE_SIZE - (TOTAL_AVAILABLE_SIZE - size) @CursorDsl val String.isCommand: Boolean get() = startsWith("$") @CursorDsl val String.isOutput: Boolean get() = !isCommand @CursorDsl val String.param: String get() = split(" ").last() @CursorDsl val String.isCd: Boolean get() = startsWith("$ cd") @CursorDsl val String.size: Long get() = split(" ").first().toLong() @CursorDsl val String.name: String get() = split(" ").last() @CursorDsl val String.isDir: Boolean get() = split(" ").first() == "dir" @CursorDsl val String.isBack: Boolean get() = endsWith("..") @CursorDsl val String.isRoot: Boolean get() = endsWith("/") fun Cursor(input: List<String>, root: Dir = Root): Cursor = Cursor(root).apply { input.forEach { line -> when { line.isCommand && line.isCd -> head = when { line.param.isBack -> head.parent!! line.param.isRoot -> root else -> head.dirs.first { dir -> dir.name == line.param } } line.isOutput -> head.indexes += when { line.isDir -> Dir(line.name, head, empty) else -> File(line.name, head, line.size) } } } } fun main() { fun part1(inputs: List<String>): Long = Cursor(inputs) .root.flatDirs .filter { index: Index -> index.size <= MAX_SIZE } .sumOf { it.size } fun part2(inputs: List<String>, root: Dir = Root): Long = Cursor(inputs, root) .root.flatDirs .filter { it.size > root.spaceAfterUpdate } .minBy { it.size } .size val testInput: List<String> = readLines("day07/test.txt") val input: List<String> = readLines("day07/input.txt") check(part1(testInput) == 95437L) println(part1(input)) check(part2(testInput) == 24933642L) println(part2(input)) }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
2,664
advent-of-code-22
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/Candy.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 135. Candy * @see <a href="https://leetcode.com/problems/candy">Source</a> */ fun interface Candy { operator fun invoke(ratings: IntArray): Int } class CandyBruteForce : Candy { override operator fun invoke(ratings: IntArray): Int { val candies = IntArray(ratings.size) { 1 } var flag = true var sum = 0 while (flag) { flag = false for (i in ratings.indices) { if (i != ratings.size - 1 && ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) { candies[i] = candies[i + 1] + 1 flag = true } if (i > 0 && ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) { candies[i] = candies[i - 1] + 1 flag = true } } } for (candy in candies) { sum += candy } return sum } } class Candy2Arrays : Candy { override operator fun invoke(ratings: IntArray): Int { var sum = 0 val left2right = IntArray(ratings.size) { 1 } val right2left = IntArray(ratings.size) { 1 } for (i in 1 until ratings.size) { if (ratings[i] > ratings[i - 1]) { left2right[i] = left2right[i - 1] + 1 } } for (i in ratings.size - 2 downTo 0) { if (ratings[i] > ratings[i + 1]) { right2left[i] = right2left[i + 1] + 1 } } for (i in ratings.indices) { sum += max(left2right[i], right2left[i]) } return sum } } class CandyArray : Candy { override operator fun invoke(ratings: IntArray): Int { if (ratings.isEmpty()) return 0 val candies = IntArray(ratings.size) { 1 } for (i in 1 until ratings.size) { if (ratings[i] > ratings[i - 1]) { candies[i] = candies[i - 1] + 1 } } var sum = candies[ratings.size - 1] for (i in ratings.size - 2 downTo 0) { if (ratings[i] > ratings[i + 1]) { candies[i] = max(candies[i], candies[i + 1] + 1) } sum += candies[i] } return sum } } class CandyMath : Candy { override operator fun invoke(ratings: IntArray): Int { fun count(n: Int) = n * n.plus(1) / 2 if (ratings.size <= 1) { return ratings.size } var candies = 0 var up = 0 var down = 0 var oldSlope = 0 for (i in 1 until ratings.size) { val newSlope = if (ratings[i] > ratings[i - 1]) 1 else if (ratings[i] < ratings[i - 1]) -1 else 0 val equalPredicate = oldSlope > 0 && newSlope == 0 val greeterPredicate = oldSlope < 0 && newSlope >= 0 if (equalPredicate || greeterPredicate) { candies += count(up) + count(down) + max(up, down) up = 0 down = 0 } if (newSlope > 0) up++ if (newSlope < 0) down++ if (newSlope == 0) candies++ oldSlope = newSlope } candies += count(up) + count(down) + max(up, down) + 1 return candies } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,941
kotlab
Apache License 2.0
src/main/kotlin/days/Day10.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days class Day10 : Day(10) { override fun runPartOne(lines: List<String>): Any { return lines.map { line -> findInvalidChar(line.toCharArray().toList()).first }.sumOf { c -> val n: Int = when(c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 null -> 0 else -> error("invalid character $c") } n } } override fun runPartTwo(lines: List<String>): Any { val scores = lines.map { line -> findInvalidChar(line.toCharArray().toList()) }.filter { (c, _) -> c == null }.map { (_, remainder) -> remainder }.map { lineScore(it) }.sorted() return scores[scores.size / 2] } fun findInvalidChar(chars: List<Char>) : Pair<Char?, List<Char>> { val stack = mutableListOf<Char>() chars.forEach { c -> when (c) { '(' -> stack.add(c) ')' -> { if (stack.last() == '(') { stack.removeLast() } else { return c to emptyList() } } '[' -> stack.add(c) ']' -> { if (stack.last() == '[') { stack.removeLast() } else { return c to emptyList() } } '{' -> stack.add(c) '}' -> { if (stack.last() == '{') { stack.removeLast() } else { return c to emptyList() } } '<' -> stack.add(c) '>' -> { if (stack.last() == '<') { stack.removeLast() } else { return c to emptyList() } } else -> error("invalid character $c") } } stack.reverse() return null to stack } fun lineScore(s: String): Long { return lineScore(s.toCharArray().toList()) } fun lineScore(s: List<Char>): Long { return s.fold(0) { acc, c -> acc * 5L + when(c) { '(' -> 1L '[' -> 2L '{' -> 3L '<' -> 4L else -> error("invalid character $c") } } } }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
2,622
aoc2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/sherepenko/leetcode/solutions/NumberOfIslands.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.solutions import com.sherepenko.leetcode.Solution class NumberOfIslands( private val grid: Array<CharArray> ) : Solution { companion object { fun numIslandsI(grid: Array<CharArray>): Int { var count = 0 for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == '1') { findIslandDfs(grid, i, j) count++ } } } return count } fun numIslandsII(grid: Array<CharArray>): Int { val m = grid.size val n = grid[0].size val dx = intArrayOf(1, 0) val dy = intArrayOf(0, 1) val dp = IntArray(m * n) var count = 0 for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == '1') { dp[i * n + j] = i * n + j count++ } } } fun union(p: Int, q: Int) { val pRoot = dp.find(p) val qRoot = dp.find(q) if (pRoot != qRoot) { dp[pRoot] = qRoot count-- } } for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == '1') { for (k in dx.indices) { val x = dx[k] + i val y = dy[k] + j if (x in grid.indices && y in grid[0].indices && grid[x][y] == '1') { union(i * n + j, x * n + y) } } } } } return count } private fun findIslandDfs(grid: Array<CharArray>, row: Int, column: Int) { if (row in grid.indices && column in grid[0].indices && grid[row][column] == '1') { grid[row][column] = 'x' findIslandDfs(grid, row + 1, column) findIslandDfs(grid, row - 1, column) findIslandDfs(grid, row, column + 1) findIslandDfs(grid, row, column - 1) } } private fun IntArray.find(index: Int): Int { var i = index while (this[i] != i) { i = this[this[i]] } return i } } override fun resolve() { println("Number Of Islands:") println(" Input:") grid.forEach { println(" ${it.joinToString(separator = " ")}") } println(" Result: ${numIslandsI(grid)}") grid.forEach { println(" ${it.joinToString(separator = " ")}") } println() } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
2,950
leetcode
The Unlicense
src/main/kotlin/days/Day21.kt
nuudles
316,314,995
false
null
package days class Day21 : Day(21) { private val allergenMapping: Map<String, String> private val allIngredients: List<String> init { val mapping = mutableMapOf<String, Set<String>>() val allIngredients = mutableListOf<String>() inputList .forEach { line -> val components = line.split(" (contains ") allIngredients.addAll(components.first().split(" ")) val ingredients = components.first().split(" ").toSet() components .last() .dropLast(1) .split(", ") .forEach { allergen -> mapping[allergen] = mapping[allergen]?.intersect(ingredients) ?: ingredients } } while (mapping.values.sumBy { it.count() } != mapping.count()) { mapping .filter { it.value.count() == 1 } .map { it.value.first() } .forEach { found -> mapping.forEach { (key, set) -> if (set.count() > 1 && set.contains(found)) { mapping[key] = set.minus(found) } } } } allergenMapping = mapping.mapValues { it.value.first() } this.allIngredients = allIngredients } override fun partOne(): Any { val allergens = allergenMapping.values.toSet() return allIngredients.count { !allergens.contains(it) } } override fun partTwo() = allergenMapping .map { it.key to it.value } .sortedBy { it.first } .joinToString(",") { it.second } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
1,742
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day08.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun Int.countVisibleTrees( axisPos: Int, changePosition: (Int) -> Int, condition: (Int) -> Boolean, newTree: (Int) -> Int, ): Int { var newPos = changePosition(axisPos) var count = 0 while (condition(newPos)) { count++ if (newTree(newPos) < this) { newPos = changePosition(newPos) } else { break } } return count } fun Int.isVisibleFromEdge( axisPos: Int, changePosition: (Int) -> Int, condition: (Int) -> Boolean, newTree: (Int) -> Int, ): Boolean { var newPos = changePosition(axisPos) while (condition(newPos)) { if (newTree(newPos) < this) { newPos = changePosition(newPos) } else { return false } } return true } fun <T> List<List<Int>>.generateVisibleTreesCount( parser: List<List<Int>>.(Pair<Int, Int>) -> T, ): List<T> = buildList { for (i in this@generateVisibleTreesCount.indices) { // ignore edges if (i == 0 || i == this@generateVisibleTreesCount.lastIndex) continue for (j in this@generateVisibleTreesCount[i].indices) { // ignore edges if (j == 0 || j == this@generateVisibleTreesCount[i].lastIndex) continue add(this@generateVisibleTreesCount.parser(i to j)) } } } fun part1(input: List<String>): Int { val trees = input.map { it.map(Char::digitToInt) } val visibleTrees = (2 * trees.size) + (2 * trees.first().size) - 4 return trees.generateVisibleTreesCount { (i, j) -> val tree = this[i][j] tree.isVisibleFromEdge( axisPos = j, changePosition = { it - 1 }, condition = { it >= 0 }, newTree = { this[i][it] } ) || tree.isVisibleFromEdge( axisPos = i, changePosition = { it - 1 }, condition = { it >= 0 }, newTree = { this[it][j] } ) || tree.isVisibleFromEdge( axisPos = j, changePosition = { it + 1 }, condition = { it < this[i].size }, newTree = { this[i][it] } ) || tree.isVisibleFromEdge( axisPos = i, changePosition = { it + 1 }, condition = { it < this.size }, newTree = { this[it][j] } ) }.count { it } + visibleTrees } fun part2(input: List<String>): Int = input.map { it.map(Char::digitToInt) } .generateVisibleTreesCount { (i, j) -> val tree = this[i][j] VisibleTreesCount( treePos = i to j, left = tree.countVisibleTrees( axisPos = j, changePosition = { it - 1 }, condition = { it >= 0 }, newTree = { this[i][it] } ), top = tree.countVisibleTrees( axisPos = i, changePosition = { it - 1 }, condition = { it >= 0 }, newTree = { this[it][j] } ), right = tree.countVisibleTrees( axisPos = j, changePosition = { it + 1 }, condition = { it < this[i].size }, newTree = { this[i][it] } ), bottom = tree.countVisibleTrees( axisPos = i, changePosition = { it + 1 }, condition = { it < this.size }, newTree = { this[it][j] } ), ) } .maxOf { it.left * it.top * it.right * it.bottom } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) val input = readInput("Day08") println(part1(input)) // part 2 check(part2(testInput) == 8) println(part2(input)) } private data class VisibleTreesCount( val treePos: Pair<Int, Int>, val left: Int, val top: Int, val right: Int, val bottom: Int, )
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
4,396
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2021/Day06.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2021 import aoc2022.applyN import utils.InputUtils // 8 + 6 + 6 + 6 + 6 fun simulate(i: List<Int>): List<Int> = i.flatMap { when (it) { 0 -> listOf(6, 8) else -> listOf(it - 1) } } fun fishAfterImpl(days: Int): Long = when { days < 0 -> 1 else -> fishAfter(days - 7) + fishAfter(days - 9) } val map = HashMap<Int, Long>() fun fishAfter(days: Int): Long = when { days < 0 -> 1 else -> map.computeIfAbsent(days, ::fishAfterImpl) } fun fishAfter(counter: Int, days: Int): Long { return fishAfter(days - 1 - counter) } fun main() { val testInput = """3,4,3,1,2""".split("\n") fun part1(input: List<String>): Int { val states = input[0].split(',').map { it.toInt() } return applyN(states, 80, ::simulate).size } fun part2(input: List<String>): Long { // Populate cache for (x in 0..260) { print("$x ") println(fishAfter(x)) } val states = input[0].split(',').map { it.toInt() } return states.groupingBy { it }.eachCount().map { (k, v) -> fishAfter(k, 256) * v }.sum() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 5934) val puzzleInput = InputUtils.downloadAndGetLines(2021, 6) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
1,467
aoc-2022-kotlin
Apache License 2.0
src/Day21.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
private sealed class Monkey(val name: String) { abstract var value: Long? val dependingMonkeys = mutableListOf<DependingMonkey>() class LeafMonkey( name: String, override var value: Long? ) : Monkey(name) class DependingMonkey( name: String, val leftMonkeyName: String, val rightMonkeyName: String, val operation: Char ): Monkey(name) { lateinit var leftMonkey: Monkey lateinit var rightMonkey: Monkey override var value: Long? = null } } fun <T> T.deepFlatMap(mapper: (T) -> List<T>): List<T> { val result = mutableListOf(this) mapper(this).forEach { result += it.deepFlatMap(mapper) } return result } fun main() { fun List<String>.toMonkeyMap(): Map<String, Monkey> { val monkeyList = map { val name = it.substringBefore(":") val data = it.substringAfter(": ") if (data.contains(" ")) { val parts = data.split(" ") val leftMonkey = parts[0] val rightMonkey = parts[2] val operation = parts[1].first() Monkey.DependingMonkey(name, leftMonkey, rightMonkey, operation) } else { Monkey.LeafMonkey(name, data.toLong()) } } val monkeyMap = monkeyList.associateBy { it.name } monkeyList.forEach { if (it is Monkey.DependingMonkey) { it.leftMonkey = monkeyMap[it.leftMonkeyName]!! it.rightMonkey = monkeyMap[it.rightMonkeyName]!! } } do { monkeyList.forEach { monkey -> if (monkey is Monkey.DependingMonkey && monkey.value == null) { val leftValue = monkeyMap[monkey.leftMonkeyName]?.value ?: return@forEach val rightValue = monkeyMap[monkey.rightMonkeyName]?.value ?: return@forEach monkey.value = when (monkey.operation) { '+' -> leftValue + rightValue '-' -> leftValue - rightValue '*' -> leftValue * rightValue '/' -> leftValue / rightValue else -> throw IllegalArgumentException("Unknown operation ${monkey.operation}") } } } } while (monkeyList.any { it.value == null }) monkeyList.forEach { monkey -> if (monkey is Monkey.DependingMonkey) { monkey.leftMonkey.dependingMonkeys.add(monkey) monkey.rightMonkey.dependingMonkeys.add(monkey) } } return monkeyMap } fun part1(input: List<String>): Long { val monkeyMap = input.toMonkeyMap() return monkeyMap["root"]!!.value!! } fun part2(input: List<String>): Long { val monkeyMap = input.toMonkeyMap() val human = monkeyMap["humn"]!! val allDependingMonkeys = human.deepFlatMap { it.dependingMonkeys } val root = monkeyMap["root"] as Monkey.DependingMonkey val leftIsDependentOnHuman = allDependingMonkeys.contains(root.leftMonkey) val rightIsDependentOnHuman = allDependingMonkeys.contains(root.rightMonkey) println("amount of monkeys depending directly on human: ${allDependingMonkeys.size}") println("left is dependent on human: $leftIsDependentOnHuman") println("right is dependent on human: $rightIsDependentOnHuman") fun Monkey.monkeyShouldBeValue(value: Long) { if (this == human) { this.value = value return } if (this !is Monkey.DependingMonkey) throw IllegalArgumentException("can only consider depending monkeys") val (targetValue, monkeyToChange) = if (allDependingMonkeys.contains(leftMonkey)) { // left monkey needs to change, right monkey is static val rightValue = rightMonkey.value!! // value = left <operation> right // value = left + right // 10 = 6 + 4 // 6 = 10 - 4 // value = left * right // 10 = 2 * 5 // 2 = 10 / 5 // value = left / right // 2 = 10 / 5 // 10 = 2 * 5 val targetValue = when (operation) { '-' -> value + rightValue // value = left - right; left = value + right '+' -> value - rightValue // value = left + right; left = value - right '*' -> value / rightValue // value = left * right; left = value / right '/' -> value * rightValue // value = left / right; left = value * right else -> throw IllegalArgumentException("Unknown operation: $operation") } targetValue to leftMonkey } else { // right monkey needs to change, left monkey is static val leftValue = leftMonkey.value!! // value = left <operation> right // value = left - right // 4 = 10 - 6 // right = left - value // 6 = 10 - 4 // value = left + right // 10 = 6 + 4 // right = value - left // 4 = 10 - 6 // value = left * right // 10 = 2 * 5 // right = value / left // 5 = 10 / 2 // value = left / right // 2 = 10 / 5 // right = left / value // 5 = 10 / 2 val targetValue = when (operation) { '-' -> leftValue - value '+' -> value - leftValue '*' -> value / leftValue '/' -> leftValue / value else -> throw IllegalArgumentException("Unknown operation: $operation") } targetValue to rightMonkey } monkeyToChange.monkeyShouldBeValue(targetValue) } val (monkeyWithTargetValue, monkeyThatNeedsToChangeValue) = if (leftIsDependentOnHuman) { root.rightMonkey to root.leftMonkey } else { root.leftMonkey to root.rightMonkey } monkeyThatNeedsToChangeValue.monkeyShouldBeValue(monkeyWithTargetValue.value!!) return human.value!! } // test if implementation meets criteria from the description, like: val dayNumber = 21 val testInput = readInput("Day${dayNumber}_test") val testResultPart1 = part1(testInput) val testAnswerPart1 = 152L check(testResultPart1 == testAnswerPart1) { "Part 1: got $testResultPart1 but expected $testAnswerPart1" } val testResultPart2 = part2(testInput) val testAnswerPart2 = 301L check(testResultPart2 == testAnswerPart2) { "Part 2: got $testResultPart2 but expected $testAnswerPart2" } val input = readInput("Day$dayNumber") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
7,152
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0993_cousins_in_binary_tree // #Easy #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_05_12_Time_152_ms_(71.43%)_Space_35.2_MB_(71.43%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun isCousins(root: TreeNode?, x: Int, y: Int): Boolean { return !isSiblings(root, x, y) && isSameLevels(root, x, y) } private fun isSameLevels(root: TreeNode?, x: Int, y: Int): Boolean { return findLevel(root, x, 0) == findLevel(root, y, 0) } private fun findLevel(root: TreeNode?, x: Int, level: Int): Int { if (root == null) { return -1 } if (root.`val` == x) { return level } val leftLevel = findLevel(root.left, x, level + 1) return if (leftLevel == -1) { findLevel(root.right, x, level + 1) } else { leftLevel } } private fun isSiblings(root: TreeNode?, x: Int, y: Int): Boolean { if (root == null) { return false } // Check children first val leftSubTreeContainsCousins = isSiblings(root.left, x, y) val rightSubTreeContainsCousins = isSiblings(root.right, x, y) if (leftSubTreeContainsCousins || rightSubTreeContainsCousins) { return true } return if (root.left == null || root.right == null) { false } else root.left!!.`val` == x && root.right!!.`val` == y || root.right!!.`val` == x && root.left!!.`val` == y } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,750
LeetCode-in-Kotlin
MIT License
src/Day23.kt
catcutecat
572,816,768
false
{"Kotlin": 53001}
import kotlin.system.measureTimeMillis fun main() { measureTimeMillis { Day23.run { solve1(110) // 3766 solve2(20) // 954 } }.let { println("Total: $it ms") } } object Day23 : Day.LineInput<Set<Pair<Int, Int>>, Int>("23") { override fun parse(input: List<String>) = mutableSetOf<Pair<Int, Int>>().apply { for (row in input.indices) { for (col in input[row].indices) { if (input[row][col] == '#') add(row to col) } } } private val directions = arrayOf( (-1 to 0) to arrayOf(-1 to -1, -1 to 0, -1 to 1), // N (1 to 0) to arrayOf(1 to -1, 1 to 0, 1 to 1), // S (0 to -1) to arrayOf(-1 to -1, 0 to -1, 1 to -1), // W (0 to 1) to arrayOf(-1 to 1, 0 to 1, 1 to 1) // E ) private fun move(elves: MutableSet<Pair<Int, Int>>, round: Int): Boolean { val move = mutableMapOf<Pair<Int, Int>, MutableList<Pair<Int, Int>>>() // [dest] = listOf(from) for (elf in elves) (round until round + directions.size) .map { directions[it % directions.size] } .filter { (_, checkpoints) -> checkpoints.all { point -> (point.first + elf.first to point.second + elf.second) !in elves } } .takeIf { it.size in 1 until directions.size } ?.let { val (dir, _) = it.first() val dest = elf.first + dir.first to elf.second + dir.second move.getOrPut(dest) { mutableListOf() }.add(elf) } for ((k, v) in move) if (v.size == 1) elves.apply { remove(v.single()) add(k) } return move.any { it.value.size == 1 } } override fun part1(data: Set<Pair<Int, Int>>): Int = data.toMutableSet().run { repeat(10) { move(this, it) } intArrayOf(minOf { it.first }, maxOf { it.first }, minOf { it.second }, maxOf { it.second }) .let { (minRow, maxRow, minCol, maxCol) -> (maxRow - minRow + 1) * (maxCol - minCol + 1) - size } } override fun part2(data: Set<Pair<Int, Int>>): Int = data.toMutableSet().run { var res = 0 while (move(this, res)) ++res res + 1 } }
0
Kotlin
0
2
fd771ff0fddeb9dcd1f04611559c7f87ac048721
2,243
AdventOfCode2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1296/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1296 import java.util.ArrayDeque /** * LeetCode page: [1296. Divide Array in Sets of K Consecutive Numbers](https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/); */ class Solution2 { /* Complexity: * Time O(N) and Space O(N) where N is the size of nums; */ fun isPossibleDivide(nums: IntArray, k: Int): Boolean { val countPerNum = getCountPerNum(nums) val starts = findStartsOfConsecutiveNumbers(countPerNum) return isPossibleDivide(countPerNum, starts, k) } private fun getCountPerNum(nums: IntArray): MutableMap<Int, Int> { val counts = hashMapOf<Int, Int>() for (num in nums) { val currCount = counts[num] ?: 0 counts[num] = currCount + 1 } return counts } private fun findStartsOfConsecutiveNumbers(countPerNum: Map<Int, Int>): ArrayDeque<Int> { val starts = ArrayDeque<Int>() for (num in countPerNum.keys) { val precedingNum = num - 1 val isStart = !countPerNum.containsKey(precedingNum) if (isStart) starts.add(num) } return starts } private fun isPossibleDivide( countPerNum: MutableMap<Int, Int>, startsOfConsecutiveNumbers: ArrayDeque<Int>, k: Int ): Boolean { val starts = startsOfConsecutiveNumbers while (starts.isNotEmpty()) { val start = starts.remove() val end = start + k - 1 val countOfStart = checkNotNull(countPerNum[start]) for (num in start..end) { val countOfNum = countPerNum[num] ?: 0 val newCount = countOfNum - countOfStart when { newCount < 0 -> return false newCount == 0 -> countPerNum.remove(num) else -> { countPerNum[num] = newCount val isNewStart = !countPerNum.containsKey(num - 1) if (isNewStart) starts.add(num) } } } val possibleNewStart = end + 1 val isNewStart = countPerNum[end] == null && countPerNum[possibleNewStart] != null if (isNewStart) starts.add(possibleNewStart) } return true } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,372
hj-leetcode-kotlin
Apache License 2.0
aoc21/day_13/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File data class Pos(val x: Int, val y: Int) data class Fold(val axe: Char, val n: Int) fun fold(dots: Set<Pos>, f: Fold): Set<Pos> = if (f.axe == 'x') { dots.filter { it.x < f.n } + dots.filter { it.x > f.n }.map { Pos(f.n - (it.x - f.n), it.y) } } else { dots.filter { it.y < f.n } + dots.filter { it.y > f.n }.map { Pos(it.x, f.n - (it.y - f.n)) } }.toSet() fun main() { val lines = File("input").readLines() var dots = lines .takeWhile { !it.isEmpty() } .map { it.split(",").map(String::toInt).let { Pos(it[0], it[1]) } } .toSet() var folds = lines .dropWhile { !it.isEmpty() } .drop(1) .map { Fold(it[11], it.split("=")[1].toInt()) } dots = fold(dots, folds[0]) println("First: ${dots.size}") dots = folds.drop(1).fold(dots) { d, f -> fold(d, f) } println("Second:") for (y in 0..dots.maxByOrNull { it.y }!!.y) { for (x in 0..dots.maxByOrNull { it.x }!!.x) { if (dots.contains(Pos(x, y))) print('#') else print('.') } println() } }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
1,141
advent-of-code
MIT License
src/aoc2022/Day02.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* internal class Day02(lines: List<String>) { init { lines.forEach { println(it) } } private val rounds = lines.map { listOf(it[0].code - 'A'.code, it[2].code - 'X'.code) } fun part1(): Int { return rounds.map { r -> // Computes the result of the round. // Lose = 0 // Tie = 3 // Win = 6 val outcome = Math.floorMod(r[1] - r[0] + 1, 3) * 3 (r[1] + 1) + outcome }.sum() } fun part2(): Int { return rounds .map { r -> val them = r[0] val result = r[1] val us = when (result) { 0 -> Math.floorMod(them - 1, 3) 2 -> Math.floorMod(them + 1, 3) else -> them } us + 1 + (result * 3) }.sum() } companion object { fun runDay() { val day = 2 val todayTest = Day02(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 15) val today = Day02(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 13675) execute(todayTest::part2, "Day[Test] $day: pt 2", 12) execute(today::part2, "Day $day: pt 2", 14184) } } } fun main() { Day02.runDay() }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
1,200
aoc2022
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day06.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2021 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readText import se.brainleech.adventofcode.toListOfInts import se.brainleech.adventofcode.verify class Aoc2021Day06 { companion object { private const val SPAWN_AGE = 8 private const val SPAWN_RATE = 6 } private fun List<Int>.toSchool(): MutableMap<Int, Long> { return this .groupingBy { it } .eachCount() .mapValues { it.value.toLong() } .toMutableMap() .withDefault { 0L } } private fun MutableMap<Int, Long>.ageAll() { for (age in 0 until (SPAWN_AGE + 1)) { this[age - 1] = this.getValue(age) } } private fun MutableMap<Int, Long>.spawnNew() { this[SPAWN_AGE] = this.getValue(-1) this[SPAWN_RATE] = this.getValue(SPAWN_RATE) + this.getValue(-1) } private fun MutableMap<Int, Long>.population(): Long { return this.filter { it.key >= 0 }.values.sum() } private fun solve(fishAges: List<Int>, days: Int): Long { val fishSchool = fishAges.toSchool() for (day in 0 until days) { fishSchool.ageAll() fishSchool.spawnNew() } return fishSchool.population() } fun part1(input: String, days: Int): Long { return solve(input.toListOfInts(), days) } fun part2(input: String, days: Int): Long { return solve(input.toListOfInts(), days) } } fun main() { val solver = Aoc2021Day06() val prefix = "aoc2021/aoc2021day06" val testData = readText("$prefix.test.txt") val realData = readText("$prefix.real.txt") verify(26L, solver.part1(testData, 18)) verify(59_34L, solver.part1(testData, 80)) verify(379_114L, solver.part1(realData, 80)) compute({ solver.part1(realData, 80) }, "$prefix.part1 = ") verify(26_984_457_539L, solver.part2(testData, 256)) compute({ solver.part2(realData, 256) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
2,045
adventofcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SuperUglyNumber.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.PriorityQueue import kotlin.math.min fun interface SuperUglyNumber { operator fun invoke(n: Int, primes: IntArray): Int } class SuperUglyNumberCommon : SuperUglyNumber { override operator fun invoke(n: Int, primes: IntArray): Int { val ugly = IntArray(n) val idx = IntArray(primes.size) ugly[0] = 1 for (i in 1 until n) { // find next ugly[i] = Int.MAX_VALUE for (j in primes.indices) ugly[i] = min(ugly[i], primes[j] * ugly[idx[j]]) // slip duplicate for (j in primes.indices) { while (primes[j] * ugly[idx[j]] <= ugly[i]) idx[j]++ } } return ugly[n - 1] } } class SuperUglyNumberRedundantMultiplication : SuperUglyNumber { override operator fun invoke(n: Int, primes: IntArray): Int { val ugly = IntArray(n) val idx = IntArray(primes.size) val values = IntArray(primes.size) { 1 } var next = 1 for (i in 0 until n) { ugly[i] = next next = Int.MAX_VALUE for (j in primes.indices) { // skip duplicate and avoid extra multiplication if (values[j] == ugly[i]) values[j] = ugly[idx[j]++] * primes[j] // find next ugly number next = min(next, values[j]) } } return ugly[n - 1] } } class SuperUglyNumberHeap : SuperUglyNumber { override operator fun invoke(n: Int, primes: IntArray): Int { val ugly = IntArray(n) val pq: PriorityQueue<Num> = PriorityQueue() for (i in primes.indices) pq.add(Num(primes[i], 1, primes[i])) ugly[0] = 1 for (i in 1 until n) { ugly[i] = pq.peek().value while (pq.peek().value == ugly[i]) { val nxt: Num = pq.poll() pq.add(Num(nxt.p * ugly[nxt.idx], nxt.idx + 1, nxt.p)) } } return ugly[n - 1] } class Num(var value: Int, var idx: Int, var p: Int) : Comparable<Num?> { override fun compareTo(other: Num?): Int { return value - other?.value!! } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,835
kotlab
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day06/Day06.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day06 import com.bloidonia.advent.readText // The trick is we only need to know how many are at each of the 9 stages of life (count needs to be a Long for Part 2) class Population(val population: Map<Int, Long>) { fun generation() = mutableMapOf<Int, Long>().let { nextGeneration -> (0..8).forEach { age -> population[age]?.let { popAtAge -> if (age == 0) { // Fish at stage 0 reset to 6 and spawn new fish at 8 nextGeneration[6] = popAtAge nextGeneration[8] = popAtAge } else { // Otherwise, they just get older nextGeneration[age - 1] = popAtAge + (nextGeneration[age - 1] ?: 0) } } } Population(nextGeneration); } fun size() = population.values.sumOf { it } } fun String.toPopulation() = Population(this.split(",").map { it.toInt() }.groupBy { it }.mapValues { it.value.size.toLong() }) fun main() { val initialPopulation = readText("/day06input.txt").toPopulation() // Part 1 val day80 = (1..80).fold(initialPopulation) { pop, _ -> pop.generation() } println(day80.size()) // Part 2 val day256 = (1..256).fold(initialPopulation) { pop, _ -> pop.generation() } println(day256.size()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,365
advent-of-kotlin-2021
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1466/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1466 /** * LeetCode page: [1466. Reorder Routes to Make All Paths Lead to the City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/); */ class Solution { /* Complexity: * Time O(n) and Space O(n); */ fun minReorder(n: Int, connections: Array<IntArray>): Int { val cityNeighbours = cityToItsNeighbours(n, connections) val cityDistances = cityToDistanceFromCapital(n, 0, cityNeighbours) return numReorderRoutes(connections, cityDistances) } private fun cityToItsNeighbours(numCities: Int, connections: Array<IntArray>): List<List<Int>> { val neighbours = List(numCities) { mutableListOf<Int>() } for ((origin, destination) in connections) { neighbours[origin].add(destination) neighbours[destination].add(origin) } return neighbours } private fun cityToDistanceFromCapital( numCities: Int, capital: Int, cityNeighbours: List<List<Int>> ): IntArray { val cityDistances = IntArray(numCities) { numCities } val destinationStack = ArrayDeque<Int>() cityDistances[capital] = 0 destinationStack.addLast(capital) while (destinationStack.isNotEmpty()) { val destination = destinationStack.removeLast() val origins = cityNeighbours[destination] for (origin in origins) { val distance = cityDistances[destination] + 1 val hasVisited = distance > cityDistances[origin] if (hasVisited) continue cityDistances[origin] = distance destinationStack.addLast(origin) } } return cityDistances } private fun numReorderRoutes(connections: Array<IntArray>, cityDistances: IntArray): Int { return connections.count { (origin, destination) -> cityDistances[origin] < cityDistances[destination] } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,028
hj-leetcode-kotlin
Apache License 2.0
src/day07/Day07.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day07 import readInput import java.util.* data class File(val name: String, val bytes: Int) data class Directory(val name: String, val files: MutableList<File> = mutableListOf(), val directories: MutableList<Directory> = mutableListOf(), val uuid: UUID = UUID.randomUUID()) { fun totalBytes(): Int { return files.sumOf { it.bytes } + directories.sumOf { it.totalBytes() } } fun findParentDirectoryOf(uuid: UUID): Directory? { return if (this.directories.any { it.uuid == uuid }) this else directories.firstNotNullOfOrNull { it.findParentDirectoryOf(uuid) } } } enum class CommandType { CD_ROOT, CD_UP, CD_IN, LS } data class Command(val type: CommandType, val param: String = "", val output: List<String> = emptyList()) fun main() { fun parseDirectoryContents(input: List<String>): Pair<List<Directory>, List<File>> { val directories = mutableListOf<Directory>() val files = mutableListOf<File>() input.forEach { i -> if (i.startsWith("dir ")) { directories.add(Directory(i.replace("dir ", ""))) } else { i.split(" ").also { tokens -> files.add(File(tokens[1], tokens[0].toInt())) } } } return directories to files } fun parseCommand(input: String, output: List<String>): Command { return if (input == "$ ls") Command(CommandType.LS, output = output) else if (input.startsWith("$ cd ")) { if (input.endsWith("/")) Command(CommandType.CD_ROOT) else if (input.endsWith("..")) Command(CommandType.CD_UP) else Command(CommandType.CD_IN, input.replace("$ cd ", "")) } else throw Exception("Invalid Command") } fun parseDirectories(input: List<String>): Directory { val rootDirectory = Directory("/") var currDirectory = rootDirectory fun execCommand(cmd: Command) { runCatching { when (cmd.type) { CommandType.CD_ROOT -> currDirectory = rootDirectory CommandType.CD_UP -> currDirectory = rootDirectory.findParentDirectoryOf(currDirectory.uuid)!! CommandType.CD_IN -> currDirectory = currDirectory.directories.find { it.name == cmd.param }!! CommandType.LS -> { parseDirectoryContents(cmd.output).also { parsed -> currDirectory.directories.addAll(parsed.first) currDirectory.files.addAll(parsed.second) } } } } } var nextCommand = "" val commandBuffer = mutableListOf<String>() input.forEach { i -> if (i.startsWith("$")) { if (nextCommand != "") { // We can now parse the previous command, since we know its output parseCommand(nextCommand, commandBuffer).also { execCommand(it) } } nextCommand = i commandBuffer.clear() } else { commandBuffer.add(i) } } // Need to manually do this for last one parseCommand(nextCommand, commandBuffer).also { execCommand(it) } return rootDirectory } // Find all of the directories with a total size of at most 100000. // What is the sum of the total sizes of those directories? fun part1(input: List<String>): Int { fun sumOfSizesUnderOrEqual(currDirectory: Directory, maxSize: Int): Int { val bytes = currDirectory.totalBytes().takeIf { it <= maxSize } ?: 0 return bytes + currDirectory.directories.sumOf { sumOfSizesUnderOrEqual(it, maxSize) } } return sumOfSizesUnderOrEqual(parseDirectories(input), 100000) } // Total System Space: 70,000,000 // Space Needed: 30,000,000 // Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. // What is the total size of that directory? fun part2(input: List<String>): Int { val totalSpace = 70000000 val spaceNeeded = 30000000 val rootDirectory = parseDirectories(input) val totalSpaceOccupied = rootDirectory.totalBytes() val minBytesToDelete = spaceNeeded - (totalSpace - totalSpaceOccupied) fun flattenedDirectorySizes(currDirectory: Directory): Map<UUID, Int> { return mutableMapOf(currDirectory.uuid to currDirectory.totalBytes()).also { map -> currDirectory.directories.forEach { dir -> map.putAll(flattenedDirectorySizes(dir)) } } } val toDelete = flattenedDirectorySizes(rootDirectory).let { map -> map.toList().sortedBy { it.second }.first { it.second >= minBytesToDelete } } return toDelete.second } val testInput = readInput("Day07_test") val input = readInput("Day07") println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 95437) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test] : ${part2(testInput)}") check(part2(testInput) == 24933642) println("Part 2 [Real] : ${part2(input)}") }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
5,471
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day09.kt
SimonMarquis
434,880,335
false
{"Kotlin": 38178}
import Neighborhood.VonNeumann class Day09(raw: List<String>) { private val input = raw.mapIndexed { y, line -> line.mapIndexed { x, height -> Point(x, y, height.toString().toInt()) }.toTypedArray() }.toTypedArray().let(::HeightMap) fun part1(): Int = with(input) { points.filter { it.isLow() } }.sumOf { it.riskLevel } fun part2(): Int = with(input) { points.groupingBy { it.flood() }.eachCount() }.filterKeys { it != null } .entries.sortedByDescending { it.value } .take(3) .fold(1) { acc, next -> acc * next.value } class HeightMap(private val map: Array<Array<Point>>) { val points: List<Point> get() = map.flatten() operator fun get(x: Int, y: Int): Point = map[y][x] private fun Point.neighbours() = map.neighboursOf(VonNeumann, x, y) fun Point.isLow() = neighbours().all { height < it.height } fun Point.flood(seen: Set<Point> = setOf(this)): Point? { if (height == 9) return null if (isLow()) return this val candidates = neighbours().filter { it.height < height } - seen return candidates.firstNotNullOfOrNull { it.flood(seen + candidates) } } } data class Point(val x: Int, val y: Int, val height: Int) { val riskLevel = height.inc() } }
0
Kotlin
0
0
8fd1d7aa27f92ba352e057721af8bbb58b8a40ea
1,372
advent-of-code-2021
Apache License 2.0
kotlin/src/x2023/Day04.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package x2023 open class Day04AExample { open val inputLines: List<String> = read2023Input("day04-example") open val expected = 13 open var answer: Int = 0 fun run() { answer = inputLines.sumOf { line -> val lines = line.split(":") val card = lines[0] val numbers = lines[1].split("|") val winning = numbers[0].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toSet() val mine = numbers[1].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toSet() val won = winning.intersect(mine) when (val count = won.count()) { 0 -> 0 else -> (count - 1).downTo(1).fold(1) { acc, _ -> acc * 2 } } as Int } } fun check() { println(this.javaClass.name) println("answer: $answer") println("expected: $expected") assert(answer == expected) println() } } class Day04A : Day04AExample() { override val inputLines: List<String> = read2023Input("day04") override val expected = 18519 } open class Day04BExample { open val inputLines: List<String> = read2023Input("day04-example") open val expected = 467835 open var answer: Int = 0 fun run() { var numbers = mutableListOf<Entry>() var symbols = mutableListOf<Symbol>() inputLines.forEachIndexed { lidx, line -> var cnum = 0 var numStart = -1 var constuctingNumber = false line.forEachIndexed { cidx, char -> if (char.isDigit()) { if (!constuctingNumber) { numStart = cidx } cnum = cnum * 10 + char.toString().toInt() constuctingNumber = true } else { if (constuctingNumber) { constuctingNumber = false numbers.add(Entry(cnum, lidx, numStart, cidx - 1)) cnum = 0 numStart = -1 } if (char != '.') { symbols.add(Symbol(char, cidx, lidx)) } } } if (constuctingNumber) { // number at end of the line numbers.add(Entry(cnum, lidx, numStart, line.length - 1)) } } answer = symbols.filter { symb -> symb.char == '*' }.sumOf { symb -> symb.gearRatio(numbers) } } fun check() { println(this.javaClass.name) println("answer: $answer") println("expected: $expected") assert(answer == expected) println() } } class Day04B : Day04BExample() { override val inputLines: List<String> = read2023Input("day04") override val expected = 87287096 } fun main() { Day04AExample().also { it.run() it.check() } Day04A().also { it.run() it.check() } Day04BExample().also { it.run() it.check() } Day04B().also { it.run() it.check() } }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
3,190
adventOfCode
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Day17.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day17(input: List<String>) { private val grid = input.toGrid().mapValues { it.value.digitToInt() } private val start = grid.region().topLeft private val goal = grid.region().bottomRight private data class State(val pos: Vector2, val dir: Direction, val straightMoves: Int) { fun nextStates() = buildList { add(State(pos + dir.turnLeft().vector(), dir.turnLeft(), 1)) add(State(pos + dir.turnRight().vector(), dir.turnRight(), 1)) if (straightMoves < 3) { add(State(pos + dir.vector(), dir, straightMoves + 1)) } } fun ultraNextStates() = buildList { if (straightMoves == 0 || straightMoves >= 4) { add(State(pos + dir.turnLeft().vector(), dir.turnLeft(), 1)) add(State(pos + dir.turnRight().vector(), dir.turnRight(), 1)) } if (straightMoves < 10) { add(State(pos + dir.vector(), dir, straightMoves + 1)) } } } fun solvePart1() = aStar( State(start, Direction.EAST, 0), { it.pos == goal }, { it.nextStates().filter { next -> next.pos in grid } }, { _, (pos) -> grid[pos]!! }, { it.pos.manhattanDistanceTo(goal) }, ).score() fun solvePart2() = aStar( State(start, Direction.EAST, 0), { it.pos == goal && it.straightMoves >= 4 }, { it.ultraNextStates().filter { next -> next.pos in grid } }, { _, (pos) -> grid[pos]!! }, { it.pos.manhattanDistanceTo(goal) }, ).score() }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
1,625
advent-2023
MIT License
src/Day04.kt
Olivki
573,156,936
false
{"Kotlin": 11297}
fun main() { fun parseRange(text: String): List<Int> { val (a, b) = text.split('-') return (a.toInt()..b.toInt()).toList() } fun parseInput(input: List<String>) = input .asSequence() .filter { it.isNotBlank() } .map { it.split(',') } .map { (a, b) -> parseRange(a) to parseRange(b) } fun part1(input: List<String>) = parseInput(input) .count { (a, b) -> a.containsAll(b) || b.containsAll(a) } fun part2(input: List<String>) = parseInput(input) .count { (a, b) -> a.any { it in b } || b.any { it in a } } val testInput = readTestInput("Day04") // p1 check(part1(testInput) == 2) // p2 check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
51c408f62589eada3d8454740c9f6fc378e2d09b
811
aoc-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/TwoSumIiInputArrayIsSorted.kt
faniabdullah
382,893,751
false
null
//Given a 1-indexed array of integers numbers that is already sorted in non- //decreasing order, find two numbers such that they add up to a specific target //number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first //< second <= numbers.length. // // Return the indices of the two numbers, index1 and index2, as an integer //array [index1, index2] of length 2. // // The tests are generated such that there is exactly one solution. You may not //use the same element twice. // // // Example 1: // // //Input: numbers = [2,7,11,15], target = 9 //Output: [1,2] //Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. // // // Example 2: // // //Input: numbers = [2,3,4], target = 6 //Output: [1,3] //Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. // // // Example 3: // // //Input: numbers = [-1,0], target = -1 //Output: [1,2] //Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. // // // // Constraints: // // // 2 <= numbers.length <= 3 * 10⁴ // -1000 <= numbers[i] <= 1000 // numbers is sorted in non-decreasing order. // -1000 <= target <= 1000 // The tests are generated such that there is exactly one solution. // // Related Topics Array Two Pointers Binary Search 👍 3691 👎 806 package leetcodeProblem.leetcode.editor.en class TwoSumIiInputArrayIsSorted { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun twoSum(numbers: IntArray, target: Int): IntArray { // 2,3,5,6,7,11,15 , 18 , 19 = 9 var left = 0 var right = numbers.size - 1 while (left < right) { val sum = numbers[left] + numbers[right] if (sum > target) right-- else if (sum < target) left++ else return intArrayOf(left + 1, right + 1) } return intArrayOf(-1, -1) } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,172
dsa-kotlin
MIT License
kotlin/src/Day07.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.Integer.parseInt import java.lang.Long.parseLong import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val positions = input.first().split(",").map(::parseInt) val maxPosition = positions.maxOrNull()!! return (0..maxPosition).fold(positions.size * maxPosition) { latestMax, finalPosition -> val potentialMax = positions.sumOf { position -> abs(finalPosition - position) } if (potentialMax < latestMax) { potentialMax } else { latestMax } } } fun part2(input: List<String>): Long { val positions = input.first().split(",").map(::parseLong) val maxPosition = positions.maxOrNull()!! return (0..maxPosition).fold(positions.size * maxPosition * maxPosition) { latestMax, finalPosition -> val potentialMax = positions.sumOf { position -> val distance = abs(finalPosition - position) distance * (distance + 1) / 2 } if (potentialMax < latestMax) { potentialMax } else { latestMax } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 37) { "${part1(testInput)}" } check(part2(testInput) == 168L) { "${part2(testInput)}" } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
1,535
aoc-2021
MIT License
2022/src/main/kotlin/sh/weller/aoc/Day02.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc object Day02 : SomeDay<Pair<Char, Char>, Int> { override fun partOne(input: List<Pair<Char, Char>>): Int = input .map { val (opponent, me) = it Shape.fromSymbol(opponent) to Shape.fromSymbol(me) } .map { val (opponent, me) = it val outcome = when { me == opponent -> Outcome.Draw me == Shape.Rock && opponent == Shape.Paper -> Outcome.Loss me == Shape.Rock && opponent == Shape.Scissor -> Outcome.Win me == Shape.Paper && opponent == Shape.Scissor -> Outcome.Loss me == Shape.Paper && opponent == Shape.Rock -> Outcome.Win me == Shape.Scissor && opponent == Shape.Paper -> Outcome.Win me == Shape.Scissor && opponent == Shape.Rock -> Outcome.Loss else -> throw IllegalArgumentException("Unknown combination") } return@map outcome.points + me.points } .sum() override fun partTwo(input: List<Pair<Char, Char>>): Int = input .map { val (opponent, me) = it Shape.fromSymbol(opponent) to Shape.fromSymbol(me) } .map { val (opponent, me) = it when { // X == Loose me == Shape.Rock -> { val choose = when (opponent) { Shape.Rock -> Shape.Scissor Shape.Paper -> Shape.Rock Shape.Scissor -> Shape.Paper } choose.points + Outcome.Loss.points } // Y == Draw me == Shape.Paper -> { opponent.points + Outcome.Draw.points } // Y == Win me == Shape.Scissor -> { val choose = when (opponent) { Shape.Rock -> Shape.Paper Shape.Paper -> Shape.Scissor Shape.Scissor -> Shape.Rock } choose.points + Outcome.Win.points } else -> throw IllegalArgumentException("Unknown Combination") } }.sum() enum class Outcome(val points: Int) { Win(6), Loss(0), Draw(3); } enum class Shape(val opponentSymbol: Char, val selfSymbol: Char, val points: Int) { Rock('A', 'X', 1), Paper('B', 'Y', 2), Scissor('C', 'Z', 3); companion object { fun fromSymbol(char: Char): Shape = when (char) { 'A' -> Rock 'X' -> Rock 'B' -> Paper 'Y' -> Paper 'C' -> Scissor 'Z' -> Scissor else -> throw IllegalArgumentException("Unknown Shape") } } } }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
3,184
AdventOfCode
MIT License
src/day03/Day03.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day03 import readInputString fun main() { fun calculatePriority(c: Char): Long { var priority = 0L if (c.isUpperCase()) { priority += 26L } priority += c.lowercaseChar().code - 96 return priority } fun part1(input: List<String>): Long { var priorityTotal = 0L for (line in input) { val sack1 = line.substring(0, line.length / 2) val sack2 = line.substring(line.length / 2, line.length) for (c in sack1) { if (sack2.contains(c)) { priorityTotal += calculatePriority(c) break } } } return priorityTotal } fun part2(input: List<String>): Long { var priorityTotal = 0L for (i in 0 until input.size / 3) { val sack1 = input[i * 3] val sack2 = input[i * 3 + 1] val sack3 = input[i * 3 + 2] for (c in sack1) { if (sack2.contains(c) && sack3.contains(c)) { priorityTotal += calculatePriority(c) break } } } return priorityTotal } val testInput = readInputString("day03/test") val input = readInputString("day03/input") // test if implementation meets criteria from the description, like: check(part1(testInput) == 157L) println(part1(input)) check(part2(testInput) == 70L) println(part2(input)) }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
1,531
Advent-Of-Code-2022
Apache License 2.0
src/Day03.kt
vi-quang
573,647,667
false
{"Kotlin": 49703}
/** * Main ------------------------------------------------------------------- */ fun main() { /** * Compartment ------------------------------------------------------------------- */ data class Compartment(val itemList: MutableList<Char> = mutableListOf()) { fun contains(c: Char) : Boolean { return itemList.contains(c) } } fun Compartment.intersect(other: Compartment) : Set<Char> { return other.itemList.intersect(this.itemList.toSet()) } /** * Rucksack ------------------------------------------------------------------- */ data class Rucksack(val compartments: MutableList<Compartment> = mutableListOf()) { init { compartments.add(Compartment()) compartments.add(Compartment()) } fun contains(c : Char) : Boolean { for (compartment in compartments) { if (compartment.contains(c)) { return true } } return false } } fun Rucksack.intersect(other: Rucksack) : Set<Char> { val returnList = mutableSetOf<Char>() for (compartment in other.compartments) { for (item in compartment.itemList) { if (this.contains(item)) { returnList.add(item) } } } return returnList.toSet() } fun Rucksack.intersect(other: Set<Char>) : Set<Char> { val returnList = mutableSetOf<Char>() for (c in other) { if (this.contains(c)) { returnList.add(c) } } return returnList.toSet() } /** * Misc ------------------------------------------------------------------- */ fun String.toDeque() : ArrayDeque<Char> { val deque = ArrayDeque<Char>() val array = this.toCharArray() for (c in array) { deque.addLast(c) } return deque } fun Char.priority() : Int { val priority = ('a' .. 'z') + ('A' .. 'Z') return priority.indexOf(this) + 1 } fun createRucksackList(input: List<String>) : MutableList<Rucksack> { val rucksacks = mutableListOf<Rucksack>() for (line in input) { val rucksack = Rucksack() val deque = line.toDeque() while (deque.size > 0) { rucksack.compartments[0].itemList.add(deque.removeFirst()) rucksack.compartments[1].itemList.add(deque.removeLast()) } rucksacks.add(rucksack) } return rucksacks } fun part1(input: List<String>): Int { var total = 0 val rucksacks = createRucksackList(input) for (rucksack in rucksacks) { val intersections = rucksack.compartments[0].intersect(rucksack.compartments[1]) total += intersections.sumOf { it.priority() } } return total } fun part2(input: List<String>): Int { var total = 0 val rucksacks = createRucksackList(input) for (index in 1 .. rucksacks.size step 3) { val rucksack1 = rucksacks[index - 1] val rucksack2 = rucksacks[index] val rucksack3 = rucksacks[index + 1] var intersections = rucksack1.intersect(rucksack2) intersections = rucksack3.intersect(intersections) total += intersections.sumOf { it.priority() } } return total } val input = readInput(3) println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
ae153c99b58ba3749f16b3fe53f06a4b557105d3
3,634
aoc-2022
Apache License 2.0
src/adventofcode/Day11.kt
Timo-Noordzee
573,147,284
false
{"Kotlin": 80936}
package adventofcode import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit private operator fun Monkey.times(other: Monkey) = amountOfInspections.toLong() * other.amountOfInspections private data class Monkey( private var items: ArrayDeque<Long>, private val inspect: (item: Long) -> Long, val divisor: Int, private val monkeyWhenTrue: Int, private val monkeyWhenFalse: Int, var amountOfInspections: Int = 0, ) { fun addItem(item: Long) = items.add(item) fun takeTurn(lowerWorryLevel: Boolean, mod: Int = 0): List<Pair<Long, Int>> = buildList { while (items.isNotEmpty()) { amountOfInspections++ val item = items.removeFirst() val worryLevel = if (lowerWorryLevel) inspect(item % mod) / 3 else inspect(item % mod) add(worryLevel to if (worryLevel % divisor == 0L) monkeyWhenTrue else monkeyWhenFalse) } } companion object { fun fromInput(input: List<String>): Monkey = Monkey( items = ArrayDeque(input[1].substringAfter(": ").split(',').map { it.trim().toInt().toLong() }), inspect = input[2].substringAfter("= ").split(" ").let { (a, operator, b) -> { old -> val left = if (a == "old") old else a.toInt().toLong() val right = if (b == "old") old else b.toInt().toLong() when (operator[0]) { '+' -> left + right '*' -> left * right else -> error("check input") } } }, divisor = input[3].substringAfterLast(' ').toInt(), monkeyWhenTrue = input[4].substringAfterLast(' ').toInt(), monkeyWhenFalse = input[5].substringAfterLast(' ').toInt() ) } } @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 0) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) class Day11 { var input: List<String> = emptyList() @Setup fun setup() { input = readInput("Day11") } private fun solve(numberOfSimulations: Int, doesWorryLevelLower: Boolean): Long { val monkeys = input.chunked(7).map { Monkey.fromInput(it) } val commonDivisor = monkeys.map { it.divisor }.reduce { a, b -> a * b } repeat(numberOfSimulations) { monkeys.forEach { monkey -> monkey.takeTurn(doesWorryLevelLower, commonDivisor).forEach { (item, nextMonkey) -> monkeys[nextMonkey].addItem(item) } } } val (mostActive, secondMostActive) = monkeys.sortedBy { monkey -> -monkey.amountOfInspections } return mostActive * secondMostActive } @Benchmark fun part1() = solve(20, true) @Benchmark fun part2(): Long = solve(10_000, false) } fun main() { val day11 = Day11() // test if implementation meets criteria from the description, like: day11.input = readInput("Day11_test") check(day11.part1() == 10605L) check(day11.part2() == 2713310158) day11.input = readInput("Day11") println(day11.part1()) println(day11.part2()) }
0
Kotlin
0
2
10c3ab966f9520a2c453a2160b143e50c4c4581f
3,204
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0882_reachable_nodes_in_subdivided_graph // #Hard #Heap_Priority_Queue #Graph #Shortest_Path // #2023_04_08_Time_434_ms_(100.00%)_Space_52_MB_(100.00%) import java.util.PriorityQueue class Solution { fun reachableNodes(edges: Array<IntArray>, maxMoves: Int, n: Int): Int { val adList = getAdList(edges, n) val pQueue = PriorityQueue { a: IntArray, b: IntArray -> a[1] - b[1] } val minDis = IntArray(n) var res = 0 pQueue.add(intArrayOf(0, 0)) while (pQueue.isNotEmpty()) { val poll = pQueue.poll() val node = poll[0] val dist = poll[1] if (minDis[node] > 0) continue res++ minDis[node] = dist for (child in adList[node]!!) { val cNode = child!![0] val weight = child[1] if (cNode != 0 && minDis[cNode] == 0) { res += (maxMoves - dist).coerceAtMost(weight) val cNodeDist = dist + weight + 1 if (cNodeDist <= maxMoves) pQueue.add(intArrayOf(cNode, cNodeDist)) } else { res += (weight - (maxMoves - minDis[cNode]).coerceAtMost(weight)).coerceAtMost( (maxMoves - dist).coerceAtMost(weight) ) } } } return res } private fun getAdList(edges: Array<IntArray>, n: Int): Array<ArrayList<IntArray?>?> { val adList: Array<ArrayList<IntArray?>?> = arrayOfNulls<ArrayList<IntArray?>?>(n) adList[0] = ArrayList() for (edge in edges) { val s = edge[0] val d = edge[1] val w = edge[2] if (adList[s] == null) adList[s] = ArrayList() if (adList[d] == null) adList[d] = ArrayList() adList[s]?.add(intArrayOf(d, w)) adList[d]?.add(intArrayOf(s, w)) } return adList } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,997
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ScheduleCourse3.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import kotlin.math.max /** * 630. Course Schedule III * @see <a href="https://leetcode.com/problems/course-schedule-iii/">Source</a> */ fun interface ScheduleCourse3 { operator fun invoke(courses: Array<IntArray>): Int } /** * Approach 2: Recursion with Memoization */ class ScheduleCourse3Recursion : ScheduleCourse3 { override operator fun invoke(courses: Array<IntArray>): Int { courses.sortWith { a, b -> a[1] - b[1] } val memo = Array(courses.size) { arrayOfNulls<Int>( courses[courses.size - 1][1] + 1, ) } return schedule(courses, 0, 0, memo) } private fun schedule(courses: Array<IntArray>, i: Int, time: Int, memo: Array<Array<Int?>>): Int { if (i == courses.size) return 0 if (memo[i][time] != null) { return memo[i][time]!! } var taken = 0 if (time + courses[i][0] <= courses[i][1]) taken = 1 + schedule(courses, i + 1, time + courses[i][0], memo) val notTaken = schedule(courses, i + 1, time, memo) memo[i][time] = max(taken, notTaken) return memo[i][time]!! } } /** * Approach 3: Iterative Solution */ class ScheduleCourse3Iterative : ScheduleCourse3 { override operator fun invoke(courses: Array<IntArray>): Int { courses.sortWith { a: IntArray, b: IntArray -> a[1] - b[1] } var time = 0 var count = 0 for (i in courses.indices) { if (time + courses[i][0] <= courses[i][1]) { time += courses[i][0] count++ } else { var maxI = i for (j in 0 until i) { if (courses[j][0] > courses[maxI][0]) maxI = j } if (courses[maxI][0] > courses[i][0]) { time += courses[i][0] - courses[maxI][0] } courses[maxI][0] = -1 } } return count } } /** * Approach 4: Optimized Iterative */ class ScheduleCourse3OptimizedIterative : ScheduleCourse3 { override operator fun invoke(courses: Array<IntArray>): Int { courses.sortWith { a: IntArray, b: IntArray -> a[1] - b[1] } var time = 0 var count = 0 for (i in courses.indices) { if (time + courses[i][0] <= courses[i][1]) { time += courses[i][0] courses[count++] = courses[i] } else { var maxI = i for (j in 0 until count) { if (courses[j][0] > courses[maxI][0]) maxI = j } if (courses[maxI][0] > courses[i][0]) { time += courses[i][0] - courses[maxI][0] courses[maxI] = courses[i] } } } return count } } /** * Approach 5: Extra List */ class ScheduleCourse3ExtraList : ScheduleCourse3 { override operator fun invoke(courses: Array<IntArray>): Int { courses.sortWith { a: IntArray, b: IntArray -> a[1] - b[1] } val validList: MutableList<Int> = ArrayList() var time = 0 for (c in courses) { if (time + c[0] <= c[1]) { validList.add(c[0]) time += c[0] } else { var maxI = 0 for (i in 1 until validList.size) { if (validList[i] > validList[maxI]) maxI = i } if (validList.isNotEmpty() && validList[maxI] > c[0]) { time += c[0] - validList[maxI] validList[maxI] = c[0] } } } return validList.size } } /** * Approach 6: Priority Queue * Time complexity : O(n log n). * Space complexity : O(n). */ class ScheduleCourse3PriorityQueue : ScheduleCourse3 { override operator fun invoke(courses: Array<IntArray>): Int { courses.sortWith { a: IntArray, b: IntArray -> a[1] - b[1] } val queue: PriorityQueue<Int> = PriorityQueue { a, b -> b - a } var time = 0 for (c in courses) { if (time + c[0] <= c[1]) { queue.offer(c[0]) time += c[0] } else if (queue.isNotEmpty() && queue.peek() > c[0]) { time += c[0] - queue.poll() queue.offer(c[0]) } } return queue.size } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,183
kotlab
Apache License 2.0
change/src/main/kotlin/Change.kt
3mtee
98,672,009
false
null
class ChangeCalculator(coins: List<Int>) { private val coins = coins.reversed() fun computeMostEfficientChange(grandTotal: Int): List<Int> { require(grandTotal >= 0) { "Negative totals are not allowed." } require((grandTotal == 0) || (grandTotal >= this.coins.minOrNull()!!)) { "The total $grandTotal cannot be represented in the given currency." } return computeChange(grandTotal).sorted() } private fun computeChange(grandTotal: Int): List<Int> { val changes = mutableListOf<List<Int>>() 0.rangeTo(grandTotal) .map { change -> changes.add(computeMinChange(change, changes)) } return changes[grandTotal].takeIf { it.sum() == grandTotal } ?: throw IllegalArgumentException("The total $grandTotal cannot be represented in the given currency.") } private fun computeMinChange(changeAmount: Int, lowerChanges: List<List<Int>>) = this.coins // filter out coins which are greater than the change amount .filter { it <= changeAmount } // group lower change amounts using bigger coins .map { listOf(it) + lowerChanges[changeAmount - it] } // filter out coin combos which aren't equal to the change amount .filter { it.sum() == changeAmount } // get the lowest number of coins for the change amount .minByOrNull { it.size } ?: emptyList() }
0
Kotlin
0
0
6e3eb88cf58d7f01af2236e8d4727f3cd5840065
1,438
exercism-kotlin
Apache License 2.0
src/main/kotlin/day20/Day20.kt
daniilsjb
434,765,082
false
{"Kotlin": 77544}
package day20 import java.io.File fun main() { val data = parse("src/main/kotlin/day20/Day20.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 20 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private fun parse(path: String): Enhance { val (algorithm, bits) = File(path) .readText() .trim() .split("""(\n\n)|(\r\n\r\n)""".toRegex()) return Enhance(bits.toImage(), algorithm) } private fun String.toImage(): Image = this.lines() .let { lines -> lines.joinToString(separator = "") to lines.size } .let { (bitmap, size) -> Image(bitmap, size) } private data class Enhance( val image: Image, val algorithm: String, ) private data class Image( val bitmap: String, val size: Int, val fill: Char = '.', ) private fun <T> Iterable<T>.cross(other: Iterable<T>): List<Pair<T, T>> = this.flatMap { a -> other.map { b -> a to b } } private operator fun Image.get(x: Int, y: Int): Char = if (x in 0 until size && y in 0 until size) { bitmap[y * size + x] } else { fill } private fun Image.adjacent(x: Int, y: Int): List<Char> = (-1..1).cross(-1..1) .map { (dy, dx) -> this[x + dx, y + dy] } private fun Image.indexAt(x: Int, y: Int): Int = this.adjacent(x, y) .fold(0) { acc, c -> acc shl 1 or if (c == '#') 1 else 0 } private fun Enhance.step(): Enhance { // After each iteration, the image expands one unit in each direction, // increasing the length of its sides by 2 in total. val size = image.size + 2 val side = -1 until image.size + 1 val bitmap = (side).cross(side) .map { (y, x) -> image.indexAt(x, y) } .map { index -> algorithm[index] } .joinToString(separator = "") val fill = if (image.fill == '.') { algorithm.first() } else { algorithm.last() } return this.copy(image = Image(bitmap, size, fill)) } private fun Enhance.perform(iterations: Int): Image = generateSequence(this) { p -> p.step() } .elementAt(iterations).image private fun Enhance.countAfter(iterations: Int): Int = perform(iterations) .bitmap.count { pixel -> pixel == '#' } private fun part1(enhance: Enhance): Int = enhance.countAfter(iterations = 2) private fun part2(enhance: Enhance): Int = enhance.countAfter(iterations = 50)
0
Kotlin
0
1
bcdd709899fd04ec09f5c96c4b9b197364758aea
2,501
advent-of-code-2021
MIT License
src/Day01.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
fun main() { fun part1(input: List<String>): Int { var current = 0 var max: Int = -1 input.forEach {s: String -> when { s.isEmpty() -> { max = maxOf(max, current) current = 0 } else -> { current += s.toInt() } } } max = maxOf(max, current) return max } fun part2(input: List<String>): Int { var current = 0 val max = intArrayOf(-1, -1, -1, -1) input.forEach {s: String -> when { s.isEmpty() -> { max[3] = current max.sortDescending() max[3] = -1 current = 0 } else -> { current += s.toInt() } } } max[3] = current max.sortDescending() max[3] = 0 return max.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
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
1,275
aoc22-kotlin
Apache License 2.0
2021/src/Day19.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import kotlin.math.abs import kotlin.math.max // https://adventofcode.com/2021/day/19 fun main() { class Position(x: Int, y: Int, z: Int) { val x = x val y = y val z = z override fun toString(): String { return "($x,$y,$z)" } override fun equals(other: Any?): Boolean { return (other is Position) && x == other.x && y == other.y && z == other.z } fun rotateX() : Position { return Position(x, -z, y) } fun rotateY() : Position { return Position(-z, y, x) } fun rotateZ() : Position { return Position(y, -x, z) } fun vectorTo(other: Position) : Position { return Position(other.x - x, other.y - y, other.z - z) } fun addVector(vector: Position) : Position { return Position(vector.x + x, vector.y + y, vector.z + z) } fun subtractVector(vector: Position) : Position { return Position(x - vector.x, y - vector.y, z - vector.z) } fun manhattanDistanceTo(other: Position) : Int { return abs(other.x - x) + abs(other.y - y) + abs(other.z - z) } fun allRotations(): Array<Position> { return arrayOf( Position(x,y,z), Position(-z,y,x), Position(y,z,x), Position(z,-y,x), Position(-y,-z,x), Position(-z,x,-y), Position(x,z,-y), Position(z,-x,-y), Position(-x,-z,-y), Position(-z,-y,-x), Position(-y,z,-x), Position(z,y,-x), Position(y,-z,-x), Position(-z,-x,y), Position(-x,z,y), Position(z,x,y), Position(x,-z,y), Position(-y,x,z), Position(y,-x,z), Position(-x,-y,z), Position(-y,-x,-z), Position(-x,y,-z), Position(y,x,-z), Position(x,-y,-z) ) // val result = mutableListOf<Position>() // var current = this // // for (x in 0..3) { // current = current.rotateX() // for (y in 0..3) { // current = current.rotateY() // for (z in 0..3) { // current = current.rotateZ() // result.add(current) // } // } // } // // return result.distinctBy { Triple(it.x, it.y, it.z) } } } class Scanner(id: String) { val id = id var beacons = mutableListOf<Position>() val alreadyComparedWith = mutableListOf<Scanner>() var rotationIndex : Int? = null var position: Position? = null override fun toString(): String { return id } } fun readScanners() : List<Scanner> { val scanners = mutableListOf<Scanner>() var currentScanner : Scanner? = null for (line in readInput("Day19")) { if (line.startsWith("---")) { currentScanner = Scanner(line) scanners.add(currentScanner) continue } if (line.isEmpty()) { continue } var numbers = line.split(",").map { it.toInt() } currentScanner!!.beacons.add(Position(numbers[0], numbers[1], numbers[2])) } return scanners } fun compare(scannerA: Scanner, scannerB: Scanner) : Boolean { scannerB.alreadyComparedWith.add(scannerA) for (rotationIndex in 0..23) { // println("Checking for rotation $rotationIndex") for (ba in scannerA.beacons) { for (bb in scannerB.beacons) { val rotatedBeaconB = bb.allRotations()[rotationIndex] val translationBtoA = rotatedBeaconB.vectorTo(ba) val translatedBeaconsB = scannerB.beacons.map { it.allRotations()[rotationIndex].addVector(translationBtoA) } val matches = translatedBeaconsB.filter { scannerA.beacons.contains(it) } if (matches.count() >= 12) { scannerB.beacons = translatedBeaconsB.toMutableList() scannerB.rotationIndex = rotationIndex scannerB.position = translationBtoA println("Match found! Assuming $ba == $bb, rotation: $rotationIndex, translation: $translationBtoA, matches: $matches. Scanner $scannerB position is ${scannerB.position}") println("Matching beacons: $matches") return true } } } } return false } fun part1() { val scanners = readScanners() // 1. Assume that first scanner's coords are (0,0) and rotation is 0 // 2. For rotation 0 assume that s1 b0 == s2 b0 and compute translation between them // 3. Apply the transformation to other beacons of s2 and check how many beacons are matching // 4. If there are no matches assume that s1 b0 == s2 b1 and compute translation between them // 5. Apply the transformation to other beacons of s2 and check how many beacons are matching (if there's e.g. more than 3 store that transformation assuming that it might be the correct rotation) // 6. ... repeat for each beacon of s2 // 7. If there's >= 12 matching beacons mark s2 as matched and save its transformation (or store beacons transformed in relation to s0). Also compute its position. // 8. ... repeat for all scanners // 9. for all non-matched scanners try matching with newly discovered scanners val firstScanner = scanners.first() firstScanner.position = Position(0, 0, 0) firstScanner.rotationIndex = 0 val discoveredScanners = mutableListOf(firstScanner) var scannersToCheck = listOf(firstScanner) while (discoveredScanners.count() < scanners.count()) { val newScannersToCheck = mutableListOf<Scanner>() for (scannerA in scannersToCheck) { for (scannerB in (scanners.minus(discoveredScanners.toSet()).filter { !it.alreadyComparedWith.contains(scannerA) })) { println("Comparing $scannerA with $scannerB") if (compare(scannerA, scannerB)) { discoveredScanners.add(scannerB) newScannersToCheck.add(scannerB) } } } scannersToCheck = newScannersToCheck } val uniqueBeaconsCount = scanners.flatMap { it.beacons }.distinctBy { it.toString() }.count() println(uniqueBeaconsCount) var maxManhattanDistance = 0 for (scannerA in scanners) { for (scannerB in scanners) { val distance = scannerA.position!!.manhattanDistanceTo(scannerB.position!!) if (distance > maxManhattanDistance) { maxManhattanDistance = distance } } } println("Max manhattan distance is: $maxManhattanDistance") } fun part2() { } part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
6,458
advent-of-code
Apache License 2.0
y2020/src/main/kotlin/adventofcode/y2020/Day12.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import kotlin.math.absoluteValue fun main() = Day12.solve() object Day12 : AdventSolution(2020, 12, "Rain Risk") { override fun solvePartOne(input: String): Int { var orientation = 0 var px = 0 var py = 0 fun process(instr: Char, v: Int) { when (instr) { 'N' -> py += v 'E' -> px += v 'S' -> py -= v 'W' -> px -= v 'L' -> orientation = (orientation + 360 - v) % 360 'R' -> orientation = (orientation + v) % 360 'F' -> when (orientation) { 0 -> process('E', v) 90 -> process('S', v) 180 -> process('W', v) 270 -> process('N', v) else -> throw IllegalStateException() } } } input .lines() .map { it[0] to it.drop(1).toInt() } .forEach { process(it.first, it.second) } return px.absoluteValue + py.absoluteValue } override fun solvePartTwo(input: String): Any { var ship = Vec2(0, 0) var waypoint = Vec2(10, 1) fun process(instr: Char, v: Int) { when (instr) { 'N' -> waypoint += Vec2(0, v) 'S' -> waypoint -= Vec2(0, v) 'E' -> waypoint += Vec2(v, 0) 'W' -> waypoint -= Vec2(v, 0) 'L' -> repeat(v / 90) { waypoint = Vec2(-waypoint.y, waypoint.x) } 'R' -> repeat(v / 90) { waypoint = Vec2(waypoint.y, -waypoint.x) } 'F' -> ship += waypoint * v } } input .lines() .map { it[0] to it.drop(1).toInt() } .forEach { process(it.first, it.second) } return ship.x.absoluteValue + ship.y.absoluteValue } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,058
advent-of-code
MIT License
src/Day14.kt
risboo6909
572,912,116
false
{"Kotlin": 66075}
enum class Entity { ROCK, BALL, } private infix fun Int.toward(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this, to, step) } fun main() { val source = Vector2(500, 0) fun makeObstacles(input: List<String>): MutableMap<Vector2, Entity> { val res = mutableMapOf<Vector2, Entity>() for (line in input) { val tmp = line.split(" -> ").map{ it -> it.split(',').map { it.toInt() } } tmp.zipWithNext().forEach{ (fst, snd) -> val (x0, y0) = fst val (x1, y1) = snd if (x0 != x1) { for (x in (x0 toward x1)) { res[Vector2(x, y1)] = Entity.ROCK } } else if (y1 != y0) { for (y in y0 toward y1) { res[Vector2(x0, y)] = Entity.ROCK } } } } return res } fun advance(field: MutableMap<Vector2, Entity>, coords: Vector2, floorLevel: Int = -1): Vector2? { val (x, y) = coords if (y == floorLevel) { field.remove(Vector2(x, y)) field[Vector2(x, y-1)] = Entity.BALL return null } if (!field.containsKey(Vector2(x, y+1))) { field.remove(Vector2(x, y)) field[Vector2(x, y+1)] = Entity.BALL return Vector2(x, y+1) } if (!field.containsKey(Vector2(x-1, y+1))) { field.remove(Vector2(x, y)) field[Vector2(x-1, y+1)] = Entity.BALL return Vector2(x-1, y+1) } if (!field.containsKey(Vector2(x+1, y+1))) { field.remove(Vector2(x, y)) field[Vector2(x+1, y+1)] = Entity.BALL return Vector2(x+1, y+1) } return null } fun part1(input: List<String>): Int { val field = makeObstacles(input) val maxY = field.keys.maxBy { it.second }.second var curPos: Vector2? = source var balls = 0 while (curPos!!.second <= maxY) { curPos = advance(field, curPos) if (curPos == null) { balls++ curPos = source } } return balls } fun part2(input: List<String>): Int { val field = makeObstacles(input) val maxY = field.keys.maxBy { it.second }.second var curPos: Vector2? = source var balls = 0 while (true) { curPos = advance(field, curPos!!, floorLevel=maxY+2) if (field[source] == Entity.BALL) { return ++balls } if (curPos == null) { balls++ curPos = source field[source] = Entity.BALL } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd6f9b46d109a34978e92ab56287e94cc3e1c945
3,160
aoc2022
Apache License 2.0
src/Day03.kt
rod41732
728,131,475
false
{"Kotlin": 26028}
fun main() { fun part1(input: List<String>): Int { val r = input.size val c = input[0].length val isSymbols = input.map { it.map { char -> !char.isDigit() && char != '.' }.toMutableList() } val isAdjSymbols = isSymbols.mapIndexed { i, row -> row.mapIndexed groupSym@{ j, isSym -> listOf(-1, 0, 1).forEach { dx -> listOf(-1, 0, 1).forEach check@{ dy -> val ni = i + dx val nj = j + dy if (ni < 0 || ni >= r || nj < 0 || nj >= c) { return@check } if (isSymbols[ni][nj]) { return@groupSym true } } } return@groupSym false } } var total = 0 var acc = 0 var accIsTouch = false input.forEachIndexed { i, row -> row.forEachIndexed { j, char -> if (char.isDigit()) { acc = 10 * acc + (char - '0') // print("c $i $j ${isAdjSymbols[i][j]}") accIsTouch = accIsTouch || isAdjSymbols[i][j] } else { // if (acc > 0) { // println("non: $acc $accIsTouch") // } if (accIsTouch) total += acc acc = 0 accIsTouch = false } } // flush // if (acc > 0) { // println("EOL: $acc $accIsTouch") // } if (accIsTouch) total += acc acc = 0 accIsTouch = false } return total } fun part2(input: List<String>): Int { val r = input.size val c = input[0].length var total = 0 fun findAdjNumbers(x: Int, y: Int): List<Int> { var chars = "" listOf(-1, 0, 1).forEach { dx -> val px = x + dx if (px < 0 || px >= r) { return@forEach } var lb = 0 var rb = 0 var lbp = -1 while (true) { val py = y + lbp if (py < 0 || py >= c) break lb = lbp if (input[px][py] == '.') break lbp-- } var rbp = 1 while (true) { val py = y + rbp if (py < 0 || py >= c) break rb = rbp if (input[px][py] == '.') break rbp++ } chars += ".${input[px].substring((y + lb)..(y + rb))}" } return Regex("\\d+").findAll(chars).map { it.value.toInt() }.toList() } input.forEachIndexed { i, row -> row.forEachIndexed { j, char -> if (char == '*') { val numbers = findAdjNumbers(i, j) if (numbers.size == 2) { total += numbers[0] * numbers[1] } } } } return total } val testInput = readInput("Day03_test") assertEqual(part1(testInput), 4361) assertEqual(part2(testInput), 467835) val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
05a308a539c8a3f2683b11a3a0d97a7a78c4ffac
3,601
aoc-23
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2021/calendar/day17/Day17.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2021.calendar.day17 import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import javax.inject.Inject import kotlin.math.abs import kotlin.math.max class Day17 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun maxHeight(fileName: String) = generatorFactory.forFile(fileName).readOne { input -> val yMin = input // full string .split("target area: ").last() // x and y data .split(", ").map { it.split("=").last() }.last() // just the y data range .split("..").first().toLong() // the min Y value triangleNumber(yMin) } fun totalNumberOfLaunchVelocities(fileName: String) = generatorFactory.forFile(fileName).readOne { input -> val area = fetchArea(input) val lowestMultiJumpX = (0..area.xMin).first { triangleNumber(it) in area.xRange } val highestMultiJumpX = (area.xMax / 2) + 1 val singleJumpValues = area.xRange val multiJumpValues = (lowestMultiJumpX..highestMultiJumpX) val validXValues = mutableListOf<Long>().apply { addAll(singleJumpValues) addAll(multiJumpValues) } val minYValue = area.yMin val maxYValue = abs(area.yMin) - 1 val validTrajectories = validXValues.sumOf { x -> findValidTrajectories(x, minYValue..maxYValue, area) } validTrajectories } private fun fetchArea(input: String): Area { val area = input.split("target area: ").last() val (xData, yData) = area.split(", ").map { it.split("=").last() } val (xMin, xMax) = xData.split("..").map { it.toLong() } val (yMin, yMax) = yData.split("..").map { it.toLong() } return Area(xMin, xMax, yMin, yMax) } private fun findValidTrajectories(xVelocity: Long, validYRange: LongRange, area: Area): Long { return validYRange.sumOf { y -> var xSpeed = xVelocity var ySpeed = y var posX = xSpeed var posY = ySpeed while (posX <= area.xMax && posY >= area.yMin) { if (posX in area.xRange && posY in area.yRange) return@sumOf 1L xSpeed = max(0, xSpeed - 1) ySpeed -= 1 posX += xSpeed posY += ySpeed } return@sumOf 0L } } private fun triangleNumber(n: Long) = ((n + 1) * n) / 2 data class Area(val xMin: Long, val xMax: Long, val yMin: Long, val yMax: Long) { val xRange = (xMin..xMax) val yRange = (yMin..yMax) } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,388
advent-of-code
MIT License
src/main/kotlin/Day2.kt
Filipe3xF
433,908,642
false
{"Kotlin": 30093}
import utils.Day fun main() = Day(2, ::extractInstructions, { (0 to 0).followInstructions(it).multiply() }, { SubmarinePosition(0, 0, 0).followInstructions(it).multiply() } ).printResult() fun extractInstructions(inputList: List<String>) = inputList.map { it.split(" ") }.map { (command, delta) -> command to delta.toInt() } typealias SimpleSubmarinePosition = Pair<Int, Int> fun SimpleSubmarinePosition.followInstructions(instructions: List<Pair<String, Int>>): SimpleSubmarinePosition = instructions.fold(this) { submarinePosition, instruction -> submarinePosition.followInstruction(instruction) } fun SimpleSubmarinePosition.followInstruction(instruction: Pair<String, Int>): SimpleSubmarinePosition { val (command, delta) = instruction return when (command) { "up" -> subtractDepth(delta) "down" -> addDepth(delta) "forward" -> addHorizontal(delta) else -> this } } fun SimpleSubmarinePosition.multiply() = first * second fun SimpleSubmarinePosition.addDepth(toAdd: Int) = first to second.plus(toAdd) fun SimpleSubmarinePosition.subtractDepth(toSubtract: Int) = first to second.minus(toSubtract) fun SimpleSubmarinePosition.addHorizontal(toAdd: Int) = first.plus(toAdd) to second typealias SubmarinePosition = Triple<Int, Int, Int> fun SubmarinePosition.followInstructions(instructions: List<Pair<String, Int>>): SubmarinePosition = instructions.fold(this) { submarinePosition, instruction -> submarinePosition.followInstruction(instruction) } fun SubmarinePosition.followInstruction(instruction: Pair<String, Int>): SubmarinePosition { val (command, delta) = instruction return when (command) { "up" -> subtractAim(delta) "down" -> addAim(delta) "forward" -> addHorizontal(delta).addDepth(delta) else -> this } } fun SubmarinePosition.multiply() = first * second fun SubmarinePosition.addAim(toAdd: Int) = SubmarinePosition(first, second, third.plus(toAdd)) fun SubmarinePosition.subtractAim(toSubtract: Int) = SubmarinePosition(first, second, third.minus(toSubtract)) fun SubmarinePosition.addHorizontal(toAdd: Int) = SubmarinePosition(first.plus(toAdd), second, third) fun SubmarinePosition.addDepth(toAdd: Int) = SubmarinePosition(first, second.plus(third * toAdd), third)
0
Kotlin
0
1
7df9d17f0ac2b1c103b5618ca676b5a20eb43408
2,302
advent-of-code-2021
MIT License
src/main/kotlin/adventofcode2017/potasz/P14DiskDefrag.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz import java.util.stream.Collectors import java.util.stream.IntStream object P14DiskDefrag { fun String.toBinary(): BooleanArray = this .map { it.toString().toInt(16) } .flatMap { num -> listOf(8, 4, 2, 1).map { num and it == it } } .toBooleanArray() fun bitMatrix(input: String): Array<BooleanArray> = IntStream.range(0, 128) .parallel() .mapToObj { "$input-$it" } .map { P10KnotHash.knotHash(it).toBinary() } .collect(Collectors.toList()) .toTypedArray() fun solve1(input: String): Int = bitMatrix(input).sumBy { it.count { it } } fun solve2(input: String): Int { val bitMatrix = bitMatrix(input) return findGroups(bitMatrix) } fun findGroups(bitMatrix: Array<BooleanArray>): Int { var nextGroup = 1 val groups = Array(bitMatrix.size, { IntArray(bitMatrix.size) }) for (i in 0 until bitMatrix.size) { for (j in 0 until bitMatrix[i].size) { if (bitMatrix[i][j] && groups[i][j] == 0) { groups[i][j] = nextGroup findAdjacent(i,j, bitMatrix, groups, nextGroup++) } } } return nextGroup - 1 } private fun findAdjacent(i: Int, j: Int, bitMatrix: Array<BooleanArray>, groups: Array<IntArray>, groupLabel: Int) { withNeighboursOf(i, j, bitMatrix.size) { k, l -> if (groups[k][l] != groupLabel && bitMatrix[k][l]) { groups[k][l] = groupLabel findAdjacent(k,l, bitMatrix, groups, groupLabel) } } } private fun withNeighboursOf(i: Int, j: Int, size: Int, block: (Int, Int) -> Unit) { listOf(Pair(i - 1,j), Pair(i, j - 1), Pair(i + 1, j), Pair(i, j + 1)) .filter { it.first in 0..(size - 1) && it.second in 0..(size - 1) } .forEach { block(it.first, it.second) } } @JvmStatic fun main(args: Array<String>) { val sample = "flqrgnkx" println(solve1(sample)) println(solve2(sample)) val input = "ffayrhll" println(solve1(input)) println(solve2(input)) } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
2,251
adventofcode2017
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/AvoidFloodInTheCity.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.TreeSet fun interface AvoidFloodStrategy { operator fun invoke(rains: IntArray): IntArray } class AvoidFloodTree : AvoidFloodStrategy { override operator fun invoke(rains: IntArray): IntArray { val full: MutableMap<Int, Int> = HashMap() // last days that is full val drain: TreeSet<Int> = TreeSet() // storage days to be used for drain val n: Int = rains.size val res = IntArray(n) { 1 } for (i in rains.indices) { val lake = rains[i] if (full.containsKey(lake)) { val key: Int = drain.ceiling(full[lake]) ?: return intArrayOf() // find if there is a day could be drain after last full // did not find, flooded res[key] = lake // set the day to be drained with lake drain.remove(key) } if (lake == 0) { drain.add(i) // we got new days } else { full[lake] = i res[i] = -1 // lake is 0, or could be dry } } return res } } class AvoidFloodSimple : AvoidFloodStrategy { private val empty = IntArray(0) override operator fun invoke(rains: IntArray): IntArray { val ans = IntArray(rains.size) val n: Int = rains.size val fullLakes: MutableMap<Int, Int> = HashMap() val noRains = TreeSet<Int?>() for (i in 0 until n) { if (rains[i] == 0) { noRains.add(i) ans[i] = 1 } else if (rains[i] > 0) { if (fullLakes.containsKey(rains[i])) { val canDry = noRains.ceiling(fullLakes[rains[i]]) ?: return empty ans[canDry] = rains[i] noRains.remove(canDry) } fullLakes[rains[i]] = i ans[i] = -1 } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,594
kotlab
Apache License 2.0
src/aoc2022/Day04.kt
Playacem
573,606,418
false
{"Kotlin": 44779}
package aoc2022 import utils.readInput object Day04 { override fun toString(): String { return this.javaClass.simpleName } } fun main() { fun rangeStringAsIntRange(rangeString: String): IntRange { val (left, right) = rangeString.split('-') return IntRange(left.toInt(10), right.toInt(10)) } fun inputAsRanges(input: String): List<IntRange> { return input.split(',').map { rangeStringAsIntRange(it) } } fun totalOverlap(list: List<IntRange>): Boolean { val (a, b) = list return (b.first in a && b.last in a) || (a.first in b && a.last in b) } fun partialOverlap(list: List<IntRange>): Boolean { val (a, b) = list for (x in a) { if (x in b) { return true } } for (x in b) { if (x in a) { return true } } return false } fun part1(input: List<String>): Int { return input.map { inputAsRanges(it) }.count { totalOverlap(it) } } fun part2(input: List<String>): Int { return input.map { inputAsRanges(it) }.count { partialOverlap(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput(2022, "${Day04}_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput(2022, Day04.toString()) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4ec3831b3d4f576e905076ff80aca035307ed522
1,486
advent-of-code-2022
Apache License 2.0
src/main/aoc2018/Day4.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 class Day4(input: List<String>) { private val guards = parseInput(input) private fun parseInput(input: List<String>): MutableMap<Int, IntArray> { val sorted = input.sorted() var currentGuard = -1 var i = 0 // Map of all guards, value is an array where each entry specifies how many days the guard was // sleeping during that minute val guards = mutableMapOf<Int, IntArray>() while (i < sorted.size) { val line = sorted[i++] // Example lines to parse (falls asleep is always followed by wakes up): // [1518-11-01 00:00] Guard #10 begins shift // [1518-11-01 00:05] falls asleep // [1518-11-01 00:25] wakes up if (line.endsWith("begins shift")) { currentGuard = line.substringAfter("#").substringBefore(" ").toInt() guards.putIfAbsent(currentGuard, IntArray(60)) continue } val fallAsleep = line.substringAfter(":").take(2).toInt() val wakeup = sorted[i++].substringAfter(":").take(2).toInt() (fallAsleep until wakeup).forEach { guards.getValue(currentGuard)[it]++ } } return guards } private fun findGuardMinuteCombination(strategy: (Map.Entry<Int, IntArray>) -> Int): Int { val snooziestGuard = guards.maxByOrNull { strategy(it) }!! val snooziestMinute = snooziestGuard.value.withIndex().maxByOrNull { it.value }!!.index return snooziestGuard.key * snooziestMinute } fun solvePart1(): Int { // Find the guard with most total sleep time return findGuardMinuteCombination { guards -> guards.value.sum() } } fun solvePart2(): Int { // Find the guard with the maximum sleep time for a given minute return findGuardMinuteCombination { guards -> guards.value.maxOrNull()!! } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,927
aoc
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestGoodInteger.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 2264. Largest 3-Same-Digit Number in String * @see <a href="https://leetcode.com/problems/largest-3-same-digit-number-in-string">Source</a> */ fun interface LargestGoodInt { operator fun invoke(num: String): String } class LargestGoodIntSingleIteration : LargestGoodInt { companion object { private const val SMALLEST_ASCII = '\u0000' } override fun invoke(num: String): String { // Assign 'maxDigit' to the NUL character (smallest ASCII value character) var maxDigit = SMALLEST_ASCII // Iterate on characters of the num string. for (index in 0..num.length - 3) { // If 3 consecutive characters are the same, // store the character in 'maxDigit' if it's bigger than what it already stores. if (num[index] == num[index + 1] && num[index] == num[index + 2]) { maxDigit = maxOf(maxDigit, num[index]) } } // If 'maxDigit' is NUL, return an empty string; otherwise, return a string of size 3 with 'maxDigit' // characters. return if (maxDigit == SMALLEST_ASCII) "" else String(charArrayOf(maxDigit, maxDigit, maxDigit)) } } class LargestGoodIntCompare : LargestGoodInt { override fun invoke(num: String): String { return (2 until num.length).maxOfOrNull { i -> if (num[i] == num[i - 1] && num[i] == num[i - 2]) { num.substring(i - 2, i + 1) } else { "" } } ?: "" } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,167
kotlab
Apache License 2.0
src/main/kotlin/abc/218-e.kt
kirimin
197,707,422
false
null
package abc import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val m = sc.nextInt() val abc = (0 until m).map { Triple(sc.next().toInt(), sc.next().toInt(), sc.next().toLong()) } println(problem218e(n, m, abc)) } fun problem218e(n: Int, m: Int, abc: List<Triple<Int, Int, Long>>): Long { class UnionFind(n: Int) { private val parent = IntArray(n) { -1 } fun root(x: Int): Int { if (parent[x] < 0) return x parent[x] = root(parent[x]) return parent[x] } fun isSameRoot(x: Int, y: Int) = root(x) == root(y) fun merge(x: Int, y: Int) { var xRoot = root(x) var yRoot = root(y) if (xRoot == yRoot) return if (parent[xRoot] > parent[yRoot]){ val tmp = xRoot xRoot = yRoot yRoot = tmp } parent[xRoot] += parent[yRoot] parent[yRoot] = xRoot } fun groupSize(x: Int) = -parent[root(x)] override fun toString(): String { return parent.toString() } } var point = abc.map { it.third }.sum() val abc = abc.sortedBy { it.third } val uf = UnionFind(n) for (i in 0 until m) { val (a, b, c) = abc[i] if (c <= 0) { uf.merge(a - 1, b - 1) point -= c } else { if (!uf.isSameRoot(a - 1, b - 1)) { uf.merge(a - 1, b - 1) point -= c } } } return point }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
1,606
AtCoderLog
The Unlicense
src/cn/leetcode/codes/simple15/Simple15_2.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple15 import cn.leetcode.codes.out import java.util.* class Simple15_2 { /* 15. 三数之和 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例 1: 输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]] 示例 2: 输入:nums = [] 输出:[] 示例 3: 输入:nums = [0] 输出:[] 提示: 0 <= nums.length <= 3000 -105 <= nums[i] <= 105 */ fun threeSum(nums: IntArray): List<List<Int>> { val ans = mutableListOf<List<Int>>() //数组长度不足3条 不满足要求 if (nums.size < 3) { return ans } //排序 Arrays.sort(nums) out(nums) //遍历 for (i in nums.indices) { out("i = $i") //当前值大于 0 则三数之和一定大于 0 if (nums[i] > 0) { break } //去重 if (i > 0 && nums[i] == nums[i - 1]) { continue } //双指针区间 var l = i + 1 var r = nums.size - 1 while (l < r) { val sum = nums[i] + nums[l] + nums[r] when { sum == 0 -> { ans.add(listOf(nums[i], nums[l], nums[r])) while (l < r && nums[l] == nums[l + 1]) l++ while (l < r && nums[r] == nums[r - 1]) r-- l++ r-- } sum > 0 -> { r-- } sum < 0 -> { l++ } } } } return ans } }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,938
LeetCodeSimple
Apache License 2.0
kotlin/1553-minimum-number-of-days-to-eat-n-oranges.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}
// dfs class Solution { fun minDays(n: Int): Int { val dp = HashMap<Int, Int>().apply { this[0] = 0 this[1] = 1 } fun dfs(n: Int): Int { if (n in dp) return dp[n]!! val divByTwo = 1 + (n % 2) + dfs(n / 2) val divByThree = 1 + (n % 3) + dfs(n / 3) dp[n] = minOf( divByTwo, divByThree ) return dp[n]!! } return dfs(n) } } // Bonus: same as above but with more compact code class Solution { fun minDays(n: Int): Int { val dp = HashMap<Int, Int>() fun dfs(n: Int): Int { if (n <= 1) return n if (n !in dp) { dp[n] = minOf( 1 + (n % 2) + dfs(n / 2), 1 + (n % 3) + dfs(n / 3) ) } return dp[n]!! } return dfs(n) } } // bfs class Solution { fun minDays(n: Int): Int { val q = LinkedList<Int>().apply { add(n) } val visited = HashSet<Int>() var days = 1 while (q.isNotEmpty()) { repeat (q.size) { val n = q.removeFirst() if (n == 1 || n == 0) return days if (n !in visited) { visited.add(n) q.addLast(n - 1) if (n % 2 == 0) q.addLast(n / 2) if (n % 3 == 0) q.addLast(n / 3) } } days++ } return days } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,594
leetcode
MIT License
year2017/src/main/kotlin/net/olegg/aoc/year2017/day20/Day20.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2017.day20 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector3D import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2017.DayOf2017 /** * See [Year 2017, Day 20](https://adventofcode.com/2017/day/20) */ object Day20 : DayOf2017(20) { override fun first(): Any? { val points = lines .map { line -> line.replace("[pva=<> ]".toRegex(), "") } .map { it.parseInts(",") } .map { nums -> Triple( Vector3D(nums[0], nums[1], nums[2]), Vector3D(nums[3], nums[4], nums[5]), Vector3D(nums[6], nums[7], nums[8]), ) } return (0..1_000) .fold(points) { acc, _ -> acc.map { (position, speed, acceleration) -> val newSpeed = speed + acceleration val newPosition = position + newSpeed return@map Triple(newPosition, newSpeed, acceleration) } } .withIndex() .minBy { it.value.first.manhattan() } .index } override fun second(): Any? { val points = lines .map { line -> line.replace("[pva=<> ]".toRegex(), "") } .map { it.parseInts(",") } .mapIndexed { index, nums -> index to Triple( Vector3D(nums[0], nums[1], nums[2]), Vector3D(nums[3], nums[4], nums[5]), Vector3D(nums[6], nums[7], nums[8]), ) } return (0..1_000) .fold(points) { acc, _ -> acc.map { (index, values) -> val (position, speed, acceleration) = values val newSpeed = speed + acceleration val newPosition = position + newSpeed return@map index to Triple(newPosition, newSpeed, acceleration) } .groupBy { it.second.first } .filterValues { it.size == 1 } .values .flatten() } .count() } } fun main() = SomeDay.mainify(Day20)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,885
adventofcode
MIT License
src/main/kotlin/com/github/brpeterman/advent2022/RopeSnake.kt
brpeterman
573,059,778
false
{"Kotlin": 53108}
package com.github.brpeterman.advent2022 class RopeSnake { data class Coords(val row: Int, val column: Int) { operator fun plus(other: Coords): Coords { return Coords(row + other.row, column + other.column) } } enum class Direction(val offset: Coords) { UP(Coords(-1, 0)), DOWN(Coords(1, 0)), LEFT(Coords(0, -1)), RIGHT(Coords(0, 1)) } fun simulateAndCount(steps: List<Pair<Direction, Int>>, tailCount: Int = 1): Int { val visited = mutableSetOf(Coords(0, 0)) var head = Coords(0, 0) val tails = (1..tailCount).fold(ArrayList<Coords>()) { list, _ -> list.add(Coords(0, 0)) list } steps.forEach { (direction, count) -> (1..count).forEach { head = head + direction.offset tails.withIndex().forEach { (index, tail) -> val leader = if (index == 0) { head } else { tails[index - 1] } if (!isAdjacent(tail, leader)) { val newTail = moveTo(tail, leader) tails[index] = newTail if (index == tailCount - 1) { visited.add(newTail) } } } } } return visited.size } fun isAdjacent(tail: Coords, head: Coords): Boolean { return listOf(Coords(0, 0), Direction.UP.offset, Direction.DOWN.offset, Direction.LEFT.offset, Direction.RIGHT.offset, Direction.UP.offset + Direction.LEFT.offset, Direction.UP.offset + Direction.RIGHT.offset, Direction.DOWN.offset + Direction.LEFT.offset, Direction.DOWN.offset + Direction.RIGHT.offset) .any { head + it == tail } } fun moveTo(tail: Coords, head: Coords): Coords { val rowOffset = if (tail.row == head.row) { 0 } else { (head.row - tail.row) / Math.abs(head.row - tail.row) } val colOffset = if (tail.column == head.column) { 0 } else { (head.column - tail.column) / Math.abs(head.column - tail.column) } return Coords(tail.row + rowOffset, tail.column + colOffset) } companion object { fun parseInput(input: String): List<Pair<Direction, Int>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val (dir, count) = line.split(" ") val direction = when (dir) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> throw IllegalStateException("Unexpected direction: ${dir}") } Pair(direction, count.toInt()) } } } }
0
Kotlin
0
0
1407ca85490366645ae3ec86cfeeab25cbb4c585
3,109
advent2022
MIT License
src/adventofcode/blueschu/y2017/day02/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day02 import java.io.File import kotlin.test.assertEquals fun input(): List<List<Int>> = File("resources/y2017/day02.txt") .readLines() .map { it.split('\t').map(String::toInt) } fun main(args: Array<String>) { assertEquals(18, part1(listOf( listOf(5, 1, 9, 5), listOf(7, 5, 3), listOf(2, 4, 5, 8)))) println("Part 1: ${part1(input())}") assertEquals(9, part2(listOf( listOf(5, 9, 2, 8), listOf(9, 4, 7, 3), listOf(3, 8, 6, 5)))) println("Part 2: ${part2(input())}") } fun part1(table: List<List<Int>>): Int { return table.map { (it.max()!! - it.min()!!) }.sum() } fun part2(table: List<List<Int>>): Int { return table.map { row -> var result = 0 loop@ for (i in 0 until row.count() - 1) { for (j in i + 1 until row.count()) { val num = row[j] val dem = row[i] result = when { num % dem == 0 -> num / dem dem % num == 0 -> dem / num else -> result } if (result != 0) { break@loop } } } result }.sum() }
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
1,260
Advent-Of-Code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/IsSubsequence.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 392. Is Subsequence * @see <a href="https://leetcode.com/problems/unique-paths-ii/">Source</a> */ fun interface IsSubsequence { operator fun invoke(source: String, target: String): Boolean } class IsSubsequenceDP : IsSubsequence { override operator fun invoke(source: String, target: String): Boolean { val rows: Int = source.length val cols: Int = target.length // the source string is empty if (rows == 0) return true val matrix = Array(rows + 1) { IntArray(cols + 1) } // DP calculation, we fill the matrix column by column, bottom up for (col in 1..cols) { for (row in 1..rows) { // find another match if (source[row - 1] == target[col - 1]) { matrix[row][col] = matrix[row - 1][col - 1] + 1 } else { // retrieve the maximal result from previous prefixes matrix[row][col] = max(matrix[row][col - 1], matrix[row - 1][col]) } } // check if we can consume the entire source string, // with the current prefix of the target string. if (matrix[rows][col] == rows) return true } // matching failure return false } } class IsSubsequenceTwoPointers : IsSubsequence { override fun invoke(source: String, target: String): Boolean { var j = 0 val n = source.length val m = target.length for (i in 0 until m) { if (j < n && source[j] == target[i]) { j++ } } return j == n } } class IsSubsequenceRecursion : IsSubsequence { override fun invoke(source: String, target: String): Boolean { val m = source.length val n = target.length if (m > n) { return false } return isSubSequence(source, target, m, n) == m } private fun isSubSequence(s1: String, s2: String, i: Int, j: Int): Int { if (i == 0 || j == 0) { return 0 } return if (s1[i - 1] == s2[j - 1]) { 1 + isSubSequence(s1, s2, i - 1, j - 1) } else { isSubSequence(s1, s2, i, j - 1) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,954
kotlab
Apache License 2.0
src/main/kotlin/days/Day10.kt
hughjdavey
317,575,435
false
null
package days class Day10 : Day(10) { private val ratings = inputList.map { it.toInt() }.let { val outletJoltage = 0 val deviceJoltage = (it.maxOrNull() ?: 0) + 3 it.plus(outletJoltage).plus(deviceJoltage) }.sorted() // 2450 override fun partOne(): Any { return countJoltDifferences(1) * countJoltDifferences(3) } // 32396521357312 override fun partTwo(): Any { return countAdapterArrangementsFast() } fun countJoltDifferences(diff: Int): Int { return ratings.windowed(2).count { it.last() - it.first() == diff } } // works on test inputs but too slow for real input fun countAdapterArrangements(next: Int = 0, count: Int = 0): Int { if (next >= ratings.maxOrNull()!!) { return count + 1 } val nexts = listOf(next + 1, next + 2, next + 3).filter { ratings.contains(it) } return count + nexts.map { countAdapterArrangements(it, count) }.sum() } // inspired by https://www.reddit.com/r/adventofcode/comments/kacdbl/2020_day_10c_part_2_no_clue_how_to_begin/gf9lzhd/ fun countAdapterArrangementsFast(): Long { val ratingsToPaths = ratings.mapIndexed { i, n -> if (i == 0) RatingToPath(n, 1L) else RatingToPath(n) }.toList() ratingsToPaths.forEach { r2p -> r2p.reachableRatings().forEach { rating -> ratingsToPaths.ifExistsWithRating(rating) { it.paths += r2p.paths } } } return ratingsToPaths.last().paths } private data class RatingToPath(val rating: Int, var paths: Long = 0L) { fun reachableRatings() = (1..3).map { rating + it } } private fun List<RatingToPath>.ifExistsWithRating(rating: Int, f: (RatingToPath) -> Unit) { val maybe = this.find { it.rating == rating } if (maybe != null) { f(maybe) } } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
1,874
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day04.kt
vlsolodilov
573,277,339
false
{"Kotlin": 19518}
fun main() { fun getSectionPairOfElves(pair: String): Pair<IntRange,IntRange> = pair.split('-',',') .map { it.toInt() } .chunked(2) .map { IntRange(it[0], it[1]) } .let { it[0] to it[1] } fun part1(input: List<String>): Int = input.map(::getSectionPairOfElves).filter { with(it) { first.all(second::contains) || second.all(first::contains) } }.size fun part2(input: List<String>): Int = input.map(::getSectionPairOfElves).filter { (it.first.any(it.second::contains)) }.size // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b75427b90b64b21fcb72c16452c3683486b48d76
856
aoc22
Apache License 2.0
src/Day09.kt
DiamondMiner88
573,073,199
false
{"Kotlin": 26457, "Rust": 4093, "Shell": 188}
import kotlin.math.abs fun main() { d9part1() d9part2() } fun move(target: Pair<Int, Int>, src: Pair<Int, Int>, exact: Boolean): Pair<Int, Int> { val (hX, hY) = target val (tX, tY) = src if (!exact) { if ( abs(hX - tX) <= 1 && abs(hY - tY) <= 1 ) { return src } } return if (hX != tX && hY != tY) { var y = hY - tY if (y > 1) y = 1 else if (y < 1) y = -1 var x = hX - tX if (x > 1) x = 1 else if (x < 1) x = -1 tX + x to tY + y } else { if (hX == tX) { var y = hY - tY if (y > 1) y = 1 else if (y < 1) y = -1 tX to tY + y } else { var x = hX - tX if (x > 1) x = 1 else if (x < 1) x = -1 tX + x to tY } } } fun d9part1() { val input = readInput("input/day09.txt") .split("\n") .filter { it.isNotBlank() } var hPos = 0 to 0 var tPos = 0 to 0 val allTPos = mutableListOf(0 to 0) for (inst in input) { val dir = inst[0] val count = inst.slice((2 until inst.length)).toInt() val targetPos = when (dir) { 'L' -> { hPos.copy(first = hPos.first - count) } 'R' -> { hPos.copy(first = hPos.first + count) } 'D' -> { hPos.copy(second = hPos.second - count) } 'U' -> { hPos.copy(second = hPos.second + count) } else -> error("guh") } while ( abs(targetPos.first - hPos.first) >= 1 || abs(targetPos.second - hPos.second) >= 1 ) { hPos = move(targetPos, hPos, true) tPos = move(hPos, tPos, false) allTPos += tPos } } println(allTPos.distinct().size) } fun d9part2() { val input = readInput("input/day09.txt") .split("\n") .filter { it.isNotBlank() } var hPos = 0 to 0 var tPos1 = 0 to 0 var tPos2 = 0 to 0 var tPos3 = 0 to 0 var tPos4 = 0 to 0 var tPos5 = 0 to 0 var tPos6 = 0 to 0 var tPos7 = 0 to 0 var tPos8 = 0 to 0 var tPos9 = 0 to 0 val allTPos9 = mutableListOf(0 to 0) for (inst in input) { val dir = inst[0] val count = inst.slice((2 until inst.length)).toInt() val targetPos = when (dir) { 'L' -> { hPos.copy(first = hPos.first - count) } 'R' -> { hPos.copy(first = hPos.first + count) } 'D' -> { hPos.copy(second = hPos.second - count) } 'U' -> { hPos.copy(second = hPos.second + count) } else -> error("guh") } while ( abs(targetPos.first - hPos.first) >= 1 || abs(targetPos.second - hPos.second) >= 1 ) { hPos = move(targetPos, hPos, true) tPos1 = move(hPos, tPos1, false) tPos2 = move(tPos1, tPos2, false) tPos3 = move(tPos2, tPos3, false) tPos4 = move(tPos3, tPos4, false) tPos5 = move(tPos4, tPos5, false) tPos6 = move(tPos5, tPos6, false) tPos7 = move(tPos6, tPos7, false) tPos8 = move(tPos7, tPos8, false) tPos9 = move(tPos8, tPos9, false) allTPos9 += tPos9 } } println(allTPos9.distinct().size) }
0
Kotlin
0
0
55bb96af323cab3860ab6988f7d57d04f034c12c
3,595
advent-of-code-2022
Apache License 2.0
hackerrank/algorithms/frequency_queries.kts
SVMarshall
46,183,306
false
{"Python": 47229, "Erlang": 4918, "Kotlin": 3374, "C": 2915, "JavaScript": 1756}
import kotlin.collections.* class FrequenciesMap { private val numberFrequencies = mutableMapOf<Int, Int>() private val frequenciesCounts = mutableMapOf<Int, Int>() fun insert(value: Int) { val newValueFrequency = insertOnNumberFrequencies(value) insertOnFrequenciesLists(newValueFrequency) } fun delete(value: Int) { val newValueFrequency = deleteOnNumberFrequencies(value) newValueFrequency?.let { deleteOnFrequenciesLists(it) } } fun check(freq: Int): Boolean { return frequenciesCounts.any { it.key == freq && it.value > 0} } private fun insertOnNumberFrequencies(value: Int): Int { val newValueFrequency = numberFrequencies[value]?.inc() ?: 1 numberFrequencies[value] = newValueFrequency return newValueFrequency } private fun insertOnFrequenciesLists(newValueFrequency: Int) { frequenciesCounts[newValueFrequency - 1]?.let { frequenciesCounts[newValueFrequency - 1] = it - 1 } frequenciesCounts[newValueFrequency] ?.let { frequenciesCounts[newValueFrequency] = it + 1 } ?: run { frequenciesCounts[newValueFrequency] = 1 } } private fun deleteOnNumberFrequencies(value: Int): Int? { val newValueFrequency = numberFrequencies[value]?.dec() newValueFrequency?.let { numberFrequencies[value] = it } return newValueFrequency } private fun deleteOnFrequenciesLists(newValueFrequency: Int) { frequenciesCounts[newValueFrequency + 1] = frequenciesCounts[newValueFrequency + 1]!!.minus(1) frequenciesCounts[newValueFrequency] = frequenciesCounts[newValueFrequency]?.plus(1) ?: 1 } } fun freqQuery(queries: Array<Array<Int>>): Array<Int> { val res = mutableListOf<Int>() val freqMap = FrequenciesMap() for (query in queries) { when (query[0]) { 1 -> freqMap.insert(query[1]) 2 -> freqMap.delete(query[1]) 3 -> res += when(freqMap.check(query[1])) {true -> 1; false -> 0} } } return res.toTypedArray() } fun main(args: Array<String>) { val q = readLine()!!.trim().toInt() val queries = Array(q) { Array(2, { 0 }) } for (i in 0 until q) { queries[i] = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray() } val ans = freqQuery(queries) println(ans.joinToString("\n")) }
0
Python
0
1
275e3258c96365a1c886c3529261906deadf90ed
2,260
programming-challanges
Do What The F*ck You Want To Public License
src/main/kotlin/aoc2015/day02_wrap_presents/wrap_presents.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2015.day02_wrap_presents import kotlin.math.min fun main() { util.solve(1598415, ::partOne) util.solve(3812909, ::partTwo) } data class Box(val length: Int, val width: Int, val height: Int) { companion object { fun parse(s: String): Box { val dims = s.split("x") .map(String::toInt) assert(dims.size == 3) return Box(dims[0], dims[1], dims[2]) } } val frontArea: Int get() = width * height val topArea: Int get() = width * length val sideArea: Int get() = length * height val totalArea: Int get() = frontArea * 2 + topArea * 2 + sideArea * 2 val neededWrappingPaperArea: Int get() = totalArea + min(min(frontArea, topArea), sideArea) val frontPerim: Int get() = 2 * (width + height) val topPerim: Int get() = 2 * (width + length) val sidePerim: Int get() = 2 * (length + height) val volume: Int get() = length * width * height val neededRibbonLength: Int get() = volume + min(min(frontPerim, topPerim), sidePerim) } fun partOne(input: String) = input .lines() .map(Box::parse) .sumOf(Box::neededWrappingPaperArea) fun partTwo(input: String) = input .lines() .map(Box::parse) .sumOf(Box::neededRibbonLength)
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
1,363
aoc-2021
MIT License
src/aoc2022/Day20.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.checkEquals import utils.sendAnswer private typealias Num = Pair<Int, Long> private val Num.value get() = second fun main() { fun part1(input: List<String>): Long { val original: List<Num> = input.mapIndexed { i, num -> i to num.toLong() } val mixingList = original.toMutableList() for (num in original) { val oldIndex = mixingList.indexOf(num) val newIndex = (oldIndex + num.value).mod(mixingList.lastIndex) mixingList.removeAt(oldIndex) mixingList.add(newIndex, num) } val zeroIndex = mixingList.indexOfFirst { it.value == 0L } return listOf(1000,2000,3000).sumOf { mixingList[((zeroIndex + it) % mixingList.size)].value } } fun part2(input: List<String>): Long { val original : List<Num> = input.mapIndexed { i, num -> i to num.toLong() * 811589153L } val mixingList = original.toMutableList() repeat(10) { for (num in original) { val index = mixingList.indexOf(num) mixingList.removeAt(index) val newIndex = (index + num.value).mod(mixingList.size) mixingList.add(newIndex, num) } } val zeroIndex = mixingList.indexOfFirst { it.value == 0L } return listOf(1000,2000,3000).sumOf { mixingList[((zeroIndex + it) % mixingList.size)].value } } // parts execution val testInput = readInput("Day20_test") val input = readInput("Day20") part1(testInput).checkEquals(3) part1(input) // .sendAnswer(part = 1, day = "20", year = 2022) part2(testInput).checkEquals(1623178306) part2(input) .sendAnswer(part = 2, day = "20", year = 2022) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,767
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day13.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2021 class Day13(private val input: List<String>) { private val initialPaper: List<List<Boolean>> private val foldInstructions: List<Pair<Char, Int>> init { val index = input.indexOf("") initialPaper = constructPaper(input.subList(0, index)) foldInstructions = input.subList(index + 1, input.size).map { line -> val axisIndex = "fold along ".length line[axisIndex] to line.substring(axisIndex + 2).toInt() } } fun solvePart1(): Int { val (axis, i) = foldInstructions.first() val folded = fold(initialPaper, axis, i) return folded.sumOf { row -> row.count { it } } } fun solvePart2(): String { val folded = foldInstructions.fold(initialPaper) { paper, instruction -> val (axis, i) = instruction fold(paper, axis, i) } return format(folded) } private fun constructPaper(coordinates: List<String>): List<List<Boolean>> { val paper = mutableListOf<MutableList<Boolean>>() for (coordinate in coordinates) { val (x, y) = parseCoordinate(coordinate) paper.extend(y + 1) { mutableListOf() } val row = paper[y] row.extend(x + 1) { false } row[x] = true } val width = paper.maxOf { it.size } paper.forEach { row -> row.extend(width) { false } } return paper } private fun fold(paper: List<List<Boolean>>, axis: Char, i: Int): List<List<Boolean>> { return if (axis == 'x') { foldVertically(paper, i) } else { foldHorizontally(paper, i) } } private fun foldHorizontally(paper: List<List<Boolean>>, i: Int): List<List<Boolean>> { return fold(paper, i) { rowA, rowB -> rowA.zip(rowB) { a, b -> a || b } } } private fun foldVertically(paper: List<List<Boolean>>, i: Int): List<List<Boolean>> { return paper.map { row -> fold(row, i) { a, b -> a || b } } } private fun <T> fold(paper: List<T>, i: Int, zip: (T, T) -> T): List<T> { val partA = paper.subList(0, i) val partB = paper.subList(i + 1, paper.size).asReversed() if (partA.size > partB.size) { val base = partA.subList(0, partA.size - partB.size) val folded = partA.subList(base.size, partA.size).zip(partB, zip) return base + folded } if (partA.size < partB.size) { val base = partB.subList(partA.size, partB.size) val folded = partB.subList(0, partA.size).zip(partA, zip) return base + folded } return partA.zip(partB, zip) } private fun parseCoordinate(instruction: String): Pair<Int, Int> { val index = instruction.indexOf(",") val x = instruction.substring(0, index).toInt() val y = instruction.substring(index + 1).toInt() return x to y } private fun format(paper: List<List<Boolean>>): String { return paper.joinToString("\n") { row -> row.joinToString("") { if (it) "#" else "." } } } private fun <T> MutableList<T>.extend(size: Int, init: (index: Int) -> T) { if (this.size < size) { this += List(size - this.size, init) } } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
3,427
advent-of-code
Apache License 2.0
solutions/src/DungeonGame.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
import kotlin.math.max import kotlin.math.min data class Room(val currentVal: Int, val lowestVal: Int) { } class DungeonGame { //https://leetcode.com/problems/dungeon-game/submissions/1 fun calculateMinimumHP(dungeon : Array<IntArray>) : Int { val rows = dungeon.size val cols = dungeon.first().size val dynamicValues: Array<Array<Room?>> = Array(rows) { arrayOfNulls<Room>(cols) } var i =rows -1 var j = cols -1 while (i >= 0) { while (j >= 0) { if (i+1 == rows && j+1 == cols) { if (dungeon[i][j] > 0) { dynamicValues[i][j]=Room(dungeon[i][j],0) } else { dynamicValues[i][j]=Room(dungeon[i][j],dungeon[i][j]) } } else if (i+1 == rows) { val prevRoom = dynamicValues[i][j+1]!! dynamicValues[i][j]=createRoom(prevRoom,dungeon[i][j]) } else if (j+1 == cols) { val prevRoom = dynamicValues[i+1][j]!! dynamicValues[i][j]=createRoom(prevRoom,dungeon[i][j]) } else { val oneRight = dynamicValues[i+1][j]!! val newLowRight = calcNewLow(oneRight,dungeon[i][j]) val oneDown = dynamicValues[i][j+1]!! val newDownLow = calcNewLow(oneDown,dungeon[i][j]) if (newLowRight > newDownLow) { dynamicValues[i][j]=createRoom(oneRight,dungeon[i][j]) } else if (newDownLow > newLowRight) { dynamicValues[i][j]=createRoom(oneDown,dungeon[i][j]) } else { if (oneRight.currentVal > oneDown.currentVal) { dynamicValues[i][j]=createRoom(oneRight,dungeon[i][j]) } else { dynamicValues[i][j]=createRoom(oneDown,dungeon[i][j]) } } } j-- } j = cols -1 i-- } val lowestVal = dynamicValues[0][0]!!.lowestVal println(dynamicValues[0][0]) if (lowestVal > 0) { return 1 } return 1-lowestVal } fun calcNewLow(r: Room, value: Int) : Int{ return min(r.lowestVal,(r.currentVal+value)) } fun createRoom(old: Room, value: Int) : Room { val currentVal = value+old.currentVal println(value) println(old) if (value >= 0) { if (currentVal >=0) { println("Case 1") return Room(currentVal, 0) } else { println("Case 2") return Room(currentVal,currentVal) } } else { if (old.currentVal < 0) { println("Case 3") return Room(currentVal,min(currentVal,old.lowestVal)) } else { println("Case 4") return Room(value,min(value,old.lowestVal)) } } } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
3,328
leetcode-solutions
MIT License