path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/com/jacobhyphenated/advent2022/day2/Day2.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day2 import com.jacobhyphenated.advent2022.Day /** * Day 2: Rock Paper Scissors * * To cheat at a tournament of paper, rock, scissors, you have a puzzle input of two columns. * The first column consists of "A" = Rock, "B" = Paper, and "C" = Scissors * * Each round is scored by adding up the result: loss = 0, draw = 3, win = 6 * and the Move you (the second column) take: Rock = 1, Paper = 2, Scissors = 3 */ class Day2: Day<List<String>> { override fun getInput(): List<String> { return readInputFile("day2").lines() } /** * Assume the second column is the move you are supposed to take where X = Rock, Y = Paper, Z = Scissors. * What is the final score after adding up the score for each round? */ override fun part1(input: List<String>): Number { return input.map { val (move1, move2) = it.split(" ") Pair(parseMove(move1), parseMove(move2)) }.sumOf { scoreRound(it) } } /** * It turns out the second column was the expected result of the round for you. * X = Loss, Y = Draw, Z = Win. * * What is the final score after adding up the score for each round? */ override fun part2(input: List<String>): Number { return input.map { val (move1, expectedResult) = it.split(" ") val firstMove = parseMove(move1) Pair(firstMove, determineSecondMove(expectedResult, firstMove)) }.sumOf { scoreRound(it) } } private fun scoreRound(round: Pair<Move,Move>): Int { val (opponentMove, yourMove) = round return roundResultScore(opponentMove, yourMove) + yourMove.points } private fun parseMove(move: String): Move { return when (move) { "A", "X" -> Move.ROCK "B", "Y" -> Move.PAPER "C", "Z" -> Move.SCISSORS else -> throw NotImplementedError("Invalid character $move") } } /** * Given the move your opponent will make (firstMove) and the expected result (Win, loss, draw), * determine what move you make this round. * @param expectedResult X = loss, Y = draw, Z = win * @param firstMove the move your opponent is making * @return the move you must make to get the expected result */ private fun determineSecondMove(expectedResult: String, firstMove: Move): Move { return when(expectedResult) { "X" -> when (firstMove) { Move.PAPER -> Move.ROCK Move.SCISSORS -> Move.PAPER Move.ROCK -> Move.SCISSORS } "Y" -> firstMove "Z" -> when (firstMove) { Move.PAPER -> Move.SCISSORS Move.SCISSORS -> Move.ROCK Move.ROCK -> Move.PAPER } else -> throw NotImplementedError("Invalid character $expectedResult") } } /** * Given your move and the opponents move, determine how many points you get. * loss = 0, draw = 3, win = 6 * * Uses the standard paper, rock, scissors rules */ private fun roundResultScore(opponent: Move, you: Move): Int { return when(opponent){ Move.SCISSORS -> when (you) { Move.SCISSORS -> 3 Move.ROCK -> 6 Move.PAPER -> 0 } Move.PAPER -> when (you) { Move.SCISSORS -> 6 Move.PAPER -> 3 Move.ROCK -> 0 } Move.ROCK -> when (you) { Move.SCISSORS -> 0 Move.ROCK -> 3 Move.PAPER -> 6 } } } } enum class Move(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3); }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
3,783
advent2022
The Unlicense
src/main/kotlin/dev/bogwalk/batch3/Problem33.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.combinatorics.combinations import dev.bogwalk.util.combinatorics.product import kotlin.math.pow import dev.bogwalk.util.maths.gcd /** * Problem 33: Digit Cancelling Fractions * * https://projecteuler.net/problem=33 * * Goal: Find every non-trivial fraction where the numerator is less than the denominator (both * have N-digits) and the value of the reduced fraction (by cancelling K digits from num. & * denom.) is equal to the original fraction. * * Constraints: 2 <= N <= 4 & 1 <= K <= N-1 * * Non-Trivial Fraction: Satisfies goal's conditions, e.g. 49/98 = 4/8. * * Trivial Fraction: Fractions with trailing zeroes in both numerator and denominator that allow * cancellation, e.g. 30/50 = 3/5. * * e.g.: N = 2, K = 1 * non-trivials = {16/64, 19/95, 26/65, 49/98} * reduced-equivalents = {1/4, 1/5, 2/5, 4/8} */ class DigitCancellingFractions { /** * Brute iteration through all numerators and denominators with the expected amount of * digits, & following constraints specified in problem above. * * SPEED (WORSE for PE problem) 2.67s for N = 4, K = 1 * * @return List of Pair(numerator, denominator) sorted by numerator. */ fun findNonTrivialsBrute(n: Int, k: Int = 1): List<Pair<Int, Int>> { val nonTrivials = mutableListOf<Pair<Int, Int>>() val minN = ((10.0).pow(n - 1) + 1).toInt() val maxD = (10.0).pow(n).toInt() for (num in minN until (maxD / 2)) { for (denom in (num + 1) until maxD) { if (denom % 10 == 0) continue if (isReducedEquivalent(n, num, denom, k)) { nonTrivials.add(num to denom) } } } return nonTrivials } /** * Naive method checks if a reduced fraction is equivalent to its original fraction. */ fun isReducedEquivalent( digits: Int, numerator: Int, denominator: Int, toCancel: Int ): Boolean { val nMod = (10.0).pow(toCancel).toInt() val dMod = (10.0).pow(digits - toCancel).toInt() if (numerator % nMod == denominator / dMod) { val ogFraction = 1.0 * numerator / denominator val reduced = 1.0 * (numerator / nMod) / (denominator % dMod) return ogFraction == reduced } return false } /** * Project Euler specific implementation that requires all non-trivial fractions that have 2 * digits (pre-cancellation of 1 digit) to be found. * * @return the denominator of the product of the fractions given in their lowest common terms. */ fun productOfNonTrivials(): Int { val (numerators, denominators) = findNonTrivials(2, k=1).unzip() val nProd = numerators.fold(1) { acc, n -> acc * n } val dProd= denominators.fold(1) { acc, n -> acc * n } return dProd / gcd(nProd.toLong(), dProd.toLong()).toInt() } /** * Solution limits loops by pre-cancelling possible digits, rather than checking each * iteration to see if cancelled digits match. This pre-reduces all numerators & * denominators, which reduces iteration by power of 10. * * Loop nesting is based on numerator < denominator & cancelled < cancelledMax. * * This order of solutions is based on the combination equation: * * (n10^k + c) / (c10^k + d) = n/d * * which reduces to: * * n(10^k -1)(c - d) = c(d - n) * * SPEED (BETTER for PE problem) 63.15ms for N = 4, K = 1 * * @return List of Pair(numerator, denominator) sorted by numerator. */ fun findNonTrivials(n: Int, k: Int = 1): List<Pair<Int, Int>> { val nonTrivials = mutableListOf<Pair<Int, Int>>() val cancelledMin = (10.0).pow(k - 1).toInt() val cancelledMax = (10.0).pow(k).toInt() val reducedMin = (10.0).pow(n - k - 1).toInt() val reducedMax = (10.0).pow(n - k).toInt() for (cancelled in cancelledMin until cancelledMax) { for (d2 in (reducedMin + 1) until reducedMax) { for (n2 in reducedMin until d2) { val numerator = n2 * cancelledMax + cancelled val denominator = cancelled * reducedMax + d2 if (n2 * denominator == numerator * d2) { nonTrivials.add(numerator to denominator) } } } } return nonTrivials.sortedBy { fraction -> fraction.first } } /** * HackerRank specific implementation that includes extra restrictions that are not clearly * specified on the problem page: * * - The digits cancelled from the numerator and denominator can be in any order. * e.g. 1306/6530 == 10/50 and 6483/8644 == 3/5. * * - Zeroes should not be cancelled, but leading zeroes are allowed as they will be read as * if removed. * e.g. 4808/8414 == 08/14 == 8/14 and 490/980 == 40/80. * * - Pre-cancelled fractions must only be counted once, even if the cancelled digits can be * removed in different ways with the same output. * e.g. 1616/6464 == 161/644 == 116/464. * * SPEED (WORSE for HR problem) 336.14s for N = 4, K = 1 * * @return Pair of (sum of numerators, sum of denominators). */ fun sumOfNonTrivialsBrute(n: Int, k: Int): Pair<Int, Int> { var nSum = 0 var dSum = 0 val minNumerator = ((10.0).pow(n - 1) + 2).toInt() val maxDenominator = (10.0).pow(n).toInt() for (numerator in minNumerator..(maxDenominator - 2)) { val nS = numerator.toString() val cancelCombos = combinations(nS.replace("0", "").toList(), k) outerDLoop@for (denominator in (numerator + 1) until maxDenominator) { val ogFraction = 1.0 * numerator / denominator for (combo in cancelCombos) { val nPost = getCancelledCombos(nS, combo) val dPost = getCancelledCombos(denominator.toString(), combo) // denominator did not contain all digits to cancel if (dPost.isEmpty()) continue innerNLoop@for (n2 in nPost) { if (n2 == 0) continue@innerNLoop innerDLoop@for (d2 in dPost) { // avoid division by zero error if (d2 == 0) continue@innerDLoop if (ogFraction == 1.0 * n2 / d2) { nSum += numerator dSum += denominator // avoid duplicating numerator with this denominator continue@outerDLoop } } } } } } return nSum to dSum } /** * Finds all combinations for digits cancelled from a number based on the indices of the * digits to be cancelled. Ensures no combinations have duplicate digits or duplicate integer * outputs. * * @return set of post-cancellation integers. */ fun getCancelledCombos(num: String, combo: List<Char>): Set<Int> { val k = combo.size val original = num.indices.toSet() // e.g. num = "9919" with cancelCombo = ('9','9') // indices = ((0,1,3), (0,1,3)) val indices: Array<List<Int>> = Array(combo.size) { ch -> num.indices.filter { i -> num[i] == combo[ch] } } // product().toSet() returns {0,1}, {0,3}, {1,0}, {1, 3}... with {0,0},etc reduced to {0} return product(*indices) .map { it.toSet() } .filter { it.size == k } // remove combos reduced due to duplicate indices .map { comboSet -> // e.g. {0,1,2,3} - {0,1} = {2,3} (original - comboSet) .joinToString("") { num.slice(it..it) } .toInt() // above identical to "9919" becoming 19 post-cancellation }.toSet() } /** * HackerRank specific implementation with extra restrictions, as detailed in the above brute * force solution. * * This solution has been optimised by only looping through possible numerators & the * cancellation combos they allow. Rather than loop through denominators, gcd() is used to * assess reductive equivalence based on the following: * * n_og / d_og = n_r / d_r, and * * n_r = n_og / gcd(n_og, d_og) * * d_r = d_og / gcd(n_og, d_og) * * SPEED (BETTER for HR problem) 507.98ms for N = 4, K = 1 * * @return Pair of (sum of numerators, sum of denominators). */ fun sumOfNonTrivialsGCD(n: Int, k: Int): Pair<Int, Int> { var nSum = 0 var dSum = 0 val minNumerator = (10.0).pow(n - 1).toInt() val maxDenominator = (10.0).pow(n).toInt() val maxReduced = (10.0).pow(n - k).toInt() for (numerator in minNumerator..(maxDenominator - 2)) { val nS = numerator.toString() val cancelCombos = combinations(nS.replace("0", "").toList(), k) // avoid denominator duplicates with same numerator val denominatorsUsed = mutableListOf<Int>() for (combo in cancelCombos) { // get all integers possible post-cancellation of k digits val nPost = getCancelledCombos(nS, combo) for (n2 in nPost) { if (n2 == 0) continue var d = numerator var nr = n2 var i = 1 while (true) { i++ val g = gcd(d.toLong(), nr.toLong()).toInt() d = d / g * i nr = nr / g * i if (d <= numerator) continue if (nr >= maxReduced || d >= maxDenominator) break val dPost = getCancelledCombos(d.toString(), combo) // denominator did not contain all digits to cancel if (dPost.isEmpty()) continue for (d2 in dPost) { if (nr == d2 && d !in denominatorsUsed) { nSum += numerator dSum += d denominatorsUsed.add(d) } } } } } } return nSum to dSum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
10,812
project-euler-kotlin
MIT License
aoc2023/day3.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day3.execute() } private object Day3 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { val numbers = mutableListOf<Int>() input.forEachIndexed { rowIndex, row -> var tmpNumber = "" var valid = false row.forEachIndexed { colIndex, c -> if (c.isDigit()) { tmpNumber += c valid = valid || input.getNeighbours(rowIndex, colIndex).any { !it.isDigit() && it != '.' } // If there is a neighbour with a symbol, it's a valid piece number } else { if (valid && tmpNumber.isNotEmpty()) { numbers.add(tmpNumber.toInt()) } // Reset flag and base value valid = false tmpNumber = "" } } if (valid && tmpNumber.isNotEmpty()) { numbers.add(tmpNumber.toInt()) } } return numbers.sum() } private fun part2(input: List<String>): Int { val numbers = mutableListOf<Int>() input.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, c -> if (c == '*') { // Check if it's a gear: val neighbours = input.getNeighbourNumbers(rowIndex, colIndex) if (neighbours.size == 2) { numbers.add(neighbours.first() * neighbours.last()) // Gear ratio } else if (neighbours.size > 2) { println("This should not happen!") } } } } return numbers.sum() } private fun readInput(): List<String> = InputRetrieval.getFile(2023, 3).readLines() private fun List<String>.getPos(x: Int, y: Int): Char = if (x in indices && y in this.first().indices) { this[x][y] } else { '.' } private fun List<String>.getNeighbours(x: Int, y: Int): List<Char> = listOf( getPos(x - 1, y - 1), // TOP LEFT getPos(x - 1, y), // TOP getPos(x - 1, y + 1), // TOP RIGHT getPos(x, y - 1), // LEFT getPos(x, y + 1), // RIGHT getPos(x + 1, y - 1), // BOTTOM LEFT getPos(x + 1, y), // BOTTOM getPos(x + 1, y + 1), // BOTTOM RIGHT ) private fun List<String>.getNeighbourNumbers(x: Int, y: Int): List<Int> { // LEFT val numbers = mutableListOf<Int>() if (getPos(x, y - 1).isDigit()) { numbers.add(this[x].getNumberToTheLeftOf(y)) } // RIGHT if (getPos(x, y + 1).isDigit()) { numbers.add(this[x].getNumberToTheRightOf(y + 1)) } // TOP val topPos = listOf(getPos(x - 1, y - 1), getPos(x - 1, y), getPos(x - 1, y + 1)) numbers.addAll(this[x - 1].getNumberFromTopBot(topPos, y)) // BOTTOM val botPos = listOf(getPos(x + 1, y - 1), getPos(x + 1, y), getPos(x + 1, y + 1)) numbers.addAll(this[x + 1].getNumberFromTopBot(botPos, y)) return numbers } private fun String.getNumberToTheLeftOf(y: Int): Int = this.substring(0, y).takeLastWhile { it.isDigit() }.toInt() private fun String.getNumberToTheRightOf(y: Int): Int = this.substring(y).takeWhile { it.isDigit() }.toInt() private fun String.getNumberFromTopBot( pos: List<Char>, y: Int, ): List<Int> { val numbers = mutableListOf<Int>() if (pos.none { it.isDigit() }) { // ... // empty top } else if (pos.all { it.isDigit() }) { // XXX // number is directly on top - only 3-digit number are allowed! numbers.add(pos.joinToString(separator = "").toInt()) } else { if (pos.first().isDigit() && !pos[1].isDigit() && !pos.last().isDigit()) { // X.. numbers.add(this.getNumberToTheLeftOf(y)) } else if (pos.first().isDigit() && pos[1].isDigit()) { // XX. numbers.add(this.getNumberToTheLeftOf(y + 1)) } else if (!pos.first().isDigit() && !pos[1].isDigit() && pos.last().isDigit()) { // ..X numbers.add(this.getNumberToTheRightOf(y + 1)) } else if (pos[1].isDigit() && pos.last().isDigit()) { // .XX numbers.add(this.getNumberToTheRightOf(y)) } else if (pos[1].isDigit()) { // .X. // Only middle contains stuff numbers.add(pos[1].toString().toInt()) } else { // X.X numbers.add(this.getNumberToTheLeftOf(y)) numbers.add(this.getNumberToTheRightOf(y + 1)) } } return numbers } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
5,263
Advent-Of-Code
MIT License
src/Day10.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val needSave = setOf(20, 60, 100, 140, 180, 220) var x = 1 var cyc = 0 return input.sumOf { s -> var ret = 0 if(s.contains("noop")) { cyc++ if (needSave.contains(cyc)) { ret = x * cyc } } else { cyc++ if (needSave.contains(cyc)) { ret = x * cyc } cyc++ if (needSave.contains(cyc)) { ret = x * cyc } x += s.takeLastWhile { it != ' ' }.toInt() } ret } } fun part2(input: List<String>): List<String> { var sprite = ".".repeat(1000) + "#".repeat(3) + ".".repeat(1000) var result = "" var pos = 1000 input.forEach { s -> result += sprite[pos] pos = (pos - 999) % 40 + 1000 if(s.contains("addx")) { val move = s.takeLastWhile { it != ' ' }.toInt() result += sprite[pos] pos = (pos - 999) % 40 + 1000 sprite = when { move > 0 -> ".".repeat(move) + sprite.dropLast(move) move < 0 -> sprite.drop(abs(move)) + ".".repeat(abs(move)) else -> sprite } } } return result.chunked(40) } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val expectedAns = listOf( "##..##..##..##..##..##..##..##..##..##..", "###...###...###...###...###...###...###.", "####....####....####....####....####....", "#####.....#####.....#####.....#####.....", "######......######......######......####", "#######.......#######.......#######....." ) check(part2(testInput) == expectedAns) val input = readInput("Day10") println(part1(input)) println(part2(input).joinToString("\n")) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
2,100
aoc2022
Apache License 2.0
src/Day04.kt
alex-rieger
573,375,246
false
null
import org.w3c.dom.ranges.Range fun main() { fun toIntRange(inputs: String): IntRange { val (start, end) = inputs.split('-') return start.toInt()..end.toInt() } fun isFullyContained(left: IntRange, right: IntRange): Boolean { return (left.min() >= right.min() && left.max() <= right.max()) || (right.min() >= left.min() && right.max() <= left.max()) } fun isOverlapping(left: IntRange, right: IntRange): Boolean { return left.min() in right || left.max() in right || right.min() in left || right.max() in left } fun part1(input: List<String>): Int { var result = 0 input.map { line -> val (left, right) = line.split(',').map { toIntRange(it) } if (isFullyContained(left, right)) { result = result.plus(1) } } return result } fun part2(input: List<String>): Int { var result = 0 input.map { line -> val (left, right) = line.split(',').map { toIntRange(it) } if (isOverlapping(left, right)) { result = result.plus(1) } } return result } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
77de0265ff76160e7ea49c9b9d31caa1cd966a46
1,318
aoc-2022-kt
Apache License 2.0
src/main/kotlin/g2201_2300/s2281_sum_of_total_strength_of_wizards/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2281_sum_of_total_strength_of_wizards // #Hard #Array #Stack #Prefix_Sum #Monotonic_Stack // #2023_06_28_Time_673_ms_(100.00%)_Space_58.2_MB_(100.00%) import java.util.Deque import java.util.LinkedList @Suppress("kotlin:S107") class Solution { fun totalStrength(nums: IntArray): Int { val n = nums.size val forward = LongArray(n) val backward = LongArray(n) val prefix = LongArray(n + 1) val suffix = LongArray(n + 1) prefix[1] = nums[0].toLong() forward[0] = prefix[1] suffix[n - 1] = nums[n - 1].toLong() backward[n - 1] = suffix[n - 1] for (i in 1 until n) { forward[i] = nums[i] + forward[i - 1] prefix[i + 1] = prefix[i] + forward[i] } run { var i = n - 2 while (0 <= i) { backward[i] = nums[i] + backward[i + 1] suffix[i] = suffix[i + 1] + backward[i] --i } } var res: Long = 0 val dq: Deque<Int> = LinkedList() for (i in 0 until n) { while (dq.isNotEmpty() && nums[dq.peekLast()] >= nums[i]) { val cur = dq.pollLast() val prev = if (dq.isEmpty()) -1 else dq.peekLast() res = ( ( res + getSum( nums, forward, prefix, backward, suffix, prev, cur, i ) * nums[cur] ) % mod ) } dq.add(i) } while (dq.isNotEmpty()) { val cur = dq.pollLast() val prev = if (dq.isEmpty()) -1 else dq.peekLast() res = ( ( res + getSum(nums, forward, prefix, backward, suffix, prev, cur, n) * nums[cur] ) % mod ) } return res.toInt() } private fun getSum( nums: IntArray, forward: LongArray, prefix: LongArray, backward: LongArray, suffix: LongArray, prev: Int, cur: Int, next: Int ): Long { val sum = (cur - prev) * nums[cur].toLong() % mod * (next - cur) % mod val preSum = getPresum(backward, suffix, prev + 1, cur - 1, next - cur) val postSum = getPostsum(forward, prefix, cur + 1, next - 1, cur - prev) return (sum + preSum + postSum) % mod } private fun getPresum(backward: LongArray, suffix: LongArray, from: Int, to: Int, m: Int): Long { val n = backward.size val cnt = to - from + 1L return ( (suffix[from] - suffix[to + 1] - cnt * (if (to + 1 == n) 0 else backward[to + 1]) % mod) % mod * m % mod ) } private fun getPostsum(forward: LongArray, prefix: LongArray, from: Int, to: Int, m: Int): Long { val cnt = to - from + 1L return ( (prefix[to + 1] - prefix[from] - cnt * (if (0 == from) 0 else forward[from - 1]) % mod) % mod * m % mod ) } companion object { private const val mod = 1e9.toInt() + 7 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,449
LeetCode-in-Kotlin
MIT License
src/main/kotlin/twentytwentytwo/Day23.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import kotlin.math.abs typealias Elve = Pair<Int, Int> fun main() { val input = {}.javaClass.getResource("input-23.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val tinput = {}.javaClass.getResource("input-23-1.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val day = Day23(input) val test = Day23(tinput) println(test.part1()) println(day.part1()) println(day.part2()) } class Day23(private val input: List<String>) { var elves: MutableSet<Elve> = mutableSetOf() var direction: String = "N" fun part1(): Int { elves = input.mapIndexed { y, row -> row.mapIndexed { x, s -> (x to y) to s } }.flatten().filter { p -> p.second == '#' }.map { it.first } .toMutableSet() repeat(10) { val moves = elves.filter { elve -> elve.all().any { elves.contains(it) } }.map { elve -> elve.getNext() to elve }.groupBy { it.first } moves.filter { it.value.size == 1 }.forEach { elves.remove(it.value.first().second) elves.add(it.key) } direction = nextDirection(direction) } println(elves.size) return elves.emptySpaces() } fun part2(): Int { direction = "N" elves = input.mapIndexed { y, row -> row.mapIndexed { x, s -> (x to y) to s } }.flatten().filter { p -> p.second == '#' }.map { it.first } .toMutableSet() repeat(10000) { val moves = elves.filter { elve -> elve.all().any { elves.contains(it) } }.map { elve -> elve.getNext() to elve }.groupBy { it.first } if (moves.isEmpty()) return it + 1 moves.filter { it.value.size == 1 }.forEach { elves.remove(it.value.first().second) elves.add(it.key) } direction = nextDirection(direction) } error("oops") } fun Elve.getNext(): Elve { var next = direction repeat(4) { if (neighbours(next).none { n -> elves.contains(n) }) { return move(next) } next = nextDirection(next) } return this } fun Elve.neighbours(direction: String): List<Elve> { return when (direction) { "N" -> { listOf( first to second - 1, first - 1 to second - 1, first + 1 to second - 1, ) } "S" -> { listOf( first to second + 1, first - 1 to second + 1, first + 1 to second + 1, ) } "W" -> { listOf( first - 1 to second, first - 1 to second + 1, first - 1 to second - 1, ) } "E" -> { listOf( first + 1 to second, first + 1 to second + 1, first + 1 to second - 1, ) } else -> { error("oops") } } } fun Elve.all() = listOf( first to second - 1, first to second + 1, first + 1 to second, first - 1 to second, first - 1 to second + 1, first - 1 to second - 1, first + 1 to second - 1, first + 1 to second + 1, ) fun Elve.move(dir: String): Elve { return when (dir) { "N" -> (first to second - 1) "S" -> (first to second + 1) "W" -> (first - 1 to second) "E" -> (first + 1 to second) else -> { this } } } private fun Set<Elve>.emptySpaces(): Int = (abs(maxOf { it.first } - minOf { it.first }) + 1) * (abs(maxOf { it.second } - minOf { it.second }) + 1) - size companion object { fun nextDirection(dir: String) = when (dir) { "N" -> "S" "S" -> "W" "W" -> "E" "E" -> "N" else -> { error("oops") } } } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
4,410
aoc202xkotlin
The Unlicense
src/main/kotlin/aoc22/Day15.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day15Domain.Sensor import aoc22.Day15Parser.toSensors import aoc22.Day15RunnerPart1.part1Day15 import aoc22.Day15RunnerPart2.part2Day15 import common.Space2D.Point import common.Space2D.Parser.toPoint import common.Year22 import kotlin.math.absoluteValue object Day15: Year22 { fun List<String>.part1(y: Int): Int = part1Day15(y) fun List<String>.part2(gridMax: Int): Long = part2Day15(gridMax) } object Day15RunnerPart1 { fun List<String>.part1Day15(y: Int): Int = toSensors() .countOfNoBeaconAt(y = y) private fun List<Sensor>.countOfNoBeaconAt(y: Int): Int = map { sensor -> sensor.rangeOfXAt(y) } .flatMap { rangeOfX -> rangeOfX.toList() } .filterNot { x -> this.beaconAt(Point(x, y)) } .toSet() .count() private fun List<Sensor>.beaconAt(point: Point) = this.any { it.nearestBeacon.x == point.x && it.nearestBeacon.y == point.y } } object Day15RunnerPart2 { fun List<String>.part2Day15(gridMax: Int): Long = toSensors() .findBeacon(gridMax = gridMax) .toTuningFrequency() private fun List<Sensor>.findBeacon(gridMax: Int): Point { val gridRange = 0 until gridMax return toEdges() .filter { it.x in gridRange && it.y in gridRange } .first { !hasDetected(it) } } private fun List<Sensor>.hasDetected(maybeBeacon: Point): Boolean = any { sensor -> sensor.hasDetected(maybeBeacon) } private fun List<Sensor>.toEdges(): List<Point> = flatMap { it.edges() } fun Point.toTuningFrequency(): Long = (x * 4000000L) + y } object Day15Domain { data class Sensor( val location: Point, val nearestBeacon: Point, ) { private val distanceToBeacon = location.distanceTo(nearestBeacon) fun rangeOfXAt(y: Int, offset: Int = 0): IntRange { val distanceToY = (location.y - y).absoluteValue val maxRangeOfX = maxRangeFor(location.x).add(offset) return IntRange( start = maxRangeOfX.start + distanceToY, endInclusive = maxRangeOfX.endInclusive - distanceToY, ) } private fun IntRange.add(offset: Int): IntRange { return IntRange(this.start - offset, this.endInclusive + offset) } private fun maxRangeFor(int: Int): IntRange = IntRange( start = int - distanceToBeacon, endInclusive = int + distanceToBeacon ) fun edges(): List<Point> { val offset = 1 val maxRangeForY = maxRangeFor(location.y).add(offset) val top = maxRangeForY.start val bottom = maxRangeForY.endInclusive return listOf(Point(location.x, top)) + (top until bottom) .flatMap { y -> rangeOfXAt(y, offset).run { listOf(Point(start, y), Point(endInclusive, y)) } } + listOf(Point(location.x, bottom)) } fun hasDetected(maybeBeacon: Point): Boolean = location.distanceTo(maybeBeacon) <= distanceToBeacon } } object Day15Parser { fun List<String>.toSensors(): List<Sensor> = map { it.split(":").map { it.toPoint() } } .map { Sensor(it[0], it[1]) } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
3,460
aoc
Apache License 2.0
src/main/kotlin/final_450/arrays/kthSmallOrLargeElement.kt
ch8n
312,467,034
false
null
package final_450.arrays fun main() { // Given an array arr[] and a number K where K is smaller // than size of array, the task is to find the Kth smallest // element in the given array. // It is given that all array elements are distinct. /** * * N = 6 arr[] = 7 10 4 3 20 15 K = 3 Output : 7 Explanation : 3rd smallest element in the * given array is 7. */ val k = 3 val input = arrayOf(7, 10, 4, 3, 20, 15) val kSmallest = input.sorted().get(k - 1) println(kSmallest) mergesort(input.toList(), mutableListOf()) } // 7,10,4,3,20,15 // 7 10 4 | 3 20 15 fun mergesort(list: List<Int>, acc: MutableList<List<Int>>) { sliceOrAdd(list, acc) println(acc) } fun sliceOrAdd(list: List<Int>, acc: MutableList<List<Int>>) { val (first, last) = list.equalSplit() val isFirstHavingOneItem = first.size == 1 val isLastHavingOneItem = last.size == 1 if (!isFirstHavingOneItem) { sliceOrAdd(first, acc) } else { val index = acc.indexOfFirst { it[0] < first[0] } acc.add(index, first) } if (!isLastHavingOneItem) { sliceOrAdd(last, acc) } else { val index = acc.indexOfFirst { it[0] < last[0] } acc.add(index, last) } } fun merge() { val input = listOf(0, 0, 0, 1, 2, 2, 2, 1, 0, 1).toMutableList() var pointer0 = 0 var pointer1 = pointer0 var pointer2 = input.lastIndex while (pointer0 <= pointer2) { val value = input[pointer0] when (value) { 0 -> { val first = input[pointer0] val mid = input[pointer1] input.set(pointer0, mid) input.set(pointer1, first) ++pointer0 ++pointer1 } 1 -> { ++pointer1 } 2 -> { val last = input[pointer2] val mid = input[pointer1] input.set(pointer2, mid) input.set(pointer1, last) --pointer2 } } } } fun List<Int>.equalSplit(): Pair<List<Int>, List<Int>> { val length = size return take(length / 2) to drop(length / 2) }
3
Kotlin
0
1
e0619ebae131a500cacfacb7523fea5a9e44733d
2,215
Big-Brain-Kotlin
Apache License 2.0
src/Day07.kt
MisterTeatime
561,848,263
false
{"Kotlin": 20300}
fun main() { fun part1(input: List<String>): Int { return calculate(input.map { Relation.create(it) }.filterNot { it.Command == Mnemonic.NOP }, mutableMapOf(), "a") } fun part2(input: List<String>): Int { return calculate(input.map { Relation.create(it) }.filterNot { it.Command == Mnemonic.NOP }, mutableMapOf("b" to part1(input)), "a") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 72) //Wert an a check(part2(testInput) == 1) val input = readInput("Day07") println(part1(input)) println(part2(input)) println("Ende") } fun calculate(relations: List<Relation>, results: MutableMap<String, Int>, target: String): Int { if (target matches """\d+""".toRegex()) return target.toInt() if (target !in results) { val relation = relations.find { it.Result == target }!! results[target] = when (relation.Command) { Mnemonic.ASSIGN -> calculate(relations, results, relation.Operand1) Mnemonic.AND -> calculate(relations, results, relation.Operand1) and calculate(relations, results, relation.Operand2) Mnemonic.OR -> calculate(relations, results, relation.Operand1) or calculate(relations, results, relation.Operand2) Mnemonic.NOT -> calculate(relations, results, relation.Operand1).toUShort().inv().toInt() Mnemonic.RSHIFT -> calculate(relations, results, relation.Operand1) shr (calculate(relations, results, relation.Operand2)) Mnemonic.LSHIFT -> calculate(relations, results, relation.Operand1) shl (calculate(relations, results, relation.Operand2)) else -> error("unbekanntes Kommando") } } return results[target]!! } data class Relation ( val Command: Mnemonic, val Result: String, val Operand1: String, val Operand2: String = "" ) { companion object { private val regexAssign = """^([a-z]+|[0-9]+) -> ([a-z]+)$""".toRegex() private val regexNot = """NOT ([a-z]+|[0-9]+) -> ([a-z]+)""".toRegex() private val regexAnd = """([a-z]+|[0-9]+) AND ([a-z]+|[0-9]+) -> ([a-z]+)""".toRegex() private val regexOr = """([a-z]+|[0-9]+) OR ([a-z]+|[0-9]+) -> ([a-z]+)""".toRegex() private val regexRShift = """([a-z]+|[0-9]+) RSHIFT ([a-z]+|[0-9]+) -> ([a-z]+)""".toRegex() private val regexLShift = """([a-z]+|[0-9]+) LSHIFT ([a-z]+|[0-9]+) -> ([a-z]+)""".toRegex() fun create(input: String) = when { input matches regexAssign -> { val (op1, res) = regexAssign.find(input)!!.destructured Relation(Mnemonic.ASSIGN, res, op1) } input matches regexNot -> { val (op1, res) = regexNot.find(input)!!.destructured Relation(Mnemonic.NOT, res, op1) } input matches regexAnd -> { val (op1, op2, res) = regexAnd.find(input)!!.destructured Relation(Mnemonic.AND, res, op1, op2) } input matches regexOr -> { val (op1, op2, res) = regexOr.find(input)!!.destructured Relation(Mnemonic.OR, res, op1, op2) } input matches regexRShift -> { val (op1, op2, res) = regexRShift.find(input)!!.destructured Relation(Mnemonic.RSHIFT, res, op1, op2) } input matches regexLShift -> { val (op1, op2, res) = regexLShift.find(input)!!.destructured Relation(Mnemonic.LSHIFT, res, op1, op2) } else -> Relation(Mnemonic.NOP, "","","") } } } enum class Mnemonic { ASSIGN, AND, OR, NOT, RSHIFT, LSHIFT, NOP }
0
Kotlin
0
0
d684bd252a9c6e93106bdd8b6f95a45c9924aed6
3,927
AoC2015
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2022/Day24.kt
tginsberg
568,158,721
false
{"Kotlin": 113322}
/* * Copyright (c) 2022 by <NAME> */ /** * Advent of Code 2022, Day 24 - Blizzard Basin * Problem Description: http://adventofcode.com/2022/day/24 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day24/ */ package com.ginsberg.advent2022 class Day24(input: List<String>) { private val initialMapState: MapState = MapState.of(input) private val start: Point2D = Point2D(input.first().indexOfFirst { it == '.' }, 0) private val goal: Point2D = Point2D(input.last().indexOfFirst { it == '.' }, input.lastIndex) fun solvePart1(): Int = solve().first fun solvePart2(): Int { val toGoal = solve() val backToStart = solve(goal, start, toGoal.second, toGoal.first) val backToGoal = solve(start, goal, backToStart.second, backToStart.first) return backToGoal.first } private fun solve( startPlace: Point2D = start, stopPlace: Point2D = goal, startState: MapState = initialMapState, stepsSoFar: Int = 0 ): Pair<Int, MapState> { val mapStates = mutableMapOf(stepsSoFar to startState) val queue = mutableListOf(PathAttempt(stepsSoFar, startPlace)) val seen = mutableSetOf<PathAttempt>() while (queue.isNotEmpty()) { val thisAttempt = queue.removeFirst() if (thisAttempt !in seen) { seen += thisAttempt val nextMapState = mapStates.computeIfAbsent(thisAttempt.steps + 1) { key -> mapStates.getValue(key - 1).nextState() } // Can we just stand still here? if (nextMapState.isOpen(thisAttempt.location)) queue.add(thisAttempt.next()) val neighbors = thisAttempt.location.cardinalNeighbors() // Is one of our neighbors the goal? if (stopPlace in neighbors) return Pair(thisAttempt.steps + 1, nextMapState) // Add neighbors that will be open to move to on the next turn. neighbors .filter { it == start || (nextMapState.inBounds(it) && nextMapState.isOpen(it)) } .forEach { neighbor -> queue.add(thisAttempt.next(neighbor)) } } } throw IllegalStateException("No path to goal") } private data class PathAttempt(val steps: Int, val location: Point2D) { fun next(place: Point2D = location): PathAttempt = PathAttempt(steps + 1, place) } private data class MapState(val boundary: Point2D, val blizzards: Set<Blizzard>) { private val unsafeSpots = blizzards.map { it.location }.toSet() fun isOpen(place: Point2D): Boolean = place !in unsafeSpots fun inBounds(place: Point2D): Boolean = place.x > 0 && place.y > 0 && place.x <= boundary.x && place.y <= boundary.y fun nextState(): MapState = copy(blizzards = blizzards.map { it.next(boundary) }.toSet()) companion object { fun of(input: List<String>): MapState = MapState( Point2D(input.first().lastIndex - 1, input.lastIndex - 1), input.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, char -> when (char) { '>' -> Blizzard(Point2D(x, y), Point2D(1, 0)) '<' -> Blizzard(Point2D(x, y), Point2D(-1, 0)) 'v' -> Blizzard(Point2D(x, y), Point2D(0, 1)) '^' -> Blizzard(Point2D(x, y), Point2D(0, -1)) else -> null } } }.toSet() ) } } private data class Blizzard(val location: Point2D, val offset: Point2D) { fun next(boundary: Point2D): Blizzard { var nextLocation = location + offset when { nextLocation.x == 0 -> nextLocation = Point2D(boundary.x, location.y) nextLocation.x > boundary.x -> nextLocation = Point2D(1, location.y) nextLocation.y == 0 -> nextLocation = Point2D(location.x, boundary.y) nextLocation.y > boundary.y -> nextLocation = Point2D(location.x, 1) } return copy(location = nextLocation) } } }
0
Kotlin
2
26
2cd87bdb95b431e2c358ffaac65b472ab756515e
4,478
advent-2022-kotlin
Apache License 2.0
src/main/kotlin/days/aoc2021/Day13.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2021 import days.Day class Day13 : Day(2021, 13) { override fun partOne(): Any { return calculateDotsAfterFirstFold(inputList) } override fun partTwo(): Any { return calculateDotsAfterFolds(inputList) } fun calculateDotsAfterFirstFold(inputList: List<String>): Int { val extents = inputList.takeWhile { it.isNotBlank() }.map { line -> Regex("(\\d+),(\\d+)").matchEntire(line.trim())?.destructured?.let { (x, y) -> Pair(x.toInt(), y.toInt()) } }.reduce { acc, pair -> acc?.let { a -> pair?.let { b-> Pair(maxOf(a.first, b.first), maxOf(a.second,b.second)) } } } ?: throw IllegalStateException("Extents didn't work out") val paper = Array(extents.second + 1) { Array(extents.first + 1) { '.' } } inputList.takeWhile { it.isNotBlank() }.forEach { line -> Regex("(\\d+),(\\d+)").matchEntire(line.trim())?.destructured?.let { (x, y) -> paper[y.toInt()][x.toInt()] = '#' } } val folds = inputList.filter { it.startsWith("fold along") } Regex("fold along ([xy])=(\\d+)").matchEntire(folds[0].trim())?.destructured?.let { (axis, position) -> var folded = foldAlongAxis(paper, axis, position.toInt()) return folded.sumBy { row -> row.filter { it == '#' }.count() } } return 0 } fun calculateDotsAfterFolds(inputList: List<String>): Array<Array<Char>> { val extents = inputList.takeWhile { it.isNotBlank() }.map { line -> Regex("(\\d+),(\\d+)").matchEntire(line.trim())?.destructured?.let { (x, y) -> Pair(x.toInt(), y.toInt()) } }.reduce { acc, pair -> acc?.let { a -> pair?.let { b -> Pair(maxOf(a.first, b.first), maxOf(a.second, b.second)) } } } ?: throw IllegalStateException("Extents didn't work out") val paper = Array(extents.second + 1) { Array(extents.first + 1) { '.' } } inputList.takeWhile { it.isNotBlank() }.forEach { line -> Regex("(\\d+),(\\d+)").matchEntire(line.trim())?.destructured?.let { (x, y) -> paper[y.toInt()][x.toInt()] = '#' } } var folded = paper inputList.filter { it.startsWith("fold along") }.forEach { fold -> Regex("fold along ([xy])=(\\d+)").matchEntire(fold.trim())?.destructured?.let { (axis, position) -> println("Folding along $axis axis at $position") folded = foldAlongAxis(folded, axis, position.toInt()) dumpPaper(folded) } } return folded } private fun dumpPaper(paper: Array<Array<Char>>) { paper.forEach { row -> println(row.joinToString("")) } } private fun foldAlongAxis(paper: Array<Array<Char>> , axis: String, position: Int): Array<Array<Char>> { val folded = Array(if (axis == "y") paper.size / 2 else paper.size) { Array(if (axis == "x") paper.first().size / 2 else paper.first().size) { '.' } } when (axis) { "x" -> { val rightmost = paper.first().size - 1 for (y in folded.indices) { for (x in folded.first().indices) { if (paper[y][x] == '#' || paper[y][rightmost - x] == '#') folded[y][x] = '#' } } } "y" -> { val bottom = paper.size - 1 for (y in folded.indices) { for (x in folded.first().indices) { if (paper[y][x] == '#' || paper[bottom - y][x] == '#') folded[y][x] = '#' } } } } return folded } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
4,065
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/Day03.kt
gsalinaslopez
572,839,981
false
{"Kotlin": 21439}
fun main() { fun getRucksackIntersection(rucksack: List<String>): Int = rucksack .map { it.toSet() } .reduce { acc, chars -> acc.intersect(chars) } .first().code.let { if (it <= 90) { it - 38 } else { it - 96 } } fun part1(input: List<String>): Int = input.sumOf { rucksack -> getRucksackIntersection(rucksack.chunked(rucksack.length / 2)) } fun part2(input: List<String>): Int = input.chunked(3).sumOf { rucksack -> getRucksackIntersection(rucksack) } // test if implementation meets criteria from the description, like: 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
041c7c3716bfdfdf4cc89975937fa297ea061830
868
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day07.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2020 import com.dvdmunckhof.aoc.splitOnce import java.util.regex.Pattern import kotlin.streams.asSequence class Day07(private val input: List<String>) { fun solvePart1(bag: String): Int { val bagMap = mutableMapOf<String, MutableList<String>>() for (rule in input) { val (parent, children) = parseRule(rule) for (child in children.keys) { bagMap.getOrPut(child, ::mutableListOf) += parent } } val parents = mutableSetOf<String>() val queue = bagMap.getValue(bag) while (queue.isNotEmpty()) { val node = queue.removeFirst() if (parents.add(node)) { queue += bagMap[node] ?: continue } } return parents.size } fun solvePart2(bag: String): Int { val map = input.map(this::parseRule).associate { it.name to it.children.toList() } return countChildBags(bag, map) } private fun countChildBags(name: String, map: Map<String, List<Pair<String, Int>>>): Int { return map.getValue(name).sumOf { (bag, count) -> count + countChildBags(bag, map) * count } } private fun parseRule(rule: String): BagRule { val (name, content) = rule.splitOnce(" bags contain ") val children = Pattern.compile("(\\d+) (\\w+ \\w+) bag") .matcher(content).results().asSequence() .associate { it.group(2) to it.group(1).toInt() } return BagRule(name, children) } private data class BagRule(val name: String, val children: Map<String, Int>) }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
1,630
advent-of-code
Apache License 2.0
src/main/kotlin/leetcode/Problem2039.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import java.lang.Integer.max import java.util.* /** * https://leetcode.com/problems/the-time-when-the-network-becomes-idle/ */ class Problem2039 { fun networkBecomesIdle(edges: Array<IntArray>, patience: IntArray): Int { val adjList = buildAdjList(edges) val queue = LinkedList<Int>() val visited = mutableSetOf<Int>() val edgeTo = mutableMapOf<Int, Int>() val counts = mutableMapOf<Int, Int>() queue.add(0) while (!queue.isEmpty()) { val current = queue.remove() if (current in visited) { continue } visited.add(current) val neighbors = adjList[current] if (neighbors != null) { for (neighbor in neighbors) { if (neighbor in visited) { continue } if (neighbor !in edgeTo) { edgeTo[neighbor] = current counts[neighbor] = (counts[current] ?: 0) + 1 } queue.add(neighbor) } } } var answer = 0 for (i in 1 until adjList.size) { val time = counts[i]!! * 2 answer = max(answer, (time + (((time - 1) / patience[i]) * patience[i])) + 1) } return answer } private fun buildAdjList(edges: Array<IntArray>): Map<Int, List<Int>> { val map = mutableMapOf<Int, MutableList<Int>>() for (edge in edges) { val list1 = map[edge[0]] ?: mutableListOf() list1 += edge[1] map[edge[0]] = list1 val list2 = map[edge[1]] ?: mutableListOf() list2 += edge[0] map[edge[1]] = list2 } return map } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,837
leetcode
MIT License
leetcode/src/daily/Q921.kt
zhangweizhe
387,808,774
false
null
package daily import java.util.* fun main() { // 921. 使括号有效的最少添加 // https://leetcode.cn/problems/minimum-add-to-make-parentheses-valid/ println(minAddToMakeValid1("()))((")) } fun minAddToMakeValid(s: String): Int { val stack = Stack<Char>() for (c in s) { if (c == ')') { val peek = if (stack.isEmpty()) { null }else { stack.peek() } if (peek == '(') { stack.pop() }else { stack.push(c) } }else { stack.push(c) } } return stack.size } fun minAddToMakeValid1(s: String): Int { // 分别记录左右括号的数量 var leftCount = 0 var rightCount = 0 for (c in s) { if (c == '(') { // 遇到左括号,直接 leftCount++,不管有没有右括号, // 因为即使有右括号,也是在当前左括号之前出现的,不能和当前左括号匹配 leftCount++ }else { // 遇到右括号 if (leftCount > 0) { // 有左括号可以匹配 leftCount-- }else { // 没有左括号可以匹配 rightCount++ } } } return leftCount+rightCount }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,367
kotlin-study
MIT License
src/main/kotlin/com/ginsberg/advent2017/Day20.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 import kotlin.math.absoluteValue /** * AoC 2017, Day 20 * * Problem Description: http://adventofcode.com/2017/day/20 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day20/ */ class Day20(input: List<String>) { private val particles: List<Particle> = input.mapIndexed { idx, s -> parseParticle(idx, s) } fun solvePart1(): Int = (1..1000).fold(particles) { acc, _ -> acc.map { it.move() } }.minBy { it.position.distance }?.id ?: throw IllegalArgumentException("Wat") fun solvePart2(): Int = (1..1000).fold(particles) { acc, _ -> acc.map { it.move() } .groupBy { it.position } .filterValues { it.size == 1 } .flatMap { it.value } }.size private fun parseParticle(id: Int, input: String): Particle = input.split("<", ">").let { Particle( id = id, position = parseVec(it[1]), velocity = parseVec(it[3]), acceleration = parseVec(it[5]) ) } private fun parseVec(input: String): Vec3D = input.split(",").map { it.trim().toLong() }.let { Vec3D(it[0], it[1], it[2]) } data class Vec3D(val x: Long, val y: Long, val z: Long) { val distance: Long = x.absoluteValue + y.absoluteValue + z.absoluteValue operator fun plus(that: Vec3D): Vec3D = Vec3D(x = x + that.x, y = y + that.y, z = z + that.z) } data class Particle(val id: Int, val position: Vec3D, val velocity: Vec3D, var acceleration: Vec3D) { fun move() = this.copy( velocity = velocity + acceleration, position = position + velocity + acceleration ) } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,971
advent-2017-kotlin
MIT License
src/main/kotlin/com/sk/todo-revise/123. Best Time to Buy and Sell Stock III.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.`todo-revise` class Solution123 { fun maxProfit(prices: IntArray): Int { var ans = 0 for (i in 0 until prices.size) { var max1 = 0 var profit1 = 0 for (k in i downTo 0) { max1 = maxOf(max1, prices[k]) profit1 = maxOf(profit1, max1 - prices[k]) } var max2 = 0 var profit2 = 0 for (k in prices.lastIndex downTo i + 1) { max2 = maxOf(max2, prices[k]) profit2 = maxOf(profit2, max2 - prices[k]) } ans = maxOf(ans, profit1 + profit2) } return ans } // From DP formula from https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solutions/135704/detail-explanation-of-dp-solution // /** * dp[k, i] = max(dp[k, i-1], prices[i] - prices[j] + dp[k-1, j-1]), j=[0..i-1] * * dp[k,i] - max profit at i with k transactions * * */ fun maxProfit2(prices: IntArray): Int { if (prices.isEmpty()) return 0 val dp = Array(3) { IntArray(prices.size) } for (k in 1..2) { var min = prices[0] for (i in 1 until prices.size) { min = minOf(min, prices[i] - dp[k - 1][i - 1]) dp[k][i] = maxOf(dp[k][i - 1], prices[i] - min) } } return dp[2][prices.size - 1] } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,436
leetcode-kotlin
Apache License 2.0
src/Day01.kt
stevennoto
573,247,572
false
{"Kotlin": 18058}
fun main() { fun part1(input: List<String>): Int { // Split into groups separated by 2 newlines. Sum each group and keep max. return input.joinToString("\n") .split("\n\n") .maxOf { it.split("\n").sumOf { it.toInt() } } } fun part2(input: List<String>): Int { // Split into groups separated by 2 newlines. Sum each group. Sort, take top 3 and sum. return input.joinToString("\n") .split("\n\n") .map { it.split("\n").sumOf { it.toInt() } } .sortedDescending().take(3).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
42941fc84d50b75f9e3952bb40d17d4145a3036b
867
adventofcode2022
Apache License 2.0
src/Day24.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
import java.util.* import kotlin.math.abs typealias Location = Pair<Int, Int> private operator fun Location.plus(offset: Pair<Int, Int>): Location { return Location(this.first + offset.first, this.second + offset.second) } private fun Location.distanceFrom(another: Location): Int { return abs(this.first - another.first) + abs(this.second - another.second) } private enum class MoveDirection(val offset: Pair<Int, Int>) { Up(Pair(0, -1)), Down(Pair(0, 1)), Left(Pair(-1, 0)), Right(Pair(1, 0)) } private data class Valley( val width: Int, val height: Int, val entrance: Location, val exit: Location, val blizzards: List<Blizzard> ) private data class Blizzard( var location: Location, val direction: MoveDirection, ) private fun parseValley(input: List<String>): Valley { val width = input[0].length val height = input.size var entrance: Location? = null var exit: Location? = null val blizzards = mutableListOf<Blizzard>() for ((y, line) in input.withIndex()) { if (y == 0) { entrance = Location(line.indexOf('.'), y) } else if (y == input.size - 1) { exit = Location(line.indexOf('.'), y) } else { for ((x, c) in line.withIndex()) { when (c) { '>' -> blizzards.add(Blizzard(Location(x, y), MoveDirection.Right)) '<' -> blizzards.add(Blizzard(Location(x, y), MoveDirection.Left)) '^' -> blizzards.add(Blizzard(Location(x, y), MoveDirection.Up)) 'v' -> blizzards.add(Blizzard(Location(x, y), MoveDirection.Down)) } } } } return Valley(width, height, entrance!!, exit!!, blizzards) } private data class PossibleStep( val location: Location, val stepsTaken: List<Location>, val estimateMinTimeToDestination: Int ) : Comparable<PossibleStep> { override fun compareTo(other: PossibleStep): Int { val totalTimeDiff = this.stepsTaken.size + this.estimateMinTimeToDestination - other.stepsTaken.size - other.estimateMinTimeToDestination if (totalTimeDiff != 0) { return totalTimeDiff } val timeSpentDiff = this.stepsTaken.size - other.stepsTaken.size if (timeSpentDiff != 0) { return timeSpentDiff } val xDiff = this.location.first - other.location.first if (xDiff != 0) { return xDiff } return this.location.second - other.location.second } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PossibleStep if (location != other.location) return false if (stepsTaken.size != other.stepsTaken.size) return false if (estimateMinTimeToDestination != other.estimateMinTimeToDestination) return false return true } override fun hashCode(): Int { var result = location.hashCode() result = 31 * result + stepsTaken.size.hashCode() result = 31 * result + estimateMinTimeToDestination return result } } private fun moveBlizzards(blizzards: List<Blizzard>, width: Int, height: Int): List<Blizzard> { return blizzards.map { blizzard -> var newX = blizzard.location.first + blizzard.direction.offset.first var newY = blizzard.location.second + blizzard.direction.offset.second if (newX == 0) { newX = width - 2 } else if (newX == width - 1) { newX = 1 } if (newY == 0) { newY = height - 2 } else if (newY == height - 1) { newY = 1 } Blizzard(Pair(newX, newY), blizzard.direction) } } private fun blizzardsLoop(initialBlizzards: List<Blizzard>, width: Int, height: Int, loop: Int): List<List<Blizzard>> { val blizzardsLoop = mutableListOf(initialBlizzards) var blizzards = initialBlizzards for (i in 2..loop) { blizzards = moveBlizzards(blizzards, width, height) blizzardsLoop.add(blizzards) } return blizzardsLoop } private fun findSteps( valley: Valley, start: Location, end: Location, blizzardsLoop: List<List<Blizzard>>, stepsTaken: Int ): Int { val possibleSteps = TreeSet<PossibleStep>() possibleSteps.add(PossibleStep(start, emptyList(), start.distanceFrom(end))) do { val possibleStep = possibleSteps.first() possibleSteps.remove(possibleStep) val nextBlizzardState = blizzardsLoop[(possibleStep.stepsTaken.size + 1 + stepsTaken) % blizzardsLoop.size] (MoveDirection.values().map { it.offset } + Pair(0, 0)).forEach { offset -> val nextLocation = possibleStep.location + offset if (nextLocation == end) { println("stepsTaken = ${possibleStep.stepsTaken + nextLocation}") return possibleStep.stepsTaken.size + 1 } if ((possibleStep.location == start && nextLocation == start) || (nextLocation.first > 0 && nextLocation.first < valley.width - 1 && nextLocation.second > 0 && nextLocation.second < valley.height - 1 && nextBlizzardState.all { it.location != nextLocation }) ) { possibleSteps.add( PossibleStep( nextLocation, possibleStep.stepsTaken + nextLocation, nextLocation.distanceFrom(end) ) ) } } } while (possibleSteps.isNotEmpty()) throw IllegalStateException("Never found a path to exit") } private fun part1(input: List<String>): Int { val valley = parseValley(input) val blizzardsLoop = blizzardsLoop(valley.blizzards, valley.width, valley.height, (valley.width - 2) * (valley.height - 2)) return findSteps(valley, valley.entrance, valley.exit, blizzardsLoop, 0) } private fun part2(input: List<String>): Int { val valley = parseValley(input) val blizzardsLoop = blizzardsLoop(valley.blizzards, valley.width, valley.height, (valley.width - 2) * (valley.height - 2)) val trip1 = findSteps(valley, valley.entrance, valley.exit, blizzardsLoop, 0) val trip2 = findSteps(valley, valley.exit, valley.entrance, blizzardsLoop, trip1) val trip3 = findSteps(valley, valley.entrance, valley.exit, blizzardsLoop, trip1 + trip2) return trip1 + trip2 + trip3 } fun main() { val input = readInput("Day24") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
6,721
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1402/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1402 /** * LeetCode page: [1402. Reducing Dishes](https://leetcode.com/problems/reducing-dishes/); */ class Solution2 { /* Complexity: * Time O(N^2) and Space O(N) where N is the size of satisfaction; */ fun maxSatisfaction(satisfaction: IntArray): Int { val sortedSatisfaction = satisfaction.sorted() val maxDishes = satisfaction.size var end = -1 /* prefixResult[j] ::= when j dishes are prepared, the result of current sortedSatisfaction * prefix array */ val prefixResult = IntArray(maxDishes + 1) var maxResult = 0 repeat(sortedSatisfaction.size) { updateNextPrefixResult(end, sortedSatisfaction, prefixResult) end++ maxResult = maxOf(maxResult, prefixResult.max()!!) } return maxResult } private fun updateNextPrefixResult( currentEnd: Int, sortedSatisfaction: List<Int>, currentResult: IntArray ) { val newEnd = currentEnd + 1 val maxDishes = newEnd + 1 val likeOfNewDish = sortedSatisfaction[newEnd] // update for the case that all dishes are prepared currentResult[maxDishes] = currentResult[maxDishes - 1] + maxDishes * likeOfNewDish // update for the remaining cases for (numDishes in maxDishes - 1 downTo 1) { val resultIfDiscardNewDish = currentResult[numDishes] val resultIfPrepareNewDish = currentResult[numDishes - 1] + numDishes * likeOfNewDish currentResult[numDishes] = maxOf(resultIfDiscardNewDish, resultIfPrepareNewDish) } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,690
hj-leetcode-kotlin
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[40]组合总和 II.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 // // candidates 中的每个数字在每个组合中只能使用一次。 // // 说明: // // // 所有数字(包括目标数)都是正整数。 // 解集不能包含重复的组合。 // // // 示例 1: // // 输入: candidates = [10,1,2,7,6,1,5], target = 8, //所求解集为: //[ // [1, 7], // [1, 2, 5], // [2, 6], // [1, 1, 6] //] // // // 示例 2: // // 输入: candidates = [2,5,2,1,2], target = 5, //所求解集为: //[ //  [1,2,2], //  [5] //] // Related Topics 数组 回溯算法 // 👍 609 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { //和39 题 一样 递归回溯剪枝 //先排序数组 var res = ArrayList<ArrayList<Int>>() //排好序保证后续剪枝判断是否使用 Arrays.sort(candidates) if (candidates.isEmpty()) return res dfsCombinationSum2(0,LinkedList<Int>(),candidates,target,res) return res } private fun dfsCombinationSum2(index: Int, stack: LinkedList<Int>, candidates: IntArray, target: Int, res: java.util.ArrayList<java.util.ArrayList<Int>>) { //递归结束条件 if(target == 0){ res.add(ArrayList(stack)) return } //逻辑处理 进入下层循环 for (i in index until candidates.size){ //剪枝 //接下来下的值大于目标值 数组排序递增 接下来也不可能有匹配的数 终止 if (target - candidates[i] <0) break //同一层相同数值的结点,从第 2 个开始,候选数更少,结果一定发生重复,因此跳过,用 continue if(i > index && candidates[i] == candidates[i-1]) continue stack.addLast(candidates[i]) dfsCombinationSum2(i+1,stack,candidates,target - candidates[i],res) //回溯 stack.removeLast() } //数据reverse } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,291
MyLeetCode
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/CountAndSay.kt
faniabdullah
382,893,751
false
null
//The count-and-say sequence is a sequence of digit strings defined by the //recursive formula: // // // countAndSay(1) = "1" // countAndSay(n) is the way you would "say" the digit string from countAndSay( //n-1), which is then converted into a different digit string. // // // To determine how you "say" a digit string, split it into the minimal number //of groups so that each group is a contiguous section all of the same character. //Then for each group, say the number of characters, then say the character. To //convert the saying into a digit string, replace the counts with a number and //concatenate every saying. // // For example, the saying and conversion for digit string "3322251": // // Given a positive integer n, return the nᵗʰ term of the count-and-say //sequence. // // // Example 1: // // //Input: n = 1 //Output: "1" //Explanation: This is the base case. // // // Example 2: // // //Input: n = 4 //Output: "1211" //Explanation: //countAndSay(1) = "1" //countAndSay(2) = say "1" = one 1 = "11" //countAndSay(3) = say "11" = two 1's = "21" //countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211" // // // // Constraints: // // // 1 <= n <= 30 // // Related Topics String 👍 895 👎 2576 package leetcodeProblem.leetcode.editor.en class CountAndSay { 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 countAndSay(n: Int): String { if (n == 1) { return "1" } if (n == 2) return "11" if (n == 3) return "21" if (n == 4) return "1211" return countAndSayOperation(4, n, "1211") } private fun countAndSayOperation(position: Int, n: Int, s: String): String { if (position == n) return s var result = "" var count = 0 var say = 0 var lastIndexedValue: Char? = s[0] for (i in s.indices) { if (lastIndexedValue == s[i]) { count++ } else { say = s[i - 1] - '0' result = "$result$count$say" count = 1 lastIndexedValue = s[i] } } if (count >= 1) { say = s[s.lastIndex] - '0' result = "$result$count$say" } return countAndSayOperation(position + 1, n, result) } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { for (i in 1..30) { println(CountAndSay.Solution().countAndSay(i)) } }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,769
dsa-kotlin
MIT License
src/Day02.kt
arisaksen
573,116,584
false
{"Kotlin": 42887}
import Outcome.* import org.assertj.core.api.Assertions.assertThat enum class Opponent(val char: Char) { ROCK('A'), PAPER('B'), SCISSORS('C') } enum class Response(val char: Char) { ROCK('X'), PAPER('Y'), SCISSORS('Z') } enum class Outcome { LOSE, DRAW, WIN } val responseScore: Map<Response, Int> = mapOf(Response.ROCK to 1, Response.PAPER to 2, Response.SCISSORS to 3) val outcomeScore: Map<Outcome, Int> = mapOf(LOSE to 0, DRAW to 3, WIN to 6) /** val (a, _, c) = "X Z" Allow you to deconstruct string to char * operator fun String.component1() = this[0] * operator fun String.component2() = this[1] * operator fun String.component3() = this[1] * val (opponent, _, choice) = "X Z" * */ fun main() { fun part1(rounds: List<String>): Int { var totalScore: Int = 0 rounds.forEach { totalScore += responseScore[response(it)] ?: 0 val outcome = opponentChoice(it).outcome(response(it)) totalScore += outcomeScore[outcome] ?: 0 println("$it - ${opponentChoice(it)} ${response(it)} - ${responseScore[response(it)]} ${outcomeScore[outcome]} $outcome totalscore: $totalScore") } return totalScore } fun part2(rounds: List<String>): Int { var totalScore: Int = 0 rounds.forEach { val outcome = response(it).fixedOutcome() val fixedResponse = fixResponse(opponentChoice(it), response(it).fixedOutcome()) print("${it.last()} -> ${response(it).fixedOutcome()} - ${response(it)} -> $fixedResponse") println(" ====> $it - ${opponentChoice(it)} $fixedResponse - ${responseScore[fixedResponse]} ${outcomeScore[outcome]} $outcome totalscore: $totalScore") totalScore += responseScore[fixedResponse] ?: 0 totalScore += outcomeScore[outcome] ?: 0 } return totalScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") assertThat(part1(testInput)).isEqualTo(15) assertThat(part2(testInput)).isEqualTo(12) val input = readInput("Day02") println("totalscore: " + part1(input)) println("totalscore: " + part2(input)) } private fun Opponent.outcome(response: Response): Outcome = when (this) { Opponent.ROCK -> { when (response) { Response.ROCK -> DRAW Response.PAPER -> WIN Response.SCISSORS -> LOSE } } Opponent.PAPER -> { when (response) { Response.ROCK -> LOSE Response.PAPER -> DRAW Response.SCISSORS -> WIN } } Opponent.SCISSORS -> { when (response) { Response.ROCK -> WIN Response.PAPER -> LOSE Response.SCISSORS -> DRAW } } } fun opponentChoice(input: String): Opponent = when (input.first()) { Opponent.ROCK.char -> Opponent.ROCK Opponent.PAPER.char -> Opponent.PAPER else -> Opponent.SCISSORS } fun response(input: String): Response = when (input.last()) { Response.ROCK.char -> Response.ROCK Response.PAPER.char -> Response.PAPER else -> Response.SCISSORS } // part2 fun Response.fixedOutcome(): Outcome = when (this) { Response.ROCK -> LOSE Response.PAPER -> DRAW Response.SCISSORS -> WIN } fun fixResponse(opponent: Opponent, desiredOutcome: Outcome): Response = when (opponent) { Opponent.ROCK -> { when (desiredOutcome) { WIN -> Response.PAPER DRAW -> Response.ROCK LOSE -> Response.SCISSORS } } Opponent.PAPER -> { when (desiredOutcome) { WIN -> Response.SCISSORS DRAW -> Response.PAPER LOSE -> Response.ROCK } } Opponent.SCISSORS -> { when (desiredOutcome) { WIN -> Response.ROCK DRAW -> Response.SCISSORS LOSE -> Response.PAPER } } }
0
Kotlin
0
0
85da7e06b3355f2aa92847280c6cb334578c2463
4,178
aoc-2022-kotlin
Apache License 2.0
src/test/kotlin/chapter2/solutions/ex2/listing.kt
DavidGomesh
680,857,367
false
{"Kotlin": 204685}
package chapter2.solutions.ex2 import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import kotlinx.collections.immutable.persistentListOf // tag::init[] val <T> List<T>.tail: List<T> get() = drop(1) val <T> List<T>.head: T get() = first() fun <A> isSorted(aa: List<A>, order: (A, A) -> Boolean): Boolean { tailrec fun go(x: A, xs: List<A>): Boolean = if (xs.isEmpty()) true else if (!order(x, xs.head)) false else go(xs.head, xs.tail) return aa.isEmpty() || go(aa.head, aa.tail) } // end::init[] class Solution2 : WordSpec({ "isSorted" should { """detect ordering of a list of correctly ordered Ints based on an ordering HOF""" { isSorted( persistentListOf(1, 2, 3) ) { a, b -> b > a } shouldBe true } """detect ordering of a list of incorrectly ordered Ints based on an ordering HOF""" { isSorted( persistentListOf(1, 3, 2) ) { a, b -> b > a } shouldBe false } """verify ordering of a list of correctly ordered Strings based on an ordering HOF""" { isSorted( persistentListOf("a", "b", "c") ) { a, b -> b > a } shouldBe true } """verify ordering of a list of incorrectly ordered Strings based on an ordering HOF""" { isSorted( persistentListOf("a", "z", "w") ) { a, b -> b > a } shouldBe false } "return true for an empty list" { isSorted(persistentListOf<Int>()) { a, b -> b > a } shouldBe true } } })
0
Kotlin
0
0
41fd131cd5049cbafce8efff044bc00d8acddebd
1,774
fp-kotlin
MIT License
src/main/kotlin/me/consuegra/algorithms/KSearchInsertPosition.kt
aconsuegra
91,884,046
false
{"Java": 113554, "Kotlin": 79568}
package me.consuegra.algorithms /** * Given a sorted array and a target value, return the index if the target is found. If not, return the index * where it would be if it were inserted in order. * <p> * You may assume no duplicates in the array. * <p> * Here are few examples. * [1,3,5,6], 5 → 2 * [1,3,5,6], 2 → 1 * [1,3,5,6], 7 → 4 * [1,3,5,6], 0 → 0 */ class KSearchInsertPosition { fun searchInsert(input: IntArray, target: Int): Int { var low = 0 var high = input.size - 1 while (low <= high) { val middle = (low + high) / 2 when { input[middle] < target -> low = middle + 1 input[middle] > target -> high = middle - 1 else -> return middle } } return low } fun searchInsertRec(input: IntArray, target: Int): Int { if (input.isEmpty()) { return 0 } return searchInsertRec(input, 0, input.size - 1, target) } fun searchInsertRec(input: IntArray, start: Int, end: Int, target: Int): Int { if (start > end) { return start } val middle = (start + end) / 2 when { input[middle] < target -> return searchInsertRec(input, middle + 1, end, target) input[middle] > target -> return searchInsertRec(input, start, middle - 1, target) else -> return middle } } }
0
Java
0
7
7be2cbb64fe52c9990b209cae21859e54f16171b
1,452
algorithms-playground
MIT License
21/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File import java.util.Collections.max import java.util.Collections.min fun readInput() : Game { val input = File("input.txt") .readLines() val posRegex = """Player (\d+) starting position: (\d+)""".toRegex() val (_, player1Pos) = posRegex.find(input[0])?.destructured!! val (_, player2Pos) = posRegex.find(input[1])?.destructured!! return Game(player1Pos.toInt(), player2Pos.toInt()) } class Game(player1Pos : Int, player2Pos : Int) { companion object { const val DIE_MAX_VAL = 100 const val MIN_SCORE_TO_WIN = 1000 const val MAX_POS = 10 const val ROLLS_PER_TURN = 3 } private val playersPos = mutableListOf(player1Pos, player2Pos) private var dieCurVal = 1 private var playerToMove = 0 private val scores = mutableListOf(0, 0) private var turns = 0 private var dieRolls = 0 fun playTurn() { playersPos[playerToMove] = makeMove(playerToMove) scores[playerToMove] += playersPos[playerToMove] changePlayerToMove() turns += 1 } private fun makeMove(player : Int) : Int { var diceSum = 0 for (i in 1..ROLLS_PER_TURN) { diceSum += dieCurVal updateDieVal() } val pos = (playersPos[player] + diceSum) % MAX_POS return if (pos == 0) MAX_POS else pos } private fun updateDieVal() { dieRolls += 1 dieCurVal = (dieCurVal + 1) % DIE_MAX_VAL if (dieCurVal == 0) dieCurVal = DIE_MAX_VAL } private fun changePlayerToMove() { playerToMove = 1 - playerToMove } fun isFinished() : Boolean { return max(scores) >= MIN_SCORE_TO_WIN } fun calcScore() : Int { return min(scores) * dieRolls; } } fun solve(game : Game) : Int { while(!game.isFinished()) { game.playTurn() } return game.calcScore() } fun main() { val game = readInput() val ans = solve(game) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
2,011
advent-of-code-2021
MIT License
kotlin/2022/day03/Day03.kt
nathanjent
48,783,324
false
{"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966}
class Day03 { fun part1(input: Iterable<String>): Int { val result = input .asSequence() .filter { !it.isBlank() } .map { it.toCharArray() } .map { val half = it.size / 2 Pair(it.sliceArray(0 until half), it.sliceArray(half until it.size)) } .map { it.first.intersect( it.second.asIterable().toSet() ) } .map { it.first() } .map { itemPriority(it) } .toList() return result.sum() } fun part2(input: Iterable<String>): Int { var result = input .filter { it.isNotBlank() } .map { it.toCharArray() } .chunked(3) .map { val i1 = it[0].intersect( it[1].asIterable().toSet() ) val i2 = it[1].intersect( it[2].asIterable().toSet() ) i1.intersect(i2) } .flatMap { it.asIterable() } .map { itemPriority(it) } return result.sum() } private fun itemPriority(it: Char): Int { return when (it) { in 'a'..'z' -> it - 'a' + 1 in 'A'..'Z' -> it - 'A' + 27 else -> throw Exception() } } }
0
Rust
0
0
7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf
1,148
adventofcode
MIT License
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day12/Day12.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day12 import eu.janvdb.aocutil.kotlin.point2d.Direction import eu.janvdb.aocutil.kotlin.point2d.Point2D import eu.janvdb.aocutil.kotlin.readLines val INSTRUCTION_REGEX = Regex("([NSEWLRF])(\\d+)") fun main() { val instructions = readLines(2020, "input12.txt").map(::parseInstruction) var position1 = Position1(Point2D(0, 0), Direction.E) instructions.forEach { position1 = position1.step(it) } println("At $position1 with distance ${position1.coordinate.manhattanDistance()}") var position2 = Position2(Point2D(0, 0), Point2D(10, 1)) instructions.forEach { position2 = position2.step(it) } println("At $position2 with distance ${position2.coordinate.manhattanDistance()}") } fun parseInstruction(instruction: String): Instruction { val matchResult = INSTRUCTION_REGEX.matchEntire(instruction) ?: throw IllegalArgumentException(instruction) return Instruction(InstructionType.valueOf(matchResult.groupValues[1]), matchResult.groupValues[2].toInt()) } enum class InstructionType { N, S, E, W, L, R, F } data class Instruction(val instructionType: InstructionType, val amount: Int) data class Position1(val coordinate: Point2D, val direction: Direction) { fun step(instruction: Instruction): Position1 { val amount = instruction.amount return when (instruction.instructionType) { InstructionType.N -> Position1(coordinate.move(Direction.N, amount), direction) InstructionType.E -> Position1(coordinate.move(Direction.E, amount), direction) InstructionType.S -> Position1(coordinate.move(Direction.S, amount), direction) InstructionType.W -> Position1(coordinate.move(Direction.W, amount), direction) InstructionType.L -> Position1(coordinate, direction.rotateLeft(amount)) InstructionType.R -> Position1(coordinate, direction.rotateRight(amount)) InstructionType.F -> Position1(coordinate.move(direction, amount), direction) } } } data class Position2(val coordinate: Point2D, val waypoint: Point2D) { fun step(instruction: Instruction): Position2 { val amount = instruction.amount return when (instruction.instructionType) { InstructionType.N -> Position2(coordinate, waypoint.move(Direction.N, amount)) InstructionType.E -> Position2(coordinate, waypoint.move(Direction.E, amount)) InstructionType.S -> Position2(coordinate, waypoint.move(Direction.S, amount)) InstructionType.W -> Position2(coordinate, waypoint.move(Direction.W, amount)) InstructionType.L -> Position2(coordinate, waypoint.rotateLeft(amount)) InstructionType.R -> Position2(coordinate, waypoint.rotateRight(amount)) InstructionType.F -> Position2(coordinate.move(waypoint, amount), waypoint) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,670
advent-of-code
Apache License 2.0
src/main/kotlin/g0401_0500/s0474_ones_and_zeroes/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0474_ones_and_zeroes // #Medium #Array #String #Dynamic_Programming // #2022_12_31_Time_204_ms_(100.00%)_Space_35.7_MB_(92.31%) class Solution { /* * The problem can be interpreted as: * What's the max number of str can we pick from strs with limitation of m "0"s and n "1"s. * * Thus we can define dp[i][j] as it stands for max number of str can we pick from strs with limitation * of i "0"s and j "1"s. * * For each str, assume it has a "0"s and b "1"s, we update the dp array iteratively * and set dp[i][j] = Math.max(dp[i][j], dp[i - a][j - b] + 1). * So at the end, dp[m][n] is the answer. */ fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int { val dp = Array(m + 1) { IntArray(n + 1) } for (str in strs) { val count = count(str) for (i in m downTo count[0]) { for (j in n downTo count[1]) { dp[i][j] = Math.max(dp[i][j], dp[i - count[0]][j - count[1]] + 1) } } } return dp[m][n] } private fun count(str: String): IntArray { val res = IntArray(2) for (i in 0 until str.length) { res[str[i].code - '0'.code]++ } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,296
LeetCode-in-Kotlin
MIT License
2023/src/main/kotlin/de/skyrising/aoc2023/day17/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day17 import de.skyrising.aoc.* import kotlin.math.absoluteValue data class Node(val posX: Int, val posY: Int, val dir: Direction, val dirCount: Int) private inline fun IntGrid.getOutgoing(node: Node): Collection<Edge<Node, Unit?>> { val edges = ArrayList<Edge<Node, Unit?>>(3) for (i in 0..3) { val dir = Direction(i) if (dir == -node.dir) continue if (node.dirCount >= 3 && dir == node.dir) continue val posX = node.posX + dir.x val posY = node.posY + dir.y if (!contains(posX, posY)) continue val loss = this[posX, posY] edges.add(Edge(node, Node(posX, posY, dir, if (dir == node.dir) node.dirCount + 1 else 1), loss, Unit)) } return edges } private inline fun IntGrid.getOutgoing2(node: Node): Collection<Edge<Node, Unit?>> { val edges = ArrayList<Edge<Node, Unit?>>(3) for (i in 0..3) { val dir = Direction(i) if (dir == -node.dir) continue if (node.dirCount in 1..3 && dir != node.dir) continue if (node.dirCount >= 10 && dir == node.dir) continue var step = 1 if (node.dir == dir && node.dirCount in 1..3) step = 4 - node.dirCount else if (dir != node.dir) step = 4 while (!contains(node.posX + dir.x * step, node.posY + dir.y * step)) step-- if (step <= 0) continue var posX = node.posX var posY = node.posY var loss = 0 repeat(step) { posX += dir.x posY += dir.y loss += this[posX, posY] } edges.add(Edge(node, Node(posX, posY, dir, if (dir == node.dir) node.dirCount + step else step), loss, Unit)) } return edges } private const val ASTAR = false private inline fun PuzzleInput.run(out: IntGrid.(Node) -> Collection<Edge<Node, Unit?>>, isEnd: (Node)->Boolean): Int { val cg = charGrid val grid = IntGrid(cg.width, cg.height, IntArray(cg.width * cg.height) { cg.data[it].digitToInt() }) val start = Node(0, 0, Direction.E, 0) val end = Vec2i(cg.width - 1, cg.height - 1) val path = if(ASTAR) { astar(start, { (end.x - it.posX).absoluteValue + (end.y - it.posY).absoluteValue }, { it.posX == end.x && it.posY == end.x && isEnd(it) }, { grid.out(it) } )!! } else { dijkstra(start, { it.posX == end.x && it.posY == end.x && isEnd(it) }, { grid.out(it) } )!! } return path.sumOf { it.weight } } val test = TestInput(""" 2413432311323 3215453535623 3255245654254 3446585845452 4546657867536 1438598798454 4457876987766 3637877979653 4654967986887 4564679986453 1224686865563 2546548887735 4322674655533 """) @PuzzleName("Clumsy Crucible") fun PuzzleInput.part1() = run(IntGrid::getOutgoing) { true } fun PuzzleInput.part2() = run(IntGrid::getOutgoing2) { it.dirCount >= 4 }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
2,980
aoc
MIT License
src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2846_minimum_edge_weight_equilibrium_queries_in_a_tree // #Hard #Array #Tree #Graph #Strongly_Connected_Component // #2023_12_18_Time_982_ms_(100.00%)_Space_72.6_MB_(66.67%) import kotlin.math.ln import kotlin.math.max @Suppress("kotlin:S107") class Solution { private class Node(var v: Int, var w: Int) fun minOperationsQueries(n: Int, edges: Array<IntArray>, queries: Array<IntArray>): IntArray { val graph = createGraph(edges, n) val queryCount = queries.size val res = IntArray(queryCount) val parent = IntArray(n) val level = IntArray(n) val weightFreq = Array(n) { IntArray(27) } val freq = IntArray(27) val height = (ln(n.toDouble()) / ln(2.0)).toInt() + 1 val up = Array(n) { IntArray(height) } for (arr in up) { arr.fill(-1) } dfs(graph, 0, 0, -1, parent, level, weightFreq, freq) for (i in 0 until n) { up[i][0] = parent[i] } for (i in 1 until height) { for (j in 0 until n) { if (up[j][i - 1] == -1) { up[j][i] = -1 continue } up[j][i] = up[up[j][i - 1]][i - 1] } } for (i in 0 until queryCount) { val src = queries[i][0] val dest = queries[i][1] val lcaNode = lca(src, dest, up, height, level) res[i] = processResult(weightFreq[src], weightFreq[dest], weightFreq[lcaNode]) } return res } private fun lca(src: Int, dest: Int, up: Array<IntArray>, height: Int, level: IntArray): Int { var curr1 = src var curr2 = dest val minlevel: Int if (level[curr1] > level[curr2]) { minlevel = level[curr2] curr1 = getKthAncestor(curr1, level[curr1] - level[curr2], up, height) } else if (level[curr1] <= level[curr2]) { minlevel = level[curr1] curr2 = getKthAncestor(curr2, level[curr2] - level[curr1], up, height) } else { minlevel = level[curr1] } if (curr1 == curr2) { return curr1 } var l = 0 var h = level[curr2] while (l <= h) { val mid = l + (h - l) / 2 val p1 = getKthAncestor(curr1, minlevel - mid, up, height) val p2 = getKthAncestor(curr2, minlevel - mid, up, height) if (p1 == p2) { l = mid + 1 } else { h = mid - 1 } } return getKthAncestor(curr1, minlevel - l + 1, up, height) } private fun getKthAncestor(node: Int, k: Int, up: Array<IntArray>, height: Int): Int { var curr = node var i = 0 while (i < height && k shr i != 0) { if (((1 shl i) and k) != 0) { if (curr == -1) { return -1 } curr = up[curr][i] } i++ } return curr } private fun processResult(freqSrc: IntArray, freqDest: IntArray, freqLCA: IntArray): Int { val freqPath = IntArray(27) for (i in 1..26) { freqPath[i] = freqSrc[i] + freqDest[i] - 2 * freqLCA[i] } var max = 0 var pathlen = 0 for (i in 1..26) { max = max(max.toDouble(), freqPath[i].toDouble()).toInt() pathlen += freqPath[i] } return pathlen - max } private fun dfs( graph: List<MutableList<Node>>, src: Int, currlevel: Int, p: Int, parent: IntArray, level: IntArray, weightFreq: Array<IntArray>, freq: IntArray ) { parent[src] = p level[src] = currlevel System.arraycopy(freq, 0, weightFreq[src], 0, freq.size) for (node in graph[src]) { val v = node.v val w = node.w if (v != p) { freq[w]++ dfs(graph, v, currlevel + 1, src, parent, level, weightFreq, freq) freq[w]-- } } } private fun createGraph(edges: Array<IntArray>, n: Int): List<MutableList<Node>> { val graph: MutableList<MutableList<Node>> = ArrayList() for (i in 0 until n) { graph.add(ArrayList()) } for (edge in edges) { val u = edge[0] val v = edge[1] val w = edge[2] graph[u].add(Node(v, w)) graph[v].add(Node(u, w)) } return graph } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
4,617
LeetCode-in-Kotlin
MIT License
src/main/kotlin/day6.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
fun day6 (lines: List<String>) { val races = parseRaces(lines) var part1 = 1L races.forEach { part1 *= getWaysToWin(it) } val longRace = parseRace(lines) val part2 = getWaysToWin(longRace) println("Day 6 part 1: $part1") println("Day 6 part 2: $part2") println() } fun getWaysToWin(race: Race): Int { val distances = mutableListOf<Long>() for (i in 0..<race.time) { val distance = (race.time - i) * i distances.add(distance) } return distances.filter { it > race.recordDistance }.count() } fun parseRace(lines: List<String>): Race { val time = lines[0].replace("\\s+".toRegex(), "").split(":")[1].split(" ").map { it.toLong() }[0] val distance = lines[1].replace("\\s+".toRegex(), "").split(":")[1].split(" ").map { it.toLong() }[0] return Race(time, distance) } fun parseRaces(lines: List<String>): List<Race> { val times = lines[0].replace("\\s+".toRegex(), " ").split(": ")[1].split(" ").map { it.toLong() } val distances = lines[1].replace("\\s+".toRegex(), " ").split(": ")[1].split(" ").map { it.toLong() } val races = mutableListOf<Race>() for (i in times.indices) { races.add(Race(times[i], distances[i])) } return races } data class Race (val time: Long, val recordDistance: Long)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
1,361
advent_of_code_2023
MIT License
src/Day04.kt
pimtegelaar
572,939,409
false
{"Kotlin": 24985}
fun main() { fun String.range(): IntRange { val (start, end) = split("-") return IntRange(start.toInt(), end.toInt()) } fun String.rangePair(): Pair<IntRange, IntRange> { val (first, second) = split(",") return Pair(first.range(), second.range()) } fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last fun part1(input: List<String>) = input.count { val (first, second) = it.rangePair() first.contains(second) || second.contains(first) } fun part2(input: List<String>) = input.count { val (first, second) = it.rangePair() first.intersect(second).isNotEmpty() } val testInput = readInput("Day04_test") val input = readInput("Day04") val part1 = part1(testInput) check(part1 == 2) { part1 } println(part1(input)) val part2 = part2(testInput) check(part2 == 4) { part2 } println(part2(input)) }
0
Kotlin
0
0
16ac3580cafa74140530667413900640b80dcf35
962
aoc-2022
Apache License 2.0
app/src/main/kotlin/solution/Solution907.kt
likexx
559,794,763
false
{"Kotlin": 136661}
package solution import solution.annotation.Leetcode import java.util.PriorityQueue import kotlin.math.pow class Solution907 { @Leetcode(907) class Solution { fun sumSubarrayMins(arr: IntArray): Int { // monotonic stack + dp var total = 0L val N = arr.size val mod = (Math.pow(10.0, 9.0) + 7).toLong() val s = mutableListOf<Int>() val dp = LongArray(N) for (i in 0..N-1) { while (s.isNotEmpty() && arr[s.last()]>=arr[i]) { s.removeAt(s.size-1) } if (s.isNotEmpty()) { dp[i] = dp[s.last()] + (i-s.last())*arr[i].toLong() } else { dp[i] = (i+1)*arr[i].toLong() // e.g. for arr[0], dp[0]=arr[0] } s.add(i) } dp.forEach { total += it } return (total%mod).toInt() } fun sumSubarrayMins_Stack(arr: IntArray): Int { var total = 0L val N = arr.size val mod = (Math.pow(10.0, 9.0) + 7).toLong() val s = mutableListOf<Int>() for (i in 0..N) { while (s.isNotEmpty() && (i==N || arr[s.last()]>=arr[i])) { val m = s.last() s.removeAt(s.size-1) val left = if (s.isEmpty()) { -1 } else { s.last() } val right = i total += arr[m].toLong()*(m-left)*(right-m) } s.add(i) } return (total%mod).toInt() } fun sumSubarrayMins_SegmentTree(arr: IntArray): Int { val N = arr.size val tree = IntArray(2*N) { Int.MAX_VALUE } for (i in 0..N-1) { var j = i+N tree[j] = arr[i] while (j>1) { j /= 2 tree[j] = kotlin.math.min(tree[j*2], tree[j*2+1]) } } fun queryMin(i: Int, j: Int): Int { var left = i + N var right= j + N + 1 var minValue = kotlin.Int.MAX_VALUE while (left < right) { if (left and 1 == 1) { minValue = kotlin.math.min(minValue, tree[left]) left += 1 } if (right and 1 == 1) { right -= 1 minValue = kotlin.math.min(minValue, tree[right]) } left /= 2 right /= 2 } return minValue } var result = 0 val mod = (Math.pow(10.0, 9.0) + 7).toInt() for (i in 0..N-1) { for (j in i..N-1) { result += queryMin(i, j) result %= mod } } return result } } }
0
Kotlin
0
0
376352562faf8131172e7630ab4e6501fabb3002
3,027
leetcode-kotlin
MIT License
pracexam1problem3/TwoStringMasks.kt
laitingsheng
341,616,623
false
null
class TwoStringMasks { private val IMPOSSIBLE: String = "impossible" private fun String.trim(b: Int): String { var i = b while (this[i] != '*') ++i return removeRange(i, i + 1) } private fun String.combine(b1: Int, e1: Int, other: String, b2: Int, e2: Int): String { val nb2 = b2 + 1 var tb1 = b1 var l1 = e1 - tb1 val l2 = e2 - nb2 + 1 if (l1 > l2) { tb1 += l1 - l2 l1 = l2 } while (tb1 < e1 && subSequence(tb1, tb1 + l1) != other.subSequence(nb2, nb2 + l1)) { ++tb1 --l1 } val sb = StringBuilder(tb1 + other.length - b2) sb.append(this, 0, tb1) sb.append(other, nb2, other.length) return sb.toString() } fun shortestCommon(s1: String, s2: String): String { var b1 = 0 var b2 = 0 var c1 = s1[b1] var c2 = s2[b2] while (c1 != '*' && c2 != '*') { if (c1 != c2) return IMPOSSIBLE c1 = s1[++b1] c2 = s2[++b2] } var e1 = s1.length - 1 var e2 = s2.length - 1 c1 = s1[e1] c2 = s2[e2] while (c1 != '*' && c2 != '*') { if (c1 != c2) return IMPOSSIBLE c1 = s1[--e1] c2 = s2[--e2] } return when { b1 == e1 -> s2.trim(b2) b2 == e2 -> s1.trim(b1) s1[e1] == '*' -> s1.combine(b1, e1, s2, b2, e2) else -> s2.combine(b2, e2, s1, b1, e1) } } }
0
Kotlin
0
0
2fc3e7a23d37d5e81cdf19a9ea19901b25941a49
1,605
2020S1-COMP-SCI-7007
ISC License
2021/src/day11/Day11.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day11 import readInput fun flash(list: Array<IntArray>, x: Int, y: Int) { if (x < 0 || y < 0 || y >= list.size || x >= list[y].size) { return } val current = list[y][x] list[y][x] += 1 if (current == 9) { for (i in -1..1) { for (j in -1..1) { if (!(i == 0 && j == 0)) { flash(list, x + i, y + j) } } } } } fun part1(lines: List<String>) : Int { val octopuses = Array(lines.size) { intArrayOf() } for (i in lines.indices) octopuses[i] = lines[i].chunked(1).map{ it.toInt() }.toIntArray() val numberOfSteps = 100 var flashes = 0 for (i in 1..numberOfSteps) { for (y in octopuses.indices) { for (x in octopuses.indices) { flash(octopuses, x, y) } } // reset the > 9 by 0's for (y in octopuses.indices) { for (x in octopuses.indices) { if (octopuses[y][x] > 9) { flashes++ octopuses[y][x] = 0 } } } } return flashes } fun part2(lines: List<String>) : Long { val octopuses = Array(lines.size) { intArrayOf() } for (i in lines.indices) octopuses[i] = lines[i].chunked(1).map{ it.toInt() }.toIntArray() var steps = 0L while (true) { for (y in octopuses.indices) { for (x in octopuses.indices) { flash(octopuses, x, y) } } // reset the > 9 by 0's var allFlashing = true for (y in octopuses.indices) { for (x in octopuses.indices) { if (octopuses[y][x] > 9) { octopuses[y][x] = 0 } else { allFlashing = false } } } if (allFlashing) return ++steps steps++ } return -1 } fun main() { val simpleInput = readInput("day11/simple") println("part1(simpleInput) => " + part1(simpleInput)) println("part2(simpleInput) => " + part2(simpleInput)) val testInput = readInput("day11/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day11/input") println("part1(input) => " + part1(input)) println("part1(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,418
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestAlternatingPaths.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue import kotlin.math.min /** * 1129. Shortest Path with Alternating Colors * @see <a href="https://leetcode.com/problems/shortest-path-with-alternating-colors/">Source</a> */ fun interface ShortestAlternatingPaths { operator fun invoke(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray } class ShortestAlternatingPathsBFS : ShortestAlternatingPaths { override operator fun invoke(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray { val graph: Array<Array<MutableSet<Int>>> = Array<Array<MutableSet<Int>>>(n) { Array(2) { HashSet() } } for (i in 0 until n) { graph[i][0] = HashSet() graph[i][1] = HashSet() } for (re in redEdges) { graph[re[0]][0].add(re[1]) } for (be in blueEdges) { graph[be[0]][1].add(be[1]) } val res = Array(n) { IntArray(2) } for (i in 1 until n) { res[i][1] = n * 2 res[i][0] = res[i][1] } val q: Queue<IntArray> = LinkedList() q.offer(intArrayOf(0, 0)) q.offer(intArrayOf(0, 1)) while (q.isNotEmpty()) { val cur: IntArray = q.poll() val ind = cur[0] val col = cur[1] for (next in graph[ind][1 - col]) { if (res[next][1 - col] == n * 2) { res[next][1 - col] = res[ind][col] + 1 q.offer(intArrayOf(next, 1 - col)) } } } val ans = IntArray(n) for (i in 0 until n) { val min = min(res[i][0], res[i][1]) ans[i] = if (min == n * 2) -1 else min } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,441
kotlab
Apache License 2.0
src/aoc2022/Day21.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.checkEquals object Day21 { fun List<String>.graphYelling(): HashMap<String, String> { val map = hashMapOf<String, String>() this.forEach { val (name, yell) = it.split(": ") map[name] = yell } return map } fun HashMap<String, String>.yell(name: String): Long { val yell = getValue(name) if (yell.toLongOrNull() != null) return yell.toLong() val (first, op, second) = yell.split(' ') val result = op.eval(yell(first), yell(second)) put(name, "$result") return getValue(name).toLong() } fun part1(input: List<String>): Long { return input.graphYelling().yell("root") } fun part2(input: List<String>): Long { val original = input.graphYelling() original["root"] = original.getValue("root").replace('+', '=') var minHumn = 1L var maxHumn = 100000000000000 var humn: Long do { val graph = HashMap(original) humn = (maxHumn + minHumn) / 2 graph["humn"] = "$humn" when (graph.yell("root")) { -1L -> maxHumn =humn - 1 1L -> minHumn = humn + 1 // 0L -> break } } while (graph["root"]!!.toInt() != 0) return humn } fun HashMap<String, String>.yell(): Long = DeepRecursiveFunction { name -> val yell = getValue(name) if (yell.toLongOrNull() != null) return@DeepRecursiveFunction yell.toLong() val (first, op, second) = yell.split(' ') val result = op.eval(callRecursive(first), callRecursive(second)) put(name, "$result") return@DeepRecursiveFunction result } .invoke("root") private fun String.eval(first: Long, second: Long): Long = when (this.single()) { '+' -> first + second '-' -> first - second '*' -> first * second '/' -> first / second '=' -> first.compareTo(second).toLong() else -> error("unsupported operation") } val testInput = readInput("Day21_test") val input = readInput("Day21") } fun main(): Unit = with(Day21) { part1(testInput).checkEquals(152) part1(input).checkEquals(256997859093114) // .sendAnswer(part = 1, day = "21", year = 2022) // part2(testInput).checkEquals(301) part2(input).checkEquals(3952288690726) // .sendAnswer(part = 2, day = "21", year = 2022) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
2,507
Kotlin-AOC-2023
Apache License 2.0
test/leetcode/SumOfDigitsOfStringAfterConvert.kt
andrej-dyck
340,964,799
false
null
package leetcode import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource /** * https://leetcode.com/problems/sum-of-digits-of-string-after-convert/ * * 1945. Sum of Digits of String After Convert * [Easy] * * You are given a string s consisting of lowercase English letters, and an integer k. * * First, convert s into an integer by replacing each letter with its position in the alphabet * (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer * by replacing it with the sum of its digits. Repeat the transform operation k times in total. * * For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations: * - convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 * - transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 * - transform #2: 17 ➝ 1 + 7 ➝ 8 * * Return the resulting integer after performing the operations described above. * * Constraints: * - 1 <= s.length <= 100 * - 1 <= k <= 10 * - s consists of lowercase English letters. */ fun getLucky(word: String, k: Int = 0): Int = sumOfDigits( alphabetPositions(word).joinToString(""), iterations = k ).toIntOrNull() ?: 0 /* convert */ private fun alphabetPositions(word: String) = word.mapNotNull(Char::alphabetPosition) fun Char.isAlphabetLetter() = this in 'a'..'z' fun Char.alphabetPosition() = if (isAlphabetLetter()) code - 'a'.code + 1 else null /* transform */ private fun sumOfDigits(number: String, iterations: Int) = generateSequence(number) { it.sumOf(Char::digitToInt).toString() } .take(iterations + 1) .last() /** * Unit Tests */ class SumOfDigitsOfStringAfterConvertTest { @ParameterizedTest @CsvSource( "'', 0", "a, 1", "b, 2", "c, 3", "z, 26", "abc, 123", "xyz, 242526" ) fun `with k = 0, it just converts to lower-case letters alphabet positions`( englishLetters: String, expectedSum: Int ) { assertThat(getLucky(englishLetters)).isEqualTo(expectedSum) } @ParameterizedTest @CsvSource( "'', 0", "a, 1", "b, 2", "c, 3", "z, 8", // 26 -> 2+6 -> 8 "abc, 6", "xyz, 21" // 24,25,26 -> 2+4+2+5+2+6 -> 21 ) fun `with k = 1, it's the sum of digits after conversion`( englishLetters: String, expectedSum: Int ) { assertThat(getLucky(englishLetters, k = 1)).isEqualTo(expectedSum) } @ParameterizedTest @CsvSource( "'', 5, 0", "a, 0, 1", "a, 2, 1", "z, 2, 8", // 26 -> 2+6 -> 8 "xyz, 2, 3", // 24,25,26 -> 2+4+2+5+2+6 -> 21 -> 2+1 -> 3 "iiii, 1, 36", // 9,9,9,9 -> 9+9+9+9 -> 36 "iiii, 2, 9", // 9,9,9,9 -> 9+9+9+9 -> 36 -> 3+6 -> 9 "iiii, 3, 9", // 9,9,9,9 -> 9+9+9+9 -> 36 -> 3+6 -> 9 "leetcode, 2, 6", // 12,5,5,20,3,15,4,5 -> 1+2+5+5+2+0+3+1+5+4+5 ➝ 33 -> 3+3 -> 6 "zbax, 2, 8", // 26,2,1,24 -> 2+6+2+1+2+4 ➝ 17 -> 1+7 -> 8 "abcdefghijklmnopqrstuvwxyz, 10, 9" ) fun `with k greater than 1, it's the sum of digits of the result of previous conversion`( englishLetters: String, k: Int, expectedSum: Int ) { assertThat(getLucky(englishLetters, k)).isEqualTo(expectedSum) } @ParameterizedTest @CsvSource( "A, 0", "1, 0", "!, 0", "' ', 0", "a a, 11", "a1a2b3, 112", ) fun `ignores all non-alphabet characters`(s: String, expectedSum: Int) { assertThat(getLucky(s)).isEqualTo(expectedSum) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
3,749
coding-challenges
MIT License
src/Day10.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
import java.util.LinkedList import kotlin.math.abs fun main() { fun checkCycle(cycle: Int) :Boolean { return cycle == 20 || cycle == 60 || cycle == 100 || cycle == 140 || cycle == 180 || cycle == 220 } fun part1(input: List<String>): Int { var cycle = 0 var x = 1 var sum = 0 input.forEach { cycle++ if(checkCycle(cycle)) { sum += cycle * x } if( it.startsWith("addx")) { cycle++ if(checkCycle(cycle)) { sum += cycle * x } x += it.split(" ")[1].toInt() } } return sum } fun printCycle(cycle: Int, x: Int) { if (abs((cycle % 40) - x) <= 1) { print("#") } else { print(".") } if ((cycle +1) % 40 == 0) { println() } } fun part2(input: List<String>): Int { var cycle = 0 var x = 1 input.forEach { printCycle(cycle, x) cycle++ if( it.startsWith("addx")) { printCycle(cycle, x) cycle++ x += it.split(" ")[1].toInt() } } return 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") println("Test") val part1 = part1(testInput) println(part1) val part2 = part2(testInput) println(part2) check(part1 == 13140) check(part2 == 1) println("Waarde") val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
1,693
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/eric/leetcode/FindTheShortestSuperstring.kt
wanglikun7342
163,727,208
false
{"Kotlin": 172132, "Java": 27019}
package com.eric.leetcode class FindTheShortestSuperstring { fun shortestSuperstring(A: Array<String>): String { val list = A.toMutableList() while (list.size > 1) { var x = 0 var y = 1 for (iv in list.withIndex()) { for (index in iv.index + 1..list.lastIndex) { if (getOverlapping(iv.value, list[index]) > getOverlapping(list[x], list[y])) { x = iv.index y = index } } } val a = list[x] val b = list[y] list.remove(a) list.remove(b) list.add(getOverlappingString(a, b)) } return list.single() } private fun getOverlapping(x: String, y: String): Int { return x.length + y.length - getOverlappingString(x, y).length } private fun getOverlappingString(str1: String, str2: String): String { var result = "" loop@ for (iv in str1.withIndex()) { if (iv.value != str2[0]) { continue } for (index in iv.index..str1.lastIndex) { if (str1[index] != str2[index - iv.index]) { continue@loop } } result = str1 + str2.substring(str1.length-iv.index..str2.lastIndex) break } loop@ for (iv in str2.withIndex()) { if (iv.value != str1[0]) { continue } for (index in iv.index..str2.lastIndex) { if (str2[index] != str1[index - iv.index]) { continue@loop } } val newResult = str2 + str1.substring(str2.length-iv.index..str1.lastIndex) if (newResult.length < result.length || result == "") { result = newResult } break } if (result == "") { result = str1 + str2 } return result } } fun main(args: Array<String>) { val inputArray = arrayOf("sssv","svq","dskss","sksss") val findTheShortestSuperstring = FindTheShortestSuperstring() println(findTheShortestSuperstring.shortestSuperstring(inputArray)) }
0
Kotlin
2
8
d7fb5ff5a0a64d9ce0a5ecaed34c0400e7c2c89c
2,286
Leetcode-Kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SingleThreadedCPU.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue /** * 1834. Single-Threaded CPU * @see <a href="https://leetcode.com/problems/single-threaded-cpu/">Source</a> */ fun interface SingleThreadedCPU { fun getOrder(tasks: Array<IntArray>): IntArray } class SingleThreadedCPUQueue : SingleThreadedCPU { override fun getOrder(tasks: Array<IntArray>): IntArray { val n: Int = tasks.size val ans = IntArray(n) val extTasks = Array(n) { IntArray(3) } for (i in 0 until n) { extTasks[i][0] = i extTasks[i][1] = tasks[i][0] extTasks[i][2] = tasks[i][1] } extTasks.sortWith { a, b -> a[1] - b[1] } val pq: PriorityQueue<IntArray> = PriorityQueue<IntArray> { a, b -> if (a[2] == b[2]) a[0] - b[0] else a[2] - b[2] } var time = 0 var ai = 0 var ti = 0 while (ai < n) { while (ti < n && extTasks[ti][1] <= time) { pq.offer(extTasks[ti++]) } if (pq.isEmpty()) { time = extTasks[ti][1] continue } val bestFit: IntArray = pq.poll() ans[ai++] = bestFit[0] time += bestFit[2] } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,905
kotlab
Apache License 2.0
src/year2023/day10/Day10.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day10 import check import readInput fun main() { val testInput1 = readInput("2023", "Day10_test_part1") val testInput2 = readInput("2023", "Day10_test_part2") check(part1(testInput1), 8) check(part2(testInput2), 8) val input = readInput("2023", "Day10") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = input.toPipeSystem().loop.size / 2 private fun part2(input: List<String>): Int { val pipeSystem = input.toPipeSystem() val pipeSystemWithSpacing = pipeSystem.withSpacing() val inside = pipeSystemWithSpacing.pipes.keys - pipeSystemWithSpacing.outsideLoop() - pipeSystemWithSpacing.loop - pipeSystemWithSpacing.spacing return inside.size } private data class Pos(val x: Int, val y: Int) { fun north() = Pos(x, y - 1) fun south() = Pos(x, y + 1) fun west() = Pos(x - 1, y) fun east() = Pos(x + 1, y) fun adjacent() = listOf(north(), south(), west(), east()) } private data class Pipe( val north: Boolean = false, val east: Boolean = false, val south: Boolean = false, val west: Boolean = false, ) { companion object { val vertical = Pipe(north = true, east = false, south = true, west = false) val horizontal = Pipe(north = false, east = true, south = false, west = true) val northEast = Pipe(north = true, east = true, south = false, west = false) val northWest = Pipe(north = true, east = false, south = false, west = true) val southWest = Pipe(north = false, east = false, south = true, west = true) val southEast = Pipe(north = false, east = true, south = true, west = false) val empty = Pipe(north = false, east = false, south = false, west = false) val start = Pipe(north = true, east = true, south = true, west = true) fun from(symbol: Char) = when (symbol) { '|' -> vertical '-' -> horizontal 'L' -> northEast 'J' -> northWest '7' -> southWest 'F' -> southEast '.' -> empty 'S' -> start else -> error("Symbol $symbol is not supported") } } } private open class PipeSystem(val pipes: Map<Pos, Pipe>, val loop: Set<Pos>) { val maxX = pipes.keys.maxOf { it.x } val maxY = pipes.keys.maxOf { it.y } override fun toString(): String { return (0..maxY).joinToString("\n") { y -> (0..maxX).joinToString("") { x -> when (val pipe = pipes.getValue(Pos(x, y))) { Pipe.empty -> " " Pipe.vertical -> "│" Pipe.horizontal -> "─" Pipe.northEast -> "└" Pipe.northWest -> "┘" Pipe.southWest -> "┐" Pipe.southEast -> "┌" else -> error("Unknown pipe: $pipe") } } } } } private class PipeSystemWithSpacing(pipes: Map<Pos, Pipe>, loop: Set<Pos>, val spacing: Set<Pos>) : PipeSystem(pipes, loop) private fun List<String>.toPipeSystem(): PipeSystem { val pipes = mutableMapOf<Pos, Pipe>() for ((y, line) in withIndex()) { for ((x, c) in line.withIndex()) { pipes += Pos(x, y) to Pipe.from(c) } } val startPos = pipes.entries.single { it.value == Pipe.start }.key val north = pipes[startPos.north()]?.south ?: false val south = pipes[startPos.south()]?.north ?: false val west = pipes[startPos.west()]?.east ?: false val east = pipes[startPos.east()]?.west ?: false pipes[startPos] = listOf( Pipe.vertical, Pipe.horizontal, Pipe.northEast, Pipe.northWest, Pipe.southWest, Pipe.southEast, ).single { it.north == north && it.south == south && it.west == west && it.east == east } fun Pos.next(): List<Pos> { val pipe = pipes.getValue(this) return listOfNotNull( north().takeIf { pipe.north }, south().takeIf { pipe.south }, west().takeIf { pipe.west }, east().takeIf { pipe.east }, ) } val loop = mutableSetOf(startPos) var next = startPos.next() while (next.isNotEmpty()) { loop += next next = next.flatMap { it.next() }.filter { it !in loop } } return PipeSystem(pipes, loop) } private fun PipeSystem.withSpacing(): PipeSystemWithSpacing { val spacedPipes = mutableMapOf<Pos, Pipe>() val spacedLoop = mutableSetOf<Pos>() val spacing = mutableSetOf<Pos>() for (x in 0 until 1 + maxX * 2) { for (y in 0 until 1 + maxY * 2) { val spacedPos = Pos(x, y) val oldPos = Pos(x / 2, y / 2).takeIf { x % 2 == 0 && y % 2 == 0 } val pipe = oldPos?.let { pipes.getValue(it) } ?: Pipe.empty spacedPipes += spacedPos to pipe if (oldPos == null) { spacing += spacedPos } if (oldPos in loop) { spacedLoop += spacedPos } } } for (spacePos in spacing) { val north = spacePos.north() in spacedLoop && spacedPipes.getValue(spacePos.north()).south val east = spacePos.east() in spacedLoop && spacedPipes.getValue(spacePos.east()).west val south = spacePos.south() in spacedLoop && spacedPipes.getValue(spacePos.south()).north val west = spacePos.west() in spacedLoop && spacedPipes.getValue(spacePos.west()).east val pipe = listOf( Pipe.vertical, Pipe.horizontal, Pipe.northEast, Pipe.northWest, Pipe.southWest, Pipe.southEast, ).firstOrNull { it.north == north && it.south == south && it.west == west && it.east == east } if (pipe != null) { spacedPipes += spacePos to pipe spacedLoop += spacePos } } return PipeSystemWithSpacing(spacedPipes, spacedLoop, spacing) } private fun PipeSystem.outsideLoop(): Set<Pos> { val outside = pipes.keys.filter { it.x == 0 || it.x == maxX || it.y == 0 || it.y == maxY }.filter { it !in loop } .toMutableSet() val stack = ArrayDeque<Pos>() stack += outside while (stack.isNotEmpty()) { val pos = stack.removeFirst() val adjacentOutside = pos.adjacent().filter { it in pipes && it !in loop && it !in outside } outside += adjacentOutside stack += adjacentOutside } return outside }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
6,531
AdventOfCode
Apache License 2.0
src/Day10.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
fun main() { fun part1(input: List<String>): Int { val cpu = Cpu() cpu.executeInstructions(input) return cpu.signalStrengthMap.values.sum() } fun part2(input: List<String>): String { val cpu = Cpu() cpu.executeInstructions(input) return cpu.getSprite() } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) println(part2(testInput)) val input = readInput("Day10") println(part1(input)) println(part2(input)) } private enum class OPERATION { NOOP, ADDX } private class Cpu { private var registerX = 1 private var cycle = 1 private var cycleToConsider = 20 private var drawPosition = 0 to 0 val signalStrengthMap = mutableMapOf<Int, Int>() private var sprite = StringBuilder() fun executeInstructions(instructions: List<String>) { instructions.forEach { val (op, value) = it.parseInput() executeCycle(op, value) } } fun getSprite(): String { return sprite.toString() } private fun executeCycle(operation: OPERATION, value: Int) { if (cycle == cycleToConsider) { calculateSignalStrength() cycleToConsider += 40 } drawSprite() cycle++ if (operation == OPERATION.ADDX) { executeCycle(OPERATION.NOOP, 0) registerX += value } } private fun calculateSignalStrength() { signalStrengthMap[cycle] = cycle * registerX } private fun drawSprite() { val spriteX = registerX - 1 .. registerX + 1 if (drawPosition.first in spriteX) { sprite.append('#') } else { sprite.append('.') } drawPosition = if (drawPosition.first == 39) { sprite.append('\n') drawPosition.copy( first = 0, second = (drawPosition.second + 1) % 5 ) } else { drawPosition.offsetBy(1 to 0) } } } private fun String.parseInput(): Pair<OPERATION, Int> { if (this == "noop") { return OPERATION.NOOP to 0 } val split = this.split(" ") return OPERATION.valueOf(split[0].uppercase()) to split[1].toInt() }
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
2,297
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kr/co/programmers/P92335.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import java.math.BigInteger // https://github.com/antop-dev/algorithm/issues/403 class P92335 { companion object { val TEEN: BigInteger = BigInteger("10") } fun solution(n: Int, k: Int): Int { var answer = 0 val kNumber = decimalToK(n, k) + "0" // n.toString(k) + "0" var num = BigInteger.ZERO for (ch in kNumber) { // 한 문자씩 탐색 val n = ch - '0' num = if (n == 0 && num != BigInteger.ZERO) { // 조건에 맞는 경우 if (isPrime(num)) { // 소수인지 판단 answer++ } BigInteger.ZERO // 수 초기화 } else { // 숫자를 완성해 나간다. // num = (num * 10) + n (num * TEEN) + BigInteger("$n") } } return answer } // 10진수를 k진수로 변환 private fun decimalToK(n: Int, k: Int): String { val sb = StringBuilder() var num = n while (num >= k) { sb.insert(0, num % k) num /= k } sb.insert(0, num) return sb.toString() } // 소수인지 판단 private fun isPrime(num: BigInteger): Boolean { if (num <= BigInteger.ONE) { return false } for (n in 2 until num.sqrt().toLong() + 1) { // 나눠지면 소수가 아니다 if (num.mod(BigInteger("$n")) == BigInteger.ZERO) { return false } } return true } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,582
algorithm
MIT License
src/main/kotlin/com/ginsberg/advent2018/Day17.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 17 - Reservoir Research * * Problem Description: http://adventofcode.com/2018/day/17 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day17/ */ package com.ginsberg.advent2018 class Day17(rawInput: List<String>) { private val parsedData = createMap(rawInput) private val grid: Array<CharArray> = parsedData.first private val minY: Int = parsedData.second private val fountain: Point = Point(500, 0) fun solvePart1(): Int { flow(fountain) return grid.filterIndexed { idx, _ -> idx >= minY }.sumBy { row -> row.filter { it in flowOrStill }.count() } } fun solvePart2(): Int { flow(fountain) return grid.filterIndexed { idx, _ -> idx >= minY }.sumBy { row -> row.filter { it == '~' }.count() } } private fun flow(source: Point) { if (source.down !in grid) { return } if (grid[source.down] == '.') { grid[source.down] = '|' flow(source.down) } if (grid[source.down] in wallOrStill && source.right in grid && grid[source.right] == '.') { grid[source.right] = '|' flow(source.right) } if (grid[source.down] in wallOrStill && source.left in grid && grid[source.left] == '.') { grid[source.left] = '|' flow(source.left) } if (hasWalls(source)) { fillLeftAndRight(source) } } private fun hasWalls(source: Point): Boolean = hasWall(source, Point::right) && hasWall(source, Point::left) private fun hasWall(source: Point, nextPoint: (Point) -> Point): Boolean { var point = source while (point in grid) { when (grid[point]) { '#' -> return true '.' -> return false else -> point = nextPoint(point) } } return false } private fun fillLeftAndRight(source: Point) { fillUntilWall(source, Point::right) fillUntilWall(source, Point::left) } private fun fillUntilWall(source: Point, nextPoint: (Point) -> Point) { var point = source while (grid[point] != '#') { grid[point] = '~' point = nextPoint(point) } } private fun createMap(input: List<String>): Pair<Array<CharArray>, Int> { val spots = claySpotsFromInput(input) val minY = spots.minBy { it.y }!!.y val maxX = spots.maxBy { it.x }!!.x val maxY = spots.maxBy { it.y }!!.y // Generate based off of maximum sizes val grid: Array<CharArray> = (0..maxY).map { // Account for zero indexing and flowing off the right side of the map! CharArray(maxX + 2).apply { fill('.') } }.toTypedArray() // Add all clay spots to the grid spots.forEach { spot -> grid[spot] = '#' } // Add the fountain grid[0][500] = '+' return Pair(grid, minY) } private fun claySpotsFromInput(input: List<String>): List<Point> = input.flatMap { row -> val digits = row.toIntArray() if (row.startsWith("y")) { (digits[1]..digits[2]).map { Point(it, digits[0]) } } else { (digits[1]..digits[2]).map { Point(digits[0], it) } } } companion object { private val nonDigits = """[xy=,]""".toRegex() private val wallOrStill = setOf('#', '~') private val flowOrStill = setOf('|', '~') private fun String.toIntArray(): IntArray = this.replace(nonDigits, "").replace("..", " ").split(" ").map { it.toInt() }.toIntArray() } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
3,837
advent-2018-kotlin
MIT License
src/Day04.kt
khongi
572,983,386
false
{"Kotlin": 24901}
fun main() { fun String.getRange(): IntRange { val (start, end) = split('-').map { it.toInt() } return start..end } fun part1(input: List<String>): Int { return input.count { line -> val (first, second) = line.split(',').map { it.getRange() } val intersect = first.intersect(second) intersect.size == first.count() || intersect.size == second.count() } } fun part2(input: List<String>): Int { return input.count { line -> val (first, second) = line.split(',').map { it.getRange() } val intersect = first.intersect(second) intersect.isNotEmpty() } } 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
9cc11bac157959f7934b031a941566d0daccdfbf
896
adventofcode2022
Apache License 2.0
src/Day11.kt
Narmo
573,031,777
false
{"Kotlin": 34749}
import java.math.BigInteger fun main() { class Monkey { val items = ArrayDeque<Long>() var operation: (Long, Long) -> Long = { item, _ -> item } var targetTrue: Int = -1 var targetFalse: Int = -1 var inspections = BigInteger.valueOf(0) var divider = 1L override fun toString(): String = "Monkey(items=$items, inspections=$inspections)\n" } // ended up with help of this solution: https://chasingdings.com/2022/12/11/advent-of-code-day-11-monkey-in-the-middle/ fun fillMonkeys(input: List<String>, shouldDecreaseWorryLevel: Boolean): List<Monkey> { return input.chunked(7) { data -> val monkey = Monkey() monkey.divider = data[3].split(" ").last().trim().toLong() val items = data[1].split(":").last().trim().split(",").map { it.trim().toLong() } monkey.items.addAll(items.map { it }) val operation = data[2].split("=").last().trim().split(" ") val op = operation[1] val firstOperand = if (operation[0] == "old") null else (operation[0].toLong()) val secondOperand = if (operation[2] == "old") null else (operation[2].toLong()) monkey.operation = when (op) { "+" -> { item, lcm -> if (shouldDecreaseWorryLevel) { ((firstOperand ?: item) + (secondOperand ?: item)) / 3 } else { ((firstOperand ?: item) + (secondOperand ?: item)) % lcm } } "*" -> { item, lcm -> if (shouldDecreaseWorryLevel) { ((firstOperand ?: item) * (secondOperand ?: item)) / 3 } else { ((firstOperand ?: item) * (secondOperand ?: item)) % lcm } } else -> { throw IllegalArgumentException("Unknown operation: $op") } } monkey.targetTrue = data[4].split(" ").last().trim().toInt() monkey.targetFalse = data[5].split(" ").last().trim().toInt() monkey } } fun simulateMonkeys(input: List<String>, shouldDecreaseWorryLevel: Boolean, rounds: Int): Long { val monkeys = fillMonkeys(input, shouldDecreaseWorryLevel) val lcm = monkeys.fold(1L) { acc, monkey -> println("Divider: ${monkey.divider}") acc * monkey.divider } println("LCM: $lcm") println("Initial monkeys: $monkeys") repeat(rounds) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { var item = monkey.items.removeFirst() monkey.inspections += BigInteger.ONE item = monkey.operation(item, lcm) if (item % monkey.divider == 0L) { monkeys[monkey.targetTrue].items.addLast(item) } else { monkeys[monkey.targetFalse].items.addLast(item) } } } } println(monkeys) return monkeys.sortedByDescending { it.inspections }.take(2).fold(BigInteger.ONE) { acc, monkey -> acc * monkey.inspections }.toLong() } fun part1(input: List<String>): Long = simulateMonkeys(input, shouldDecreaseWorryLevel = true, rounds = 20) fun part2(input: List<String>): Long = simulateMonkeys(input, shouldDecreaseWorryLevel = false, rounds = 10_000) val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
335641aa0a964692c31b15a0bedeb1cc5b2318e0
3,118
advent-of-code-2022
Apache License 2.0
aoc2022/day5.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval import java.util.ArrayDeque fun main() { Day5.execute() } object Day5 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: Pair<List<ArrayDeque<Char>>, List<Move>>): String { val (initialStatus, moves) = input val currentStatus = initialStatus.map { it.clone() } // Create a copy of the queues, so we don't modify the original input moves.forEach { move -> repeat(move.number) { currentStatus[move.targetPos - 1].push(currentStatus[move.startPos - 1].pop()) } } return currentStatus.getTopElements() } private fun part2(input: Pair<List<ArrayDeque<Char>>, List<Move>>): String { val (currentStatus, moves) = input moves.forEach { move -> val tmpList = mutableListOf<Char>() repeat(move.number) { tmpList.add(currentStatus[move.startPos - 1].pop()) } repeat(move.number) { currentStatus[move.targetPos - 1].push(tmpList.removeLast()) } } return currentStatus.getTopElements() } private fun readInput(): Pair<List<ArrayDeque<Char>>, List<Move>> { val (initialStatus, moves) = InputRetrieval.getFile(2022, 5).readText().dropLast(1).split("\n\n") val boardState = MutableList(initialStatus.trim().last().digitToInt()) { ArrayDeque<Char>() } initialStatus.lines().dropLast(1).reversed().forEach { it.chunked(4).forEachIndexed { index, value -> if (value.isNotBlank()) { boardState[index].push(value.removePrefix("[").first()) } } } val parsedMoves = moves.lines().map { Move(it.removePrefix("move ").split(" from ", " to ")) } return boardState to parsedMoves } private fun List<ArrayDeque<Char>>.getTopElements(): String = this.map { it.first }.joinToString("") data class Move( val number: Int, val startPos: Int, val targetPos: Int, ) { constructor(input: List<String>) : this(input.first().toInt(), input[1].toInt(), input.last().toInt()) } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,214
Advent-Of-Code
MIT License
src/Day01.kt
Reivax47
572,984,467
false
{"Kotlin": 32685}
fun main() { fun part1(input: List<String>): Int { var max_somme = 0 var somme = 0 input.forEach { if (it != "") { somme += it.toInt() } else { max_somme = if (somme > max_somme) somme else max_somme somme = 0 } } return max_somme } fun part2(input: List<String>): Int { val tableau = mutableListOf<Int>() var somme = 0 input.forEach { if (it != "") { somme += it.toInt() } else { tableau.add(somme) somme = 0 } } tableau.add(somme) tableau.sortDescending() return tableau.subList(0, 3).fold(0) { somme, element -> somme + element } } // 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
0affd02997046d72f15d493a148f99f58f3b2fb9
1,103
AD2022-01
Apache License 2.0
src/main/kotlin/days/Day3.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days class Day3 : Day(3) { override fun partOne(): Any { return inputList.map { Day3Util.splitString(it) } .map { Day3Util.overlappingChars(it.first, it.second) } .sumOf { chars -> chars.sumOf { Day3Util.letterToScore(it) } } } override fun partTwo(): Any { return inputList.windowed(3, 3, false) .sumOf { groupList -> check(groupList.size == 3) { "Size should be 3! But was ${groupList.size}" } val overlap = groupList.map { it.toSet() }.reduce { l, r -> l.intersect(r) } check(overlap.size == 1) { "Expected only 1 char in common but got ${overlap.size}" } Day3Util.letterToScore(overlap.iterator().next()) } } } object Day3Util { fun splitString(s: String): Pair<String, String> { val subStringLength = s.length / 2 check(subStringLength * 2 == s.length) { "Expected even length for $s, but was ${s.length}" } return s.substring(0, subStringLength) to s.substring(subStringLength) } fun letterToScore(s: Char): Int { // ascii magic... return if (s.isLowerCase()) { s - 'a' + 1 } else { s - 'A' + 27 } } fun overlappingChars(first: String, second: String): List<Char> { return first.toSet().intersect(second.toSet()).toList() } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
1,402
aoc2022
Creative Commons Zero v1.0 Universal
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_14_Longest_Common_Prefix.kt
v43d3rm4k4r
515,553,024
false
{"Kotlin": 40113, "Java": 25728}
package leetcode.solutions.concrete.kotlin import leetcode.solutions.* import leetcode.solutions.ProblemDifficulty.* import leetcode.solutions.validation.SolutionValidator.* import leetcode.solutions.annotations.ProblemInputData import leetcode.solutions.annotations.ProblemSolution /** * __Problem:__ Write a function to find the longest common prefix string amongst an array of strings. * If there is no common prefix, return an empty string `""`. * * __Constraints:__ * - `1 <= strs.length <= 200` * - `0 <= strs[i].length <= 200` * - `strs[i]` consists of only lowercase English letters. * __Solution :__ * Using two loops, the outer one will be responsible for the total character index, which is checked for strings. * The inner one will be for passing through the lines themselves. We compare characters until we reach the end of * the smallest string, or until we stumble upon a mismatch between the corresponding characters of the strings. * * __Time:__ O(N*M) * * __Space:__ O(1) * * @author <NAME> */ class Solution_14_Longest_Common_Prefix : LeetcodeSolution(EASY) { @ProblemSolution(timeComplexity = "O(N*M)", spaceComplexity = "O(1)") private fun longestCommonPrefix(strs: Array<String>): String { val output = StringBuilder() var currentCharIndex = 0 var currentChar: Char var isLastChar = false var isWrongChar = false while (!isLastChar && !isWrongChar) { currentChar = if (strs[0].isNotEmpty()) strs[0][currentCharIndex] else break strs.forEach { str -> if (str.isEmpty()) { isWrongChar = true return@forEach } if (str[currentCharIndex] != currentChar) { isWrongChar = true return@forEach } currentChar = str[currentCharIndex] if (currentCharIndex == str.length - 1) isLastChar = true } if (!isWrongChar) output.append(currentChar) ++currentCharIndex } return output.toString() } @ProblemInputData override fun run() { ASSERT_EQ("fl", longestCommonPrefix(arrayOf("flower", "flow", "flight"))) ASSERT_EQ("", longestCommonPrefix(arrayOf("dog", "racecar", "car"))) ASSERT_EQ("flower", longestCommonPrefix(arrayOf("flower","flower","flower","flower"))) ASSERT_EQ("c", longestCommonPrefix(arrayOf("cir","car"))) ASSERT_EQ("", longestCommonPrefix(arrayOf("abab","aba",""))) } }
0
Kotlin
0
1
c5a7e389c943c85a90594315ff99e4aef87bff65
2,626
LeetcodeSolutions
Apache License 2.0
codes/src/test/kotlin/katas/nakulgupta18/consecutive_strings.kt
cheroliv
522,283,474
false
{"Kotlin": 82456, "CSS": 52294, "TypeScript": 22466, "FreeMarker": 21485, "JavaScript": 12573, "Astro": 7822, "Groovy": 7785, "Java": 5477, "HTML": 5302, "Python": 3261, "SCSS": 1101, "Gherkin": 919, "Shell": 240}
package katas.nakulgupta18 import katas.nakulgupta18.LongestConsecLog.log import org.slf4j.LoggerFactory.getLogger import kotlin.test.Test import kotlin.test.assertEquals /** * consecutive_strings * @see <a href="https://www.codewars.com/kata/56a5d994ac971f1ac500003e/train/kotlin">nakulgupta18</a> * * * * * You are given an array(list) str_arr of strings and an integer k. * Your task is to return the first longest string, * consisting of k consecutive strings taken in the array. * Example: * * longest_consec(["zone", "abigail", "theta", "form", "libe", * "zas", "theta", "abigail"], 2) --> "abigailtheta" * * n being the length of the string array, if n = 0 or k > n or k <= 0 return "". * Note * * consecutive strings : follow one after another without an interruption * */ data class Consec(val firstPos: Int, val motif: String) fun longestConsec(strings: Array<String>, k: Int): String { @Suppress("UNUSED_VARIABLE") val length = strings.size var result = "" val lengthAtIndex = strings.map { it.length } val posByKConsec = mutableListOf<Int>() val firstPosByKConsec = mutableListOf<Int>() strings.forEachIndexed { idx, it -> var wc = 0 strings.forEach { item -> if (it == item) wc++ } if (wc == k) posByKConsec.add(idx) } //posByKConsec: [1, 2, 3, 4, 8, 9] posByKConsec.forEachIndexed { i: Int, kPos: Int -> if (i == 0) firstPosByKConsec.add(kPos) // else //si le motif exist deja on ne prend pas } // var maxLength_ = 0 // posByK.forEachIndexed { idx, it -> // val l = it.length // when { // maxLength_ < l -> maxLength_ = l // } // } log.info("posByLength: $lengthAtIndex") log.info("posByKConsec: $posByKConsec") log.info("firstPosByKConsec: $firstPosByKConsec") // log.info("max length: $maxLength_") return result } //fun longestConsec(strings: Array<String>, k: Int): String { // val length = strings.size // var result = "" // return when { // k <= 0 || length == 0 || k > length -> result // else -> { // strings.map { item -> // mapOf(item to mapOf(item to strings.filter { itemToCount -> // itemToCount == item // }.size)) // }.toList().filter { // k == it.entries.iterator().next().value.entries.iterator().next().value // }.forEach { // if (!result.contains(it.iterator().next().key)) // result += it.iterator().next().key // } // // // val maVar = strings.map { item -> // mapOf(item to mapOf(strings.filter { itemToCount -> // itemToCount == item // }.size to item.length)) // } // log.info(maVar.toString()) // // // result // } // } //} class LongestConsecMainTest { companion object { private fun testing(actual: String, expected: String) { assertEquals(expected, actual) } } @Test fun preTest() { // val strings = arrayOf("zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail") val strings = arrayOf("zone", "abigai", "abigail", "abigai", "theta", "form", "libe", "zas", "theta", "abigail") log.info(longestConsec(strings, 2))//posByK: [1, 2, 3, 4, 8, 9] } // @Test fun test() { println("longestConsec Fixed Tests") testing(longestConsec(arrayOf("zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"), 2), "abigailtheta") testing(longestConsec(arrayOf("ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"), 1), "oocccffuucccjjjkkkjyyyeehh") } } object LongestConsecLog { @JvmStatic val log = getLogger(LongestConsecLog.javaClass) } //fun longestConsec_(strarr: Array<String>): String { // return max(strarr.map { item -> // mapOf(item to mapOf(item to strarr.filter { itemToCount -> // itemToCount == item // }.size)) // }.toList()) //} //fun max(stringsCounted: List<Map<String, Map<String, Int>>>): String { // val occRates = mutableListOf<Int>() // stringsCounted.forEach { // occRates.add(it.entries.iterator().next().value.entries.iterator().next().value) // } // return stringsCounted[occRates.indexOf(occRates.maxByOrNull { it }!!)].keys.iterator().next() //}
0
Kotlin
0
3
be4085eaee07284723a7fe2fab2cae58c253caf9
4,513
developer-pages
MIT License
src/Day21.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
suspend fun main() { val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") measureAndPrintResult { part1(input) } measureAndPrintResult { part2(input) } } private fun part1(input: List<String>): Long { val root = parseJob("root", input) return root.computed!! } private fun part2(input: List<String>): Long { val root = parseJob("root", input, checkForHuman = true) as Operation val computedA = root.childA.computed val computedB = root.childB.computed return when { computedA != null -> root.childB.computeInverse(computedA) computedB != null -> root.childA.computeInverse(computedB) else -> error("xd") } } private fun parseJob(name: String, input: List<String>, checkForHuman: Boolean = false): Job { val job = input.first { it.startsWith(name) }.substringAfter(": ") return when { job.first().isDigit() -> Constant(number = job.toLong().takeUnless { checkForHuman && name == "humn" }) else -> { val (jobAName, operand, jobBName) = job.split(" ") val jobA = parseJob(jobAName, input, checkForHuman) val jobB = parseJob(jobBName, input, checkForHuman) Operation(op = operand, childA = jobA, childB = jobB) } } } private sealed class Job { val computed: Long? by lazy { when (this) { is Constant -> number is Operation -> { val computedA = childA.computed ?: return@lazy null val computedB = childB.computed ?: return@lazy null when (op) { "+" -> computedA + computedB "-" -> computedA - computedB "*" -> computedA * computedB "/" -> computedA / computedB else -> error("xd") } } } } fun computeInverse(expected: Long): Long = when (this) { is Constant -> number ?: expected is Operation -> { val computedA = childA.computed val computedB = childB.computed val (unknown, other, isLeftUnknown) = when { computedA != null -> Triple(childB, computedA, false) computedB != null -> Triple(childA, computedB, true) else -> error("xd") } val newExpected = when (op) { "+" -> expected - other "-" -> if (isLeftUnknown) expected + other else other - expected "*" -> expected / other "/" -> if (isLeftUnknown) expected * other else other / expected else -> error("xd") } unknown.computeInverse(newExpected) } } } private data class Constant(val number: Long?) : Job() private data class Operation(val op: String, val childA: Job, val childB: Job) : Job()
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
2,986
aoc-22
Apache License 2.0
2015/Day10/src/main/kotlin/main.kt
mcrispim
658,165,735
false
null
import java.io.File data class Element(val name: String, val sequence: String, val nextSequence: String) { val size get() = sequence.length } fun readTable(name: String): Map<String, Element> { val input = File("src", name).readLines() // first line is header return buildMap<String, Element> { for (line in input.drop(1)) { val (_, element, sequence, nextSequence, _) = line.split("\t") set(element, Element(element, sequence, nextSequence)) } } } val elements = readTable("elements.txt") fun findElement(sequence: String): Element { for ((name, element) in elements) { if (element.sequence == sequence) { return element } } throw IllegalArgumentException("Unknown sequence $sequence") } fun onePass(seed: String): String { var seedElements = seed.split(".") val result = buildString { for (element in seedElements) { append(elements[element]?.nextSequence ?: throw IllegalArgumentException("Unknown element $element")) append(".") } } return result.dropLast(1) } fun nPasses(seed: String, times: Int): String { var result = seed repeat(times) { result = onePass(result) } return result } fun lengthOfSequence(sequence: String): Int { val sequenceElements = sequence.split(".") var result = 0 for (element in sequenceElements) { result += elements[element]?.size ?: throw IllegalArgumentException("Unknown element $element") } return result } fun main() { val mySeed = "1321131112" val seedElement = findElement(mySeed) val result = nPasses(seedElement.name, 40) println("Part 1 result: ${lengthOfSequence(result)}") val result2 = nPasses(result, 10) println("Part 2 result: ${lengthOfSequence(result2)}") }
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
1,857
AdventOfCode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/StringCompression2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 1531. String Compression II * @see <a href="https://leetcode.com/problems/string-compression-ii/">Source</a> */ fun interface StringCompression2 { operator fun invoke(s: String, k: Int): Int } class StringCompression2DP : StringCompression2 { override fun invoke(s: String, k: Int): Int { val n: Int = s.length val dp = initializeDP(n, k) for (i in 1..n) { for (m in 0..k) { updateDP(dp, s, i, m) } } return dp[n][k] } private fun initializeDP(n: Int, k: Int): Array<IntArray> { val dp = Array(n + 1) { IntArray(k + 1) { n } } dp[0][0] = 0 return dp } private fun updateDP(dp: Array<IntArray>, s: String, i: Int, m: Int) { if (m > 0) { dp[i][m] = min(dp[i][m], dp[i - 1][m - 1]) } // keep s[i], concat the same, remove the different var same = 0 var diff = 0 for (j in i downTo 1) { if (s[j - 1] == s[i - 1]) { same++ } else { diff++ } if (diff > m) break dp[i][m] = min(dp[i][m], dp[j - 1][m - diff] + getLen(same)) } } private fun getLen(count: Int): Int { return when { count == 1 -> 1 count < DECIMAL -> 2 count < LIMIT -> 3 else -> 4 } } companion object { private const val LIMIT = 100 private const val DECIMAL = 10 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,202
kotlab
Apache License 2.0
src/Day25.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
import java.lang.Math.pow private fun decimalToSnafu(dec: Long): String { val quinary = dec.toString(5) val snafuReversed = mutableListOf<Char>() var hasCarry = false for (c in quinary.reversed()) { val decValue = c.digitToInt(10) + if (hasCarry) 1 else 0 when (decValue) { 0 -> { hasCarry = false snafuReversed.add('0') } 1 -> { hasCarry = false snafuReversed.add('1') } 2 -> { hasCarry = false snafuReversed.add('2') } 3 -> { hasCarry = true snafuReversed.add('=') } 4 -> { hasCarry = true snafuReversed.add('-') } 5 -> { hasCarry = true snafuReversed.add('0') } else -> throw IllegalStateException("Not expecting $decValue") } } if (hasCarry) { snafuReversed.add('1') } return String(snafuReversed.reversed().toCharArray()) } private fun snafuCharToDecimal(char: Char): Long { return when (char) { '0' -> 0 '1' -> 1 '2' -> 2 '-' -> -1 '=' -> -2 else -> throw IllegalArgumentException("Unknown SNAFU char $char") } } private fun snafuToDecimal(snafu: String): Long { return snafu.mapIndexed { index, c -> val power = snafu.length - index - 1 pow(5.0, power.toDouble()).toLong() * snafuCharToDecimal(c) }.sum() } private fun part1(input: List<String>): String { val decimalSum = input.map { snafuToDecimal(it) }.sum() return decimalToSnafu(decimalSum) } private fun part2(input: List<String>): Int { return input.size } fun main() { val input = readInput("Day25") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
1,998
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day14.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2021 class Day14(private val input: List<String>) { private val cache = Array<MutableMap<String, Map<Char, Long>>>(41) { mutableMapOf() } private val rules = input.drop(2).associate { rule -> rule.substring(0, 2) to rule.last() } fun solvePart1(): Long = solve(10) fun solvePart2(): Long = solve(40) private fun solve(steps: Int): Long { val template = input.first().toMutableList() val count = template.windowed(2).fold(emptyMap<Char, Long>()) { count, chars -> val pair = chars.joinToString("") count(steps, pair).mergeReduce(count) { a, b -> a + b } } val min = count.minOf { it.value } val max = count.maxOf { it.value } return max - min } private fun count(step: Int, pair: String): Map<Char, Long> { val cachedResult = cache[step][pair] if (cachedResult != null) { return cachedResult } val rule = rules[pair] if (step == 0 || rule == null) { return pair.countChars() } val countA = count(step - 1, pair[0] + rule) val countB = count(step - 1, rule + pair[1]) val result = countA.mergeReduce(countB) { a, b -> a + b } result[rule] = result.getValue(rule) - 1 cache[step][pair] = result return result } private fun <K, V> Map<K, V>.mergeReduce(other: Map<K, V>, reduce: (V, V) -> V): MutableMap<K, V> { val result = this.toMutableMap() for (entry in other) { val existing = result[entry.key] if (existing == null) { result[entry.key] = entry.value } else { result[entry.key] = reduce(entry.value, existing) } } return result } private fun CharSequence.countChars(): Map<Char, Long> { val destination = mutableMapOf<Char, Long>() for (c in this) { val count = destination.getOrDefault(c, 0L) destination[c] = count + 1L } return destination } private operator fun Char.plus(c: Char) = this.toString() + c.toString() }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
2,195
advent-of-code
Apache License 2.0
day03/main.kts
LOZORD
441,007,912
false
{"Kotlin": 29367, "Python": 963}
import java.util.Scanner import java.util.Collections fun main1() { // ones collects the number of ones at each bit index for each input // binary number. var ones: IntArray? = null val input = Scanner(System.`in`) var total = 0 while (input.hasNextLine()) { val scanned = input.nextLine() total++ if (ones == null) { ones = IntArray(scanned.length) } for ((i, c) in scanned.withIndex()) { if (c == '1') { ones[i]++ } } // println("ones is %s; total is %d; input was %s".format( // ones.contentToString(), total, scanned)) } var mostCommon = 0 var leastCommon = 0 for ((i, count) in ones!!.withIndex()) { val pct = (100.0 * count) / total if (pct > 50.0) { mostCommon = mostCommon or (1 shl (ones.size - i - 1)) } else { leastCommon = leastCommon or (1 shl (ones.size - i - 1)) } // println("MOST: %s; LEAST: %s".format( // Integer.toBinaryString(mostCommon), Integer.toBinaryString(leastCommon))) } println("GAMMA (MOST): %d; EPSILON (LEAST): %d; MULTIPLIED: %d".format( mostCommon, leastCommon, mostCommon * leastCommon)) } fun main2() { val input = Scanner(System.`in`) val list = ArrayList<Int>() // Insight: the most common bits are the median number // when the list is sorted. // ^^ This is likely wrong, but we can do some clever binary searching if // the numbers are sorted since bits also appear sorted (all 0s before all // 1s in any given sorted collection of binary numbers). // NOTE: This algorithm (the binary search part) only works if the numbers // are all distinct/unique. var numBits = -1 while (input.hasNextLine()) { val line = input.nextLine() if (numBits < 0) { numBits = line.length } list.add(Integer.parseInt(line, 2)) } Collections.sort(list) // start: The start index of the sublist. // // end: Similar, for the end. // // searchAccumulation: The accumulated number that is part of the number // to which we binary search. It encodes (or its components are) the binary // digits of our search. I.e. the nth bit of searchAccumulation is 1 iff // 1 was the majority of the nth column (given the previously included // numbers). data class State(val start: Int, val end: Int, val searchAccumulation: Int) // stepIndex: which iteration of searching this stp is. // // searchIndex: the "actual index" of binary search (translating the // insertion point). Note that this searchIndex is over the entire list and // not just the sublist in "focus" (determined by start and end). // // oneIsMajority: True iff 1 is the majority bit for this stp. data class Step(val stepIndex: Int, val searchIndex: Int, val oneIsMajority: Boolean) fun doSearch(stpper: (Step, State) -> State): Int { var start = 0 var end = list.size - 1 var i = 0 var searchAccumulation = 0 while (start != end) { val size = end - start + 1 val shifted = 1 shl (numBits - i - 1) val search = searchAccumulation + shifted val index = list.binarySearch(search, start, end + 1) val actualIndex = if (index >= 0) { index } else { -(index+1) } val normalizedIndex = actualIndex - start val newState = stpper(Step( stepIndex = i, searchIndex = actualIndex, oneIsMajority = normalizedIndex <= size / 2, ), State( start, end, searchAccumulation, )) start = newState.start end = newState.end searchAccumulation = newState.searchAccumulation i++ } return list.get(start) } // var start = 0 // var end = list.size - 1 // var i = 0 // var searchAccumulation = 0 // while (start != end) { // val size = end - start + 1 // println("start $start; end $end; i $i; size $size; searchAccumulation $searchAccumulation") // val shifted = 1 shl (numBits - i - 1) // val search = searchAccumulation + shifted // val index = list.binarySearch(search, start, end + 1) // val actualIndex = // if (index >= 0) { // index // } else { // -(index+1) // } // val normalizedIndex = actualIndex - start // println("searched for $search; got actual index $actualIndex; NI $normalizedIndex") // if (normalizedIndex > size / 2) { // // 0 is the more common digit. // searchAccumulation += 0 // start = start // end = actualIndex - 1 // println("end is now $end; SA is $searchAccumulation") // } else { // // 1 is the more common digit (or tie). // searchAccumulation += shifted // start = actualIndex // end = end // println("start is now $start; SA is $searchAccumulation") // } // i++ // } // var start = 0 // var end = list.size - 1 // var i = 0 // while (i < numBits && start < end) { // println("start $start; end $end; examining list: %s".format(list.subList(start, end+1))) // var size = end - start + 1 // // Search the binary number 10...0 that is less that the number of // // bits in the list. // val search = 1 shl (numBits - i - 1) // println("binary searching for %s among %s".format(Integer.toBinaryString(search), list.subList(start,end+1).map(Integer::toBinaryString))) // val index = list.binarySearch(search, start, end) // val actualIndex: Int // if (index >= 0) { // actualIndex = index // } else { // actualIndex = -(index+1) // Insertion point. // } // println("index $index; actualIndex $actualIndex") // if (actualIndex > (size / 2)) { // // 0 in majority. // end = actualIndex - 1 // } else { // // 1 in majority (or tie). // start = actualIndex // } // i++ // } // val mostCommon = list.get(start) val mostCommon = doSearch({ stp, state -> if (stp.oneIsMajority) { state.copy( searchAccumulation = state.searchAccumulation + (1 shl numBits - stp.stepIndex - 1), start = stp.searchIndex, ) } else { state.copy( end = stp.searchIndex - 1, ) } }) val leastCommon = doSearch({ stp, state -> if (stp.oneIsMajority) { state.copy( end = stp.searchIndex - 1, ) } else { state.copy( searchAccumulation = state.searchAccumulation + (1 shl numBits - stp.stepIndex - 1), start = stp.searchIndex, ) } }) println("MOST COMMON: $mostCommon; LEAST COMMON: $leastCommon; MULTIPLIED: %d".format(mostCommon*leastCommon)) } main2()
0
Kotlin
0
0
17dd266787acd492d92b5ed0d178ac2840fe4d57
7,457
aoc2021
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1335/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1335 import kotlin.math.max import kotlin.math.min /** * LeetCode page: [1335. Minimum Difficulty of a Job Schedule](https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/); * * TODO : There is solution with time complexity O(Nd) [(see Ref)](https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/490316/); */ class Solution { /* Complexity: * Time O(N^2 * d) and Space O(N) where N is the size of jobDifficulty; */ fun minDifficulty(jobDifficulty: IntArray, d: Int): Int { val n = jobDifficulty.size if (n < d) { return -1 } // dp[i]@day ::= minDifficulty(jobDifficulty[i:], day) val dp = IntArray(n) // Base cases in which day = 1 dp[n - 1] = jobDifficulty[n - 1] for (index in n - 2 downTo 0) { dp[index] = max(dp[index + 1], jobDifficulty[index]) } // Update dp@day from dp@day-1 for (day in 2..d) { for (i in 0..n - day) { var subresult = Int.MAX_VALUE var firstDayCost = jobDifficulty[i] for (firstDayEnd in i..n - day) { firstDayCost = max(firstDayCost, jobDifficulty[firstDayEnd]) subresult = min(subresult, firstDayCost + dp[firstDayEnd + 1]) } dp[i] = subresult } } return dp[0] } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,466
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/jalgoarena/ranking/BasicRankingCalculator.kt
jalgoarena
128,505,026
false
{"Kotlin": 44176, "Shell": 236, "Dockerfile": 233}
package com.jalgoarena.ranking import com.jalgoarena.domain.* import com.jalgoarena.submissions.SubmissionsFilter import org.slf4j.LoggerFactory class BasicRankingCalculator( private val scoreCalculator: ScoreCalculator ) : RankingCalculator { private val logger = LoggerFactory.getLogger(this.javaClass) override fun ranking( users: List<User>, allSubmissions: List<Submission>, problems: List<Problem> ): List<RankEntry> { logger.info( "Calculating ranking for {} users, {} submissions, {} problems", users.size, allSubmissions.size, problems.size ) val stats = SubmissionsFilter.stats(allSubmissions) logger.info("Stats: {}", stats) val submissions = SubmissionsFilter.acceptedWithBestTimes(allSubmissions) logger.info("Number of submissions accepted with with best times: {}", submissions.size) return users.map { user -> val userSubmissionsCount = stats.count[user.id].orEmpty() val userSubmissions = submissions .filter { it.userId == user.id } .sortedBy { it.elapsedTime } .distinctBy { it.problemId } val solvedProblems = userSubmissions.map { it.problemId } RankEntry( user.username, score(userSubmissions, problems, userSubmissionsCount), solvedProblems, user.region, user.team ) }.sortedWith(compareByDescending(RankEntry::score).thenByDescending { it.solvedProblems.size }) } override fun problemRanking( users: List<User>, problemSubmissions: List<Submission>, problems: List<Problem>, problemId: String ): List<ProblemRankEntry> { val stats = SubmissionsFilter.stats(problemSubmissions) val submissions = SubmissionsFilter.acceptedWithBestTimes(problemSubmissions) return submissions.map { submission -> val user = users.first { it.id == submission.userId } val userSubmissionsCount = stats.count[user.id]!! ProblemRankEntry( user.username, score(listOf(submission), problems, userSubmissionsCount), submission.elapsedTime ) }.sortedBy { it.elapsedTime }.distinctBy { it.hacker } } private fun score(userSubmissions: List<Submission>, problems: List<Problem>, userSubmissionsCount: Map<String, Int>): Double { return userSubmissions.sumByDouble { userSubmission -> val problem = problems.first { it.id == userSubmission.problemId } val problemSubmissionsCount = userSubmissionsCount[problem.id] scoreCalculator.calculate( userSubmission, problem, problemSubmissionsCount ?: 1 ) } } }
3
Kotlin
1
1
d34e72ab09804b0b2470387e87a435e93110686f
2,923
JAlgoArena-Ranking
Apache License 2.0
src/Day01.kt
anisch
573,147,806
false
{"Kotlin": 38951}
fun main() { fun part1(input: List<String>): Int { return input .joinToString(";") { it } .split(";;") .maxOf { elf -> elf .split(";") .sumOf { it.toInt() } } } fun part2(input: List<String>): Int { return input .joinToString(";") { it } .split(";;") .map { elf -> elf .split(";") .sumOf { it.toInt() } } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") val input = readInput("Day01") check(part1(testInput) == 24000) println(part1(input)) check(part2(testInput) == 45000) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
903
Advent-of-Code-2022
Apache License 2.0
src/Day03.kt
HenryCadogan
574,509,648
false
{"Kotlin": 12228}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { backpack -> val midPoint = backpack.length / 2 val firstHalf = backpack.substring(0 until midPoint) val secondHalf = backpack.substring(midPoint until backpack.length) val item = firstHalf.toSet().intersect(secondHalf.toSet()) item.single().toPriority() } } fun part2(input: List<String>): Int { return input.chunked(3) .sumOf { backpacks -> backpacks .map { it.toSet() } .reduce(Set<Char>::intersect) .single() .toPriority() } } val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun Char.toPriority(): Int { return if (isUpperCase()) { code - 38 } else { code - 96 } }
0
Kotlin
0
0
0a0999007cf16c11355fcf32fc8bc1c66828bbd8
943
AOC2022
Apache License 2.0
src/jvmMain/kotlin/day11/initial/Day11.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day11.initial import day11.initial.Image.Galaxy import day11.initial.Image.Space import util.add import java.io.File fun main() { solvePart1() // Solution: 9565386, time 13:50 } fun solvePart1() { // val input = File("src/jvmMain/kotlin/day11/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day11/input/input.txt") val grid = Gridd(input.readLines()) println("Initial grid:") println(grid.toPrintableString(includeLocation = false)) println(grid.toPrintableString(includeLocation = true)) println() println("Expanded grid:") val expandedGrid = grid.expandSpace() println(expandedGrid.toPrintableString(includeLocation = false)) println(expandedGrid.toPrintableString(includeLocation = true)) println() val pairList = expandedGrid.getPairList() println("Pair list. Size: ${pairList.size}. Content:") println(pairList.joinToString("\n")/* { (first, second) -> "$first, $second, distance: ${first.taxicabDistance(second)}" }*/) println() val distanceSum = pairList.sumOf { it.distance } println("Distance sum: $distanceSum") } data class GalaxyPair( val first: Location<Image>, val second: Location<Image>, val distance: Int ) fun GalaxyPair(pair: Pair<Location<Image>, Location<Image>>): GalaxyPair = GalaxyPair( first = pair.first, second = pair.second, distance = pair.first.taxicabDistance(pair.second) ) // FIXME Very inefficient fun Grid<Image>.getPairList(): List<GalaxyPair> { val galaxyList = this.rowList.flatten().filter { it.value is Galaxy } return galaxyList.foldIndexed(emptyList<Pair<Location<Image>, Location<Image>>>()) { index, acc, firstGalaxy -> println("Handling pair index: $index, of ${galaxyList.size}") acc + galaxyList.flatMap { secondGalaxy -> if (firstGalaxy == secondGalaxy || acc.contains(firstGalaxy to secondGalaxy) || acc.contains(secondGalaxy to firstGalaxy)) { listOf(null) } else { listOf(firstGalaxy to secondGalaxy) } }.filterNotNull() }.map(::GalaxyPair) } fun Grid<Image>.expandSpace(): Grid<Image> { val expandedRowGrid = rowList.fold(listOf(emptyList<Location<Image>>()) to 0) { (acc, additional), row -> val newRow = row.map { it.copy(row = it.row + additional) } if (newRow.all { it.value == Space }) { val updatedNewRow = row.map { it.copy(row = it.row + additional + 1) } acc.add(newRow).add(updatedNewRow) to additional + 1 } else { acc.add(newRow) to additional } }.first.flatten().let(::Grid) val expandedColumnGrid = expandedRowGrid.columnList.fold(listOf(emptyList<Location<Image>>()) to 0) { (acc, additional), column -> val newColumn = column.map { it.copy(column = it.column + additional) } if (newColumn.all { it.value == Space }) { val newUpdatedColumn = column.map { it.copy(column = it.column + additional + 1) } acc.add(newColumn).add(newUpdatedColumn) to additional + 1 } else { acc.add(newColumn) to additional } }.first.flatten().let(::Grid) return expandedColumnGrid } // ----------- Parsing sealed interface Image { data class Galaxy(val char: Char) : Image { override fun toString(): String = char.toString() } object Space : Image { override fun toString(): String = "." } } fun Gridd(lines: List<String>): Grid<Image> { val list = lines.flatMapIndexed { row, line -> line.mapIndexed { column, char -> Location(value = Image(char), row = row, column = column) } } return Grid(list) } fun Image(char: Char): Image = when (char) { '#' -> Galaxy(char) '.' -> Space else -> error("Invalid image char: $char") } fun <T> Location<T>.toPrintableString(): String = value.toString()
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
4,004
advent-of-code
MIT License
src/algorithmdesignmanualbook/sorting/FindTransitionIndex.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.sorting import algorithmdesignmanualbook.print import kotlin.math.pow import kotlin.test.assertTrue /** * [otherValue] is the value that is NOT to be searched i.e. index of value other than the [otherValue] is searched. */ private fun getLeftMostOccurrence(otherValue: String, array: Array<String>, low: Int, high: Int): Int { if (low <= high) { val mid = (low + high) / 2 if ((mid == 0 || array[mid - 1] == otherValue) && array[mid] != otherValue) { return mid } else if (array[mid] == otherValue) { return getLeftMostOccurrence(otherValue, array, mid + 1, high) } else { return getLeftMostOccurrence(otherValue, array, low, mid) } } return -1 } /** * Given unbounded 0s followed by unbounded number of 1s, find the first index of transition. * * Done using ONE-SIDED BINARY SEARCH * * Solution: * * Incremental search 1,2,4,6,8... and then binary search on transition range */ private fun findTransitionIndex(startIndex: Int, input: Array<String>): Int? { var growth = 0 var currentIndex = startIndex + 2.toDouble().pow(growth).toInt() val firstElement = input[0] while (currentIndex <= input.lastIndex) { if (input[currentIndex] == firstElement) { growth++ val nextIndex = 2.toDouble().pow(growth).toInt() if (nextIndex < input.lastIndex) { currentIndex = nextIndex } else { currentIndex++ } } else { // binary search since there is a transition after `startIndex` return startIndex + getLeftMostOccurrence(firstElement, input, startIndex, input.lastIndex) } } return null } fun main() { run { val input1 = "00000000000000000001111111111111111111".formatInput() assertTrue { findTransitionIndex(0, input = input1).print() == input1.indexOf("1") } } run { val input2 = "0000000000000000000".formatInput() assertTrue { findTransitionIndex(0, input = input2) == null } } run { val input3 = "0000000000000000001".formatInput() assertTrue { findTransitionIndex(0, input = input3) == input3.indexOf("1") } } run { val input4 = "01111".formatInput() assertTrue { findTransitionIndex(0, input = input4) == input4.indexOf("1") } } } private fun String.formatInput() = split("").filter(String::isNotEmpty).toTypedArray()
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,511
algorithms
MIT License
src/main/kotlin/nl/meine/aoc/_2023/Day2.kt
mtoonen
158,697,380
false
{"Kotlin": 201978, "Java": 138385}
package nl.meine.aoc._2023 import java.util.HashMap class Day2 { fun one(input: String): Int { val lines = input.split("\n") var counter = 0 val maxColor = HashMap<String, Int>(); maxColor["red"] = 12 maxColor["green"] = 13 maxColor["blue"] = 14 val a = lines.map { checkGame(it, maxColor) } .sum() return a; } fun checkGame(line: String, maxColors: HashMap<String, Int>): Int { val game = line.substringBefore(":").substringAfter(" ") val a=line.substringAfter(": ") .split("; ") .map { it.split(", ") } .map { b -> processSet(b,maxColors) } .all{it} return if (a) game.toInt() else 0 } fun processSet(cubes: List<String>, maxColors: HashMap<String, Int>): Boolean { for(set in cubes){ val items = set.split(" "); val number :Int = items[0].toInt() val color : String = items[1] val maxColor=maxColors[color] if(maxColor!! < number){ return false } } return true } fun two(input: String): Int { val lines = input.split("\n") var counter = 0 val a = lines.map { checkGame(it) } .sum() return a; } fun checkGame(line: String): Int { val game = line.substringBefore(":").substringAfter(" ") val cubes=line.substringAfter(": ") .split("; ") .flatMap { it.split(", ") } .map { b -> val entry = b.split(" ") Pair(entry[1], entry[0]) } .map{c->c} .groupBy ({it.first} , {it.second.toInt()}) var counter = 1; for(set in cubes){ counter *=set.value.max() } return counter } } fun main() { val ins = Day2(); println(ins.two(input)) } val input = """Game 1: 1 red, 10 blue, 5 green; 11 blue, 6 green; 6 green; 1 green, 1 red, 12 blue; 3 blue; 3 blue, 4 green, 1 red Game 2: 3 red, 5 green; 5 green, 7 red; 1 blue, 7 red, 3 green; 3 red, 2 blue; 5 green, 4 red Game 3: 4 blue, 4 green; 2 green, 2 blue; 8 green, 2 red, 3 blue Game 4: 3 blue, 15 green; 16 green; 2 red, 7 green; 2 blue, 14 green Game 5: 8 green, 6 red, 16 blue; 8 red, 12 green; 1 red, 9 green, 16 blue; 8 red, 3 green; 2 blue, 5 red, 10 green; 15 red, 4 blue, 8 green Game 6: 5 blue, 2 green; 6 red, 3 green; 4 green, 4 blue, 2 red; 14 blue, 2 red Game 7: 2 green, 6 blue, 1 red; 2 blue, 1 red; 8 blue; 5 blue, 1 green; 6 blue, 1 red; 2 blue Game 8: 1 red, 10 blue, 1 green; 6 blue, 1 red; 3 blue, 2 green; 1 red, 1 blue, 3 green; 13 blue; 10 blue, 3 green, 3 red Game 9: 2 blue; 8 green, 3 blue; 4 green; 14 green, 1 red, 2 blue; 3 blue, 1 red, 12 green Game 10: 1 blue, 7 green; 1 red, 3 green, 5 blue; 1 blue, 5 green, 1 red; 13 green, 5 blue, 2 red Game 11: 1 green, 10 red, 6 blue; 15 red, 12 blue; 18 red, 1 green, 1 blue Game 12: 16 red, 8 blue, 1 green; 15 red, 3 blue, 1 green; 5 red Game 13: 6 red, 7 blue, 7 green; 3 blue, 4 red, 13 green; 1 blue, 6 red, 11 green; 2 red, 1 blue, 14 green; 8 green, 5 blue, 2 red; 4 blue, 18 green, 4 red Game 14: 16 red, 3 blue, 1 green; 7 green, 3 red; 16 red, 15 green, 3 blue; 3 blue, 13 red, 10 green Game 15: 1 blue, 1 red; 3 blue, 2 green; 1 red; 2 red, 2 green, 3 blue; 3 blue, 1 red, 3 green Game 16: 9 red, 3 blue; 13 red, 9 blue; 9 blue, 10 red; 5 red, 10 blue, 1 green; 2 red, 6 green, 8 blue; 6 green, 13 red, 5 blue Game 17: 15 red, 17 green, 8 blue; 18 red, 16 blue, 15 green; 8 blue, 17 green, 10 red; 5 green, 3 red, 12 blue Game 18: 2 blue, 11 red, 2 green; 1 green, 11 red, 11 blue; 1 red, 4 blue; 10 blue, 9 red; 1 blue, 7 red Game 19: 2 blue, 3 green, 5 red; 8 blue, 16 green; 12 red, 7 blue, 8 green; 9 green, 1 blue; 3 red, 16 green, 10 blue Game 20: 3 blue, 5 green, 6 red; 2 red, 8 blue, 7 green; 7 green, 3 blue; 2 red, 11 blue; 1 green, 6 red, 3 blue Game 21: 16 red, 3 blue, 8 green; 10 red, 15 blue, 3 green; 6 green, 13 red, 15 blue; 11 green, 13 blue, 10 red Game 22: 8 green, 1 blue; 2 blue, 9 green, 3 red; 2 red, 2 blue; 1 red, 3 blue, 8 green; 2 blue, 1 green; 1 green, 2 blue Game 23: 2 blue, 8 red, 5 green; 9 green, 2 blue; 10 red, 2 green; 12 red, 1 blue; 11 green, 2 blue, 13 red; 7 green Game 24: 6 red; 13 green, 7 red, 10 blue; 7 green, 9 red, 1 blue; 3 blue, 2 green, 2 red Game 25: 7 green, 1 red, 2 blue; 8 green, 2 blue, 5 red; 5 blue, 8 green, 4 red; 5 blue, 2 green, 1 red; 5 green, 3 red, 7 blue; 3 blue, 6 green, 1 red Game 26: 6 green, 3 red; 1 blue, 2 green, 2 red; 2 green, 2 red, 3 blue; 4 blue, 8 red, 2 green; 1 red, 1 green, 1 blue; 6 red, 5 blue Game 27: 4 green, 13 blue, 2 red; 2 red, 7 green, 10 blue; 14 blue, 11 green, 1 red; 10 blue, 15 green Game 28: 4 green, 13 red, 7 blue; 2 red, 5 blue; 5 blue, 4 green Game 29: 6 green, 15 red; 1 blue, 6 red, 8 green; 6 green, 1 blue; 12 red; 1 green, 7 red, 1 blue Game 30: 4 blue, 4 green, 2 red; 6 blue, 9 red, 20 green; 9 blue, 4 red, 2 green; 8 red, 8 blue, 1 green; 6 green, 12 blue, 2 red; 8 green, 8 red Game 31: 9 blue; 1 red, 2 blue, 5 green; 2 blue, 2 red, 9 green; 2 blue, 1 red, 8 green; 11 green, 2 red, 3 blue; 7 green, 5 blue Game 32: 15 red, 5 green; 4 green, 2 blue, 3 red; 1 blue, 9 red; 1 blue, 15 red; 4 blue, 2 red, 8 green; 3 green, 3 blue Game 33: 13 blue, 1 red, 1 green; 8 blue, 6 red; 4 blue, 2 red Game 34: 5 blue, 9 red, 7 green; 8 red, 6 green, 5 blue; 2 blue, 7 green, 12 red Game 35: 4 blue, 15 red; 1 green, 10 blue, 7 red; 9 red, 3 green, 1 blue; 13 red, 9 blue; 3 blue, 2 red Game 36: 4 blue, 18 green, 2 red; 5 green, 6 blue, 11 red; 6 red, 12 blue, 14 green; 19 green, 10 blue, 7 red; 7 red, 8 green, 9 blue Game 37: 16 blue, 5 green, 18 red; 3 blue, 14 green, 1 red; 4 blue, 3 green, 14 red; 12 green, 7 red, 15 blue; 15 green, 11 blue, 2 red; 8 blue, 13 green, 6 red Game 38: 6 red, 4 blue, 12 green; 3 red, 11 blue; 16 green, 2 blue, 8 red; 4 blue, 11 red, 4 green; 17 green, 7 red, 10 blue; 9 blue, 15 green, 1 red Game 39: 1 green, 1 red, 10 blue; 1 red, 5 blue, 2 green; 4 red, 7 blue; 9 red, 6 green, 5 blue; 1 green, 2 blue, 9 red Game 40: 13 blue, 11 red, 12 green; 8 green, 11 red, 4 blue; 2 blue, 2 green, 12 red; 2 green, 3 red, 13 blue; 13 blue, 6 red, 2 green; 4 green, 6 red, 8 blue Game 41: 12 red, 4 green, 13 blue; 4 red, 7 blue, 10 green; 17 green, 17 red, 11 blue Game 42: 1 red, 1 green; 1 red, 4 green; 1 blue, 4 red, 4 green; 3 red; 1 blue, 3 green, 1 red Game 43: 7 blue, 10 green; 5 blue, 2 green; 2 blue, 1 green, 4 red; 14 red, 6 green, 7 blue; 4 green, 14 red, 8 blue; 4 green, 6 red Game 44: 9 green, 4 red; 4 red, 6 green; 5 red, 2 blue, 7 green; 9 blue, 1 green, 14 red Game 45: 20 blue, 4 red, 6 green; 3 blue, 1 green, 6 red; 8 blue, 8 green, 11 red Game 46: 1 green, 6 red; 6 red, 3 blue, 3 green; 6 red, 3 blue, 4 green; 1 blue, 5 red; 1 green, 4 red, 1 blue; 2 green, 4 red Game 47: 12 green, 8 red, 4 blue; 7 green, 6 red, 11 blue; 4 red, 11 blue, 12 green Game 48: 1 green, 3 blue; 13 green, 3 red, 11 blue; 7 blue, 1 green, 2 red; 7 red, 15 green, 4 blue; 4 red, 8 blue, 10 green; 15 green, 8 blue, 6 red Game 49: 2 red; 2 red, 9 blue; 4 blue, 1 green Game 50: 10 blue, 1 green, 18 red; 13 red, 1 green, 7 blue; 4 red, 2 green, 9 blue; 2 green, 4 red, 10 blue; 7 blue, 3 red; 19 red, 9 blue Game 51: 2 green, 2 red, 5 blue; 9 red, 5 blue; 3 red, 10 blue; 9 blue, 6 red, 7 green; 2 red, 5 blue Game 52: 6 blue, 3 green; 5 green, 3 blue, 5 red; 1 blue, 2 green, 2 red Game 53: 2 blue, 9 green, 15 red; 18 red, 1 blue; 13 red, 12 green; 7 green, 2 blue, 9 red Game 54: 18 green; 2 red, 6 green; 6 red, 9 green, 1 blue; 1 blue, 4 green, 5 red; 3 red; 3 green, 4 red Game 55: 5 red, 2 blue, 5 green; 10 blue, 4 green, 8 red; 15 green, 9 blue, 9 red; 1 green, 9 blue Game 56: 8 green, 11 blue, 1 red; 1 blue, 1 red, 4 green; 8 blue Game 57: 5 green, 4 blue; 1 blue, 4 green; 1 red, 1 green, 3 blue; 1 red, 2 blue, 6 green Game 58: 8 green, 10 red, 10 blue; 8 blue, 6 green, 12 red; 9 green, 11 blue, 1 red; 12 red, 5 green, 11 blue; 7 red, 2 green, 8 blue Game 59: 10 red, 1 green, 3 blue; 16 red, 1 green, 4 blue; 9 red, 2 blue; 1 red Game 60: 11 blue, 13 green, 10 red; 15 red, 12 blue; 3 blue, 9 green, 6 red; 12 blue, 5 green Game 61: 2 blue, 7 red; 3 green, 14 blue, 11 red; 7 red, 10 blue; 6 blue, 3 green, 4 red; 10 blue Game 62: 1 blue, 7 green; 6 red, 12 green, 1 blue; 8 red Game 63: 1 blue, 3 green, 1 red; 8 green, 10 red, 1 blue; 8 green, 11 red; 1 blue, 11 green, 5 red; 8 green, 11 red, 2 blue; 2 blue, 10 red, 6 green Game 64: 17 green, 2 blue; 12 blue, 8 green; 11 green, 3 red, 4 blue; 5 red, 9 green, 14 blue Game 65: 7 blue, 12 green, 5 red; 13 green, 5 blue, 4 red; 4 blue, 8 green, 1 red; 5 red, 10 green, 10 blue; 5 red, 5 blue, 15 green; 4 red, 9 green, 10 blue Game 66: 8 green, 2 red; 8 red, 4 green; 5 red, 2 blue, 7 green Game 67: 10 green, 7 blue, 2 red; 15 blue, 1 green, 9 red; 2 red, 7 green, 18 blue; 3 green, 5 blue, 8 red; 10 green, 11 blue, 1 red; 10 green, 4 red, 17 blue Game 68: 13 green, 10 blue, 7 red; 1 red, 15 green, 7 blue; 17 green, 14 red, 3 blue; 6 green, 8 blue, 6 red; 4 red, 3 blue, 5 green Game 69: 1 red, 6 green, 3 blue; 3 red, 4 blue, 6 green; 2 blue, 2 red, 1 green; 6 blue, 9 green, 2 red; 5 green, 6 blue Game 70: 1 green, 1 red, 3 blue; 2 green, 4 blue, 8 red; 5 red, 2 green, 3 blue; 3 green, 1 red, 3 blue; 3 green, 4 blue Game 71: 11 blue, 13 green; 1 red, 11 green, 3 blue; 6 blue, 14 green, 1 red; 5 blue, 17 green Game 72: 3 blue, 10 green, 4 red; 2 green, 6 red, 13 blue; 1 green, 1 blue, 6 red; 5 red, 1 blue, 1 green; 2 green, 5 red, 5 blue; 9 blue, 10 green, 6 red Game 73: 6 red, 4 green, 1 blue; 1 blue, 5 red, 3 green; 2 red, 11 green, 3 blue Game 74: 13 green, 2 red, 2 blue; 5 blue, 6 green; 12 green, 3 red, 4 blue; 2 green Game 75: 9 red, 10 blue, 6 green; 12 blue, 9 red; 11 red, 6 green; 12 blue, 2 red, 1 green Game 76: 1 green, 2 blue, 5 red; 2 blue, 1 green; 1 blue, 2 green, 1 red; 2 blue, 1 red; 3 green, 3 red Game 77: 5 green, 12 blue, 3 red; 11 blue, 9 green, 13 red; 8 blue, 13 green, 13 red Game 78: 2 red, 3 blue, 1 green; 1 green, 19 blue, 1 red; 7 blue, 2 green, 2 red Game 79: 5 red, 1 blue, 4 green; 1 blue, 9 green, 10 red; 13 red, 1 green; 1 blue, 1 red, 5 green Game 80: 13 green, 2 blue; 1 red, 4 blue, 13 green; 5 red, 7 green, 4 blue Game 81: 3 red, 4 blue, 12 green; 16 green, 5 red, 1 blue; 4 blue, 2 red, 2 green; 4 blue, 5 red, 13 green; 8 red, 4 blue, 13 green; 16 green, 3 red Game 82: 6 red, 3 green, 2 blue; 1 green, 6 red, 2 blue; 3 blue, 8 green, 9 red Game 83: 3 green, 3 red, 1 blue; 3 blue, 4 green, 3 red; 3 blue, 4 green, 1 red; 2 red, 8 green, 2 blue Game 84: 5 red, 6 blue, 3 green; 1 blue, 2 green; 3 green, 2 blue, 2 red; 1 red, 3 green, 6 blue; 12 red, 2 green; 4 blue, 2 green, 4 red Game 85: 11 green, 4 blue, 9 red; 13 red, 1 blue, 11 green; 7 green, 8 blue, 7 red; 1 red, 4 blue Game 86: 3 blue, 19 green, 7 red; 19 green, 1 red, 1 blue; 9 green, 2 red; 7 red, 6 green, 1 blue Game 87: 1 blue, 1 green, 4 red; 1 green, 6 red; 6 red, 2 blue; 8 red, 3 blue Game 88: 9 red, 6 blue; 4 red, 1 blue, 2 green; 1 green, 10 blue, 6 red; 2 blue, 1 green, 10 red; 7 red, 9 blue Game 89: 3 blue, 15 green, 1 red; 1 red, 13 green, 3 blue; 4 blue, 14 green, 4 red; 10 green, 1 blue Game 90: 1 red, 13 green; 3 green, 1 red, 5 blue; 5 blue, 6 green; 14 green, 4 blue; 3 blue, 10 green; 13 green, 1 red Game 91: 13 green, 11 red, 4 blue; 14 red, 1 green, 10 blue; 4 red, 2 green, 3 blue Game 92: 2 red, 3 blue, 6 green; 2 red, 2 blue, 8 green; 14 blue, 1 red, 1 green Game 93: 15 blue, 2 red, 13 green; 8 green, 2 red, 8 blue; 6 blue, 1 red, 2 green Game 94: 5 red, 4 green, 9 blue; 1 red, 5 green, 4 blue; 11 blue, 4 green, 2 red Game 95: 9 blue, 3 green; 2 green, 12 blue; 10 green, 3 blue; 1 green, 1 red, 10 blue Game 96: 4 blue, 2 red; 3 green, 10 blue, 7 red; 2 blue, 7 green, 1 red; 13 blue, 9 green; 10 blue, 4 green, 1 red Game 97: 6 red, 4 green; 1 blue, 13 red; 3 green, 13 red Game 98: 1 red, 13 blue, 1 green; 7 green, 5 blue, 3 red; 15 blue, 6 green; 4 blue, 5 green; 13 blue, 2 green, 1 red; 4 blue, 3 red, 2 green Game 99: 1 red, 2 green; 2 red, 2 blue, 1 green; 3 green, 1 blue, 6 red; 3 red, 4 green; 5 red, 1 blue, 4 green; 1 blue, 2 red, 1 green Game 100: 9 green, 2 blue, 12 red; 2 blue, 14 red, 2 green; 14 red, 12 green"""
0
Kotlin
0
0
a36addef07f61072cbf4c7c71adf2236a53959a5
12,480
advent-code
MIT License
src/Day20.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
fun main() { fun parseInput(input: List<String>): ArrayDeque<Pair<Int, Long>> { return ArrayDeque(input.mapIndexed{ idx, it -> Pair(idx, it.toLong())}.toCollection(ArrayDeque())) } fun part1(input: ArrayDeque<Pair<Int, Long>>): Long { // Iterate over each element in the list for (i in 0 until input.size){ // Find the element that has the original idx (i) val elem = input.find { it.first == i } var idx = input.indexOf(elem).toLong() val cur = input.removeAt(idx.toInt()) idx += cur.second idx = idx.mod(input.size.toLong()) if (idx == 0L) { idx = input.size.toLong() } input.add(idx.toInt(), cur) } val zeroElement = input.find { it.second == 0L } val zeroIdx = input.indexOf(zeroElement) var ans = input.get((1000+zeroIdx).mod(input.size)).second ans += input.get((2000+zeroIdx).mod(input.size)).second ans += input.get((3000+zeroIdx).mod(input.size)).second return ans } fun part2(input: ArrayDeque<Pair<Int, Long>>): Long { val decryptKey = 811589153L for (i in 0 until input.size) { val cur = input.removeAt(i) val newCur = Pair(cur.first, cur.second*decryptKey) input.add(i, newCur) } for (j in 0 until 10) { for (i in 0 until input.size){ // Find the element that has the original idx (i) val elem = input.find { it.first == i } var idx = input.indexOf(elem).toLong() val cur = input.removeAt(idx.toInt()) idx += cur.second idx = idx.mod(input.size.toLong()) if (idx == 0L) { idx = input.size.toLong() } input.add(idx.toInt(), cur) } } val zeroElement = input.find { it.second == 0L } val zeroIdx = input.indexOf(zeroElement) var ans = input.get((1000+zeroIdx).mod(input.size)).second ans += input.get((2000+zeroIdx).mod(input.size)).second ans += input.get((3000+zeroIdx).mod(input.size)).second return ans } val input = readInput("../input/Day20") var inputArray = parseInput(input) println(part1(inputArray)) // 2275 inputArray = parseInput(input) println(part2(inputArray)) // 4090409331120 }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
2,470
aoc-2022
Apache License 2.0
src/Day01.kt
galiagacandia
573,231,710
false
null
fun main() { fun part1(calories: List<String>): Int { var contadorElfo: Int = 0; var totalCalories: Int = 0 var maximasCalories: Int = 0 var elfoConMasCalories: String = "" var mapElfosCalories = mutableMapOf<Int, Int>() for (calorie in calories) { println(calorie) if (calorie.isNotEmpty()){ totalCalories += calorie.toInt(); } else { contadorElfo++ // Vacia llenamos la suma a una variable if(totalCalories > maximasCalories){ maximasCalories = totalCalories elfoConMasCalories = contadorElfo.toString() totalCalories = 0 mapElfosCalories[contadorElfo] = maximasCalories } } } //calories.forEach { s -> s.toBigInteger() }. return maximasCalories } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") var resultado: Int = part1(testInput) println("Maxima: " + resultado) //check(part1(testInput) == 14) //val input = readInput("Day01") //println(part1(input)) //println(part2(input)) }
0
Kotlin
0
0
b2a36f7616f86a68670a398cdefb491ab14a3968
1,341
adventofcode2022Kotlin
Apache License 2.0
src/Day07.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader fun main() { val testInput = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent() val testFs = createFS(testInput.reader()) check(partOne(testFs) == 95437) val input = file("Day07.txt") val fs = createFS(input.reader()) println( partOne(fs) ) println(partTwo(fs)) } private fun createFS(source: Reader): Node.Dir { val root = Node.Dir("/") var currentDir = root source.forEachLine { line -> if (line.isNotEmpty() && line[0] == '$') { // command val split = line.split(" ") if (split[1] == "cd") { val newDir = split[2] currentDir = when (newDir) { "/" -> root ".." -> currentDir.parent ?: root else -> { currentDir[newDir] as Node.Dir } } } } else { // file list val split = line.split(" ") if (split[0] == "dir") { currentDir.addDir(split[1]) } else { currentDir.addFile(split[1], split[0].toInt()) } } } return root } private fun Node.Dir.flatten(): List<Node.Dir> { return this.files.filterIsInstance<Node.Dir>().flatMap { it.flatten() } + this } private fun Node.Dir.dirSizes(): List<Int> { return this.flatten().map { it.size } } private fun partOne(rootfs: Node.Dir): Int { val dirs = rootfs.dirSizes() val filtered = dirs.filter { it <= 100000 } return filtered.fold(0) { acc, dir -> acc + dir } } private fun partTwo(rootfs: Node.Dir): Int { val nodes = rootfs.dirSizes() val totalSize = 70000000 val needed = 30000000 val free = totalSize - rootfs.size val toFree = needed - free return nodes.sorted().filter { it >= toFree }.apply { println(this) } .first() } sealed interface Node { val name: String val size: Int val parent: Dir? class File( override val name: String, override val size: Int, override val parent: Node.Dir ): Node { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as File if (name != other.name) return false if (parent != other.parent) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + parent.hashCode() return result } } class Dir( override val name: String, override val parent: Node.Dir? = null ): Node { val files: MutableList<Node> = mutableListOf() operator fun get(filename: String) = files.first { it.name == filename } fun addFile(filename: String, size: Int) = apply { files.add(File(filename, size, this)) } fun addDir(filename: String) = apply { files.add(Dir(filename, this)) } operator fun plus(file: Node) = apply { files.add(file) } override val size: Int get() = files.fold(0) { acc, sizedFile -> acc + sizedFile.size } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Dir if (name != other.name) return false if (parent != other.parent) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + (parent?.hashCode() ?: 0) return result } } }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
4,099
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestIsland.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack import kotlin.math.max /** * 827. Making A Large Island * @see <a href="https://leetcode.com/problems/making-a-large-island/">Source</a> */ fun interface LargestIsland { operator fun invoke(grid: Array<IntArray>): Int } /** * Approach 1: Naive Depth First Search */ class LargestIslandDFS : LargestIsland { private val dr = intArrayOf(-1, 0, 1, 0) private val dc = intArrayOf(0, -1, 0, 1) override operator fun invoke(grid: Array<IntArray>): Int { val n: Int = grid.size var ans = 0 var hasZero = false for (r in 0 until n) for (c in 0 until n) if (grid[r][c] == 0) { hasZero = true grid[r][c] = 1 ans = max(ans, check(grid, r, c)) grid[r][c] = 0 } return if (hasZero) ans else n * n } fun check(grid: Array<IntArray>, r0: Int, c0: Int): Int { val n = grid.size val stack: Stack<Int> = Stack() val seen: MutableSet<Int> = HashSet() stack.push(r0 * n + c0) seen.add(r0 * n + c0) while (stack.isNotEmpty()) { val code: Int = stack.pop() val r = code / n val c = code % n for (k in 0..3) { val nr = r + dr[k] val nc = c + dc[k] val isContains = !seen.contains(nr * n + nc) val local = nr in 0 until n && 0 <= nc && nc < n if (isContains && local && grid[nr][nc] == 1) { stack.push(nr * n + nc) seen.add(nr * n + nc) } } } return seen.size } } /** * Approach #2: Component Sizes */ class LargestIslandComponentSizes : LargestIsland { private val dr = intArrayOf(-1, 0, 1, 0) private val dc = intArrayOf(0, -1, 0, 1) private var grid: Array<IntArray> = arrayOf() private var n = 0 override operator fun invoke(grid: Array<IntArray>): Int { this.grid = grid n = grid.size var index = 2 val area = IntArray(n * n + 2) for (r in 0 until n) { for (c in 0 until n) { if (grid[r][c] == 1) { area[index] = dfs(r, c, index++) } } } var ans = 0 for (x in area) ans = max(ans, x) for (r in 0 until n) for (c in 0 until n) if (grid[r][c] == 0) { val seen: MutableSet<Int> = HashSet() for (move in neighbors(r, c)) { if (grid[move / n][move % n] > 1) { seen.add(grid[move / n][move % n]) } } var bns = 1 for (i in seen) { bns += area[i] } ans = max(ans, bns) } return ans } private fun dfs(r: Int, c: Int, index: Int): Int { var ans = 1 grid[r][c] = index for (move in neighbors(r, c)) { if (grid[move / n][move % n] == 1) { grid[move / n][move % n] = index ans += dfs(move / n, move % n, index) } } return ans } private fun neighbors(r: Int, c: Int): List<Int> { val ans: MutableList<Int> = ArrayList() for (k in 0..3) { val nr = r + dr[k] val nc = c + dc[k] if (nr in 0 until n && 0 <= nc && nc < n) { ans.add(nr * n + nc) } } return ans } } class LargestIslandUnionFind : LargestIsland { override operator fun invoke(grid: Array<IntArray>): Int { val rows: Int = grid.size val cols: Int = grid.first().size // create father array and size array, and initialize them val father = IntArray(rows * cols) for (i in 0 until rows * cols) { father[i] = i } val size = IntArray(rows * cols) { 1 } val dx = intArrayOf(0, 1, -1, 0) val dy = intArrayOf(1, 0, 0, -1) scanGrid(rows, cols, grid, dx, dy, father, size) // find current max component size val max = findMaxComponent(rows, cols, grid, dx, dy, father, size) // return whole size if the grid is an all 1 matrix, otherwise return the value of max return if (max == 0) rows * cols else max } private fun findMaxComponent( rows: Int, cols: Int, grid: Array<IntArray>, dx: IntArray, dy: IntArray, father: IntArray, size: IntArray, ): Int { var max = 0 for (i in size.indices) { max = max(max, size[i]) } // find max component size if we set any 0 to 1 for (i in 0 until rows) { for (j in 0 until cols) { if (grid[i][j] == 0) { var combinedSize = 1 val prevFather: MutableSet<Int> = HashSet() for (k in 0..3) { val newI = i + dx[k] val newJ = j + dy[k] val newId = newI * cols + newJ if (isValid(rows, cols, newI, newJ) && grid[newI][newJ] == 1) { val currFather = find(father, newId) if (prevFather.isEmpty() || !prevFather.contains(currFather)) { combinedSize += size[currFather] prevFather.add(currFather) } } } max = max(max, combinedSize) } } } return max } private fun scanGrid( rows: Int, cols: Int, grid: Array<IntArray>, dx: IntArray, dy: IntArray, father: IntArray, size: IntArray, ) { // scan grid, update father array and size array for (i in 0 until rows) { for (j in 0 until cols) { if (grid[i][j] == 1) { val id = i * cols + j for (k in 0..3) { val newI = i + dx[k] val newJ = j + dy[k] val newId = newI * cols + newJ if (isValid(rows, cols, newI, newJ) && grid[newI][newJ] == 1) { union(father, size, id, newId) } } } } } } private fun find(father: IntArray, id: Int): Int { return if (father[id] == id) { id } else { find(father, father[id]).also { father[id] = it } } } private fun union(father: IntArray, size: IntArray, id1: Int, id2: Int) { val fa1 = find(father, id1) val fa2 = find(father, id2) if (fa1 != fa2) { father[fa1] = fa2 size[fa2] += size[fa1] } } private fun isValid(rows: Int, cols: Int, i: Int, j: Int): Boolean { return i in 0 until rows && j >= 0 && j < cols } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
7,741
kotlab
Apache License 2.0
src/day17/Code.kt
fcolasuonno
221,697,249
false
null
package day17 import java.io.File import java.security.MessageDigest fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.single() data class Position(val hash: String, val location: Pair<Int, Int>) fun isOpen(hash: ByteArray, direction: Pair<Char, Pair<Int, Int>>) = when (direction.first) { 'U' -> direction.second.second >= 0 && (0xf0 and hash[0].toInt()).ushr(4) > 10 'D' -> direction.second.second <= 3 && (0x0f and hash[0].toInt()) > 10 'L' -> direction.second.first >= 0 && (0xf0 and hash[1].toInt()).ushr(4) > 10 else -> direction.second.first <= 3 && (0x0f and hash[1].toInt()) > 10 } fun part1(input: String): Any? { val frontier = mutableSetOf<Position>().toSortedSet(compareBy<Position> { it.hash.length } .thenBy { 6 - it.location.first - it.location.second }.thenBy { it.hash }) frontier.add(Position(input, (0 to 0))) while (frontier.isNotEmpty()) { val position = frontier.first() frontier.remove(position) val location = position.location val hash = MessageDigest.getInstance("MD5").digest(position.hash.toByteArray()) val elements = setOf( 'U' to location.copy(second = location.second - 1), 'D' to location.copy(second = location.second + 1), 'L' to location.copy(first = location.first - 1), 'R' to location.copy(first = location.first + 1)) .filter { isOpen(hash, it) } .map { Position(position.hash + it.first, it.second) } elements.forEach { if (it.location == (3 to 3)) { return it.hash.substring(input.length) } else { frontier.add((it)) } } } return null } fun part2(input: String): Any? { val frontier = mutableSetOf<Position>().toSortedSet(compareBy<Position> { it.hash.length } .thenBy { 6 - it.location.first - it.location.second }.thenBy { it.hash }) frontier.add(Position(input, (0 to 0))) val solutions = mutableSetOf<String>() while (frontier.isNotEmpty()) { val position = frontier.first() frontier.remove(position) val location = position.location val hash = MessageDigest.getInstance("MD5").digest(position.hash.toByteArray()) val elements = setOf( 'U' to location.copy(second = location.second - 1), 'D' to location.copy(second = location.second + 1), 'L' to location.copy(first = location.first - 1), 'R' to location.copy(first = location.first + 1)) .filter { isOpen(hash, it) } .map { Position(position.hash + it.first, it.second) } elements.forEach { if (it.location == (3 to 3)) { solutions.add(it.hash.substring(input.length)) } else { frontier.add((it)) } } } return solutions.map { it.length }.max() }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
3,296
AOC2016
MIT License
src/main/kotlin/days/Day12.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day12 : Day(12) { private val edges = inputList.map { it.split("-") } .flatMap { (from, to) -> listOf(from to to, to to from) } .groupBy { it.first } .mapValues { (_, value) -> value.map { (_, to) -> to } } override fun partOne(): Any { val visited = setOf("start") return countPaths("start", visited, edges, true) } override fun partTwo(): Any { val visited = setOf("start") return countPaths("start", visited, edges, false) } private fun countPaths(s: String, visited: Set<String>, edges: Map<String, List<String>>, beenTwice: Boolean): Int { if (s == "end") return 1 return edges.getOrDefault(s, emptyList()).sumBy { next -> if (next !in visited || next.all { it.isUpperCase() }) countPaths(next, visited + next, edges, beenTwice) else if (next != "start" && !beenTwice) countPaths(next, visited + next, edges, true) else 0 } } }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
1,000
aoc-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/hj/leetcode/kotlin/problem2251/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2251 /** * LeetCode page: [2251. Number of Flowers in Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom/); */ class Solution { /* Complexity: * Time O((N+M)LogN) and Space O(N) where N is the size of flowers and * M is the size of people; */ fun fullBloomFlowers(flowers: Array<IntArray>, people: IntArray): IntArray { val sortedStarts = IntArray(flowers.size) { flowers[it][0] }.apply { sort() } val sortedEnds = IntArray(flowers.size) { flowers[it][1] }.apply { sort() } return IntArray(people.size) { index -> numFlowersInFullBloom(people[index], sortedStarts, sortedEnds) } } private fun numFlowersInFullBloom( time: Int, sortedStarts: IntArray, sortedEnds: IntArray ): Int { val numStarted = leftInsertionIndex(time + 1, sortedStarts) val numEnded = leftInsertionIndex(time, sortedEnds) return numStarted - numEnded } /** * Return the leftmost index to insert the [target] while keeping * the [sorted] sorted. */ private fun leftInsertionIndex(target: Int, sorted: IntArray): Int { if (sorted.isEmpty() || target <= sorted[0]) { return 0 } if (sorted.last() < target) { return sorted.size } var left = 0 var right = sorted.lastIndex while (left < right) { val mid = (left + right) ushr 1 if (sorted[mid] < target) { left = mid + 1 } else { right = mid } } return left } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,706
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/Subsets2Kt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/subsets-ii/description/ Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] */ class Subsets2Kt { class Solution { private fun equalLists(l0: List<Int>, l1: List<Int>): Boolean { if (l0.size != l1.size) { return false } l0.forEachIndexed { index, value -> if (l1[index] != value) { return false } } return true } private fun listOfListContainsList(bigList: ArrayList<List<Int>>?, other: List<Int>): Boolean { bigList?.forEach { if (equalLists(it, other)) { return true } } return false } fun backtrack(results: HashMap<Int, ArrayList<List<Int>>>, tempList: ArrayList<Int>, possible: ArrayList<Int>) { if (results[tempList.size] == null) { results[tempList.size] = ArrayList() results[tempList.size]?.add(tempList) } else if (!listOfListContainsList(results[tempList.size], tempList)) { results[tempList.size]?.add(tempList) } possible.forEachIndexed { index, value -> val copyTempList = ArrayList(tempList) copyTempList.add(value) val copyPossible = ArrayList<Int>(possible.size) possible.forEachIndexed { i, v -> if (i > index) { copyPossible.add(v) } } backtrack(results, copyTempList, copyPossible) } } fun subsetsWithDup(nums: IntArray): List<List<Int>> { nums.sort() val results = HashMap<Int, ArrayList<List<Int>>>() val possible = ArrayList<Int>() nums.forEach { possible.add(it) } backtrack(results, ArrayList(), possible) val res = ArrayList<List<Int>>() results.forEach { _, value -> res.addAll(value) } return res } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
2,429
cloud-dqn-leetcode
No Limit Public License
src/Day14.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
fun main() { fun input(input: List<String>): MutableSet<Pair<Int, Int>> { val used = HashSet<Pair<Int, Int>>() for (s in input) { val parts = s.split(" -> ") for (i in 0 until parts.size - 1) { val (x0, y0) = parts[i].split(',').map { it.toInt() } val (x1, y1) = parts[i + 1].split(',').map { it.toInt() } for (x in minOf(x0, x1)..maxOf(x0, x1)) { for (y in minOf(y0, y1)..maxOf(y0, y1)) { used += x to y } } } } return used } val start = 500 to 0 fun fallNext(used: MutableSet<Pair<Int, Int>>, lowest: Int): Pair<Int, Int> { var (x, y) = start while (true) { val ny = y + 1 if (y > lowest) break for (dx in intArrayOf(0, -1, 1)) { val nx = x + dx if ((nx to ny) !in used) { x = nx y = ny break } } if (y != ny) break } return (x to y).also { used += it } } fun part1(input: List<String>): Int { val used = input(input) val lowest = used.maxOf { (_, y) -> y } var cnt = 0 while (true) { val (x, y) = fallNext(used, lowest) if (y > lowest) break used += x to y cnt++ } return cnt } fun part2(input: List<String>): Int { val used = input(input) val lowest = used.maxOf { (_, y) -> y } var cnt = 0 while (start !in used) { used += fallNext(used, lowest) cnt++ } return cnt } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 14) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
2,197
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximalNetworkRank.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1615. Maximal Network Rank * @see <a href="https://leetcode.com/problems/maximal-network-rank/">Source</a> */ fun interface MaximalNetworkRank { operator fun invoke(n: Int, roads: Array<IntArray>): Int } class MaximalNetworkRankInDegree : MaximalNetworkRank { override operator fun invoke(n: Int, roads: Array<IntArray>): Int { var maxRank = 0 val adj: MutableMap<Int, MutableSet<Int>> = HashMap() // Construct adjacency list 'adj', where adj[node] stores all nodes connected to 'node'. for (road in roads) { adj.computeIfAbsent(road[0]) { HashSet() }.add(road[1]) adj.computeIfAbsent(road[1]) { HashSet() }.add(road[0]) } // Iterate on each possible pair of nodes. for (node1 in 0 until n) { for (node2 in node1 + 1 until n) { var currentRank = adj.getOrDefault(node1, emptySet()).size + adj.getOrDefault(node2, emptySet()).size // Find the current pair's respective network rank and store if it's maximum till now. if (adj.getOrDefault(node1, emptySet()).contains(node2)) { --currentRank } maxRank = max(maxRank.toDouble(), currentRank.toDouble()).toInt() } } // Return the maximum network rank. return maxRank } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,055
kotlab
Apache License 2.0
src/magic-square-forming.kt
syn-ack42
117,293,780
false
null
package magic_square_forming import java.util.* val origMagicSquare: List<List<Int>> = listOf( listOf(2, 7, 6), listOf(9, 5, 1), listOf(4, 3, 8) ) fun rotateSquare(square: List<List<Int>>, by: Int): List<List<Int>> { return when(by) { 0 -> square 1 -> listOf(listOf(square[2][0], square[1][0], square[0][0]), listOf(square[2][1], square[1][1], square[0][1]), listOf(square[2][2], square[1][2], square[0][2])) 2 -> rotateSquare(rotateSquare(square, 1), 1) 3 -> rotateSquare(rotateSquare(square, 2), 1) else -> throw (RuntimeException("screw up!")) } } fun flipSquare(square: List<List<Int>>): List<List<Int>> { return listOf( listOf(square[2][0], square[2][1], square[2][2]), listOf(square[1][0], square[1][1], square[1][2]), listOf(square[0][0], square[0][1], square[0][2])) } fun printSquare(square: List<List<Int>>) { square.forEach { println(it.joinToString(separator = " ", transform = {it.toString()})) } } fun abs(d: Int): Int { return if (d>=0) d else -d } fun squaresDistance(square1: List<List<Int>>, square2: List<List<Int>>): Int { var sum = 0 for (y in 0..2) { for (x in 0..2) { sum += abs(square1[y][x] - square2[y][x]) } } return sum } val allSquares = listOf( origMagicSquare, rotateSquare(origMagicSquare,1), rotateSquare(origMagicSquare,2), rotateSquare(origMagicSquare,3), flipSquare(origMagicSquare), rotateSquare(flipSquare(origMagicSquare),1), rotateSquare(flipSquare(origMagicSquare),2), rotateSquare(flipSquare(origMagicSquare),3) ) fun main(args: Array<String>) { val sc = Scanner(System.`in`) val row0 = sc.nextLine().split(" ").map { it.toInt()} val row1 = sc.nextLine().split(" ").map { it.toInt()} val row2 = sc.nextLine().split(" ").map { it.toInt()} val matrix: List<List<Int>> = listOf(row0, row1, row2) var minDist = 99999 // println("in matrix:") // printSquare(matrix) // println("\nall magic squares:") allSquares.forEach { // printSquare(it) val d = squaresDistance(matrix, it) // println("distance: $d") if (d<minDist) { minDist = d } } print(minDist) }
0
Kotlin
0
0
aaafc8b59889f2ea49836b2a2d64517167179036
2,532
HackerRank
MIT License
src/day04/Day04.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day04 import readInput fun main() { fun part1(input: List<String>): Int { val lambda = { line: String -> val (range1, range2) = parseLine(line) val unionSection = range1 union range2 if (range1 == unionSection || range2 == unionSection) 1 else 0 } return input.sumOf(lambda) } fun part2(input: List<String>): Int { val lambda = { line: String -> val (range1, range2) = parseLine(line) if ((range1 intersect range2).isNotEmpty()) 1 else 0 } return input.sumOf(lambda) } val testInput = readInput("day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("day04") println(part1(input)) // 580 println(part2(input)) // 895 } fun parseLine(line: String): Pair<Set<Int>, Set<Int>> { val (a1, a2, b1, b2) = line.split('-', ',').map(String::toInt) val range1 = (a1..a2).toSet() val range2 = (b1..b2).toSet() return range1 to range2 }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,044
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2401_2500/s2497_maximum_star_sum_of_a_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2497_maximum_star_sum_of_a_graph // #Medium #Array #Sorting #Greedy #Heap_Priority_Queue #Graph // #2023_07_05_Time_773_ms_(100.00%)_Space_94.6_MB_(100.00%) import java.util.PriorityQueue class Solution { private lateinit var graphNodeIdToNodeValues: Array<PriorityQueue<Int>?> fun maxStarSum(nodeValues: IntArray, edges: Array<IntArray>, maxNumberOfEdges: Int): Int { val totalNodes = nodeValues.size graphNodeIdToNodeValues = arrayOfNulls(totalNodes) for (i in 0 until totalNodes) { graphNodeIdToNodeValues[i] = PriorityQueue() } for (edge in edges) { addEdgeEndingWithValueOfNode(nodeValues, edge[0], edge[1], maxNumberOfEdges) addEdgeEndingWithValueOfNode(nodeValues, edge[1], edge[0], maxNumberOfEdges) } return calculateMaxStarSum(nodeValues, totalNodes) } private fun addEdgeEndingWithValueOfNode( nodeValues: IntArray, fromNode: Int, toNode: Int, maxNumberOfEdges: Int ) { if (nodeValues[toNode] > 0 && graphNodeIdToNodeValues[fromNode]!!.size < maxNumberOfEdges) { graphNodeIdToNodeValues[fromNode]!!.add(nodeValues[toNode]) } else if (graphNodeIdToNodeValues[fromNode]!!.isNotEmpty() && graphNodeIdToNodeValues[fromNode]!!.peek() < nodeValues[toNode] ) { graphNodeIdToNodeValues[fromNode]!!.poll() graphNodeIdToNodeValues[fromNode]!!.add(nodeValues[toNode]) } } private fun calculateMaxStarSum(nodeValues: IntArray, totalNodes: Int): Int { var maxStarSum = Int.MIN_VALUE for (i in 0 until totalNodes) { var sum = nodeValues[i] for (value in graphNodeIdToNodeValues[i]!!) { sum += value } maxStarSum = Math.max(maxStarSum, sum) } return maxStarSum } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,919
LeetCode-in-Kotlin
MIT License
a3/a3-enhanced/src/main/kotlin/ui/assignments/connectfour/model/Grid.kt
Gray-Yang
589,632,902
false
null
package ui.assignments.connectfour.model /** * The grid of Connect-Four and functionality to interact with it, i.e., play the game. * version 1.01: BUGFIX: did not detect insertions that form chains > length, e.g., ***_** -> ****** */ class Grid(width: Int, height: Int, private val length: Int) { /** * The grid. Coordinates run from (0,0) (top-left) to (width-1,height-1) (bottom-right). */ private val grid = Array2D(width, height) /** * Returns the larger of two Pair<Player, Int>. why do we need to use this func */ private fun max(item: Pair<Player, Int>, other: Pair<Player, Int>): Pair<Player, Int> { return if (item.first == Player.NONE && other.first != Player.NONE) other else if (item.first != Player.NONE && other.first == Player.NONE) item else if (other.second > item.second) other else item } /** * Returns the largest consecutive chain within a list * @param list the list * @return a [Pair<Player, Int>] that holds the length of the longest chain, and which player's pieces form this chain. 有用如果回来是4 且 有 player就出结果 */ private fun longestChain(list: List<Player>) : Pair<Player, Int> { var curCount = Pair(list[0], 1) var maxCount = curCount.copy() (1 until list.count()).forEach { idx -> curCount = if (list[idx] == curCount.first) { Pair(curCount.first, curCount.second + 1) } else { maxCount = max(maxCount, curCount) Pair(list[idx], 1) } } return max(maxCount, curCount) } /** * Returns the player who has won the game on the current grid. * version 1.01: BUGFIX: did not detect insertions that form chains > length, e.g., ***_** -> ****** * changed (playerWon.second == length) to: (playerWon.second >= length) * @return player who has won the game, or [Player.NONE] if no-one has won the game yet. every step call this to see whether there is a winer */ fun hasWon() : Player { var playerWon = Pair(Player.NONE, 0) grid.getColumns().forEach { // check columns playerWon = max(playerWon, longestChain(it)) } grid.getRows().forEach { // check rows playerWon = max(playerWon, longestChain(it)) } grid.getDiagonals().forEach { // check diagonals top-right -> bottom-left playerWon = max(playerWon, longestChain(it)) } grid.getDiagonals2().forEach { // check diagonals bottom-right -> top-left playerWon = max(playerWon, longestChain(it)) } return if (playerWon.second >= length) playerWon.first else Player.NONE } /** * Checks if the draw-condition has occurred, i.e., the grid is full. * @return draw-condition has occurred if no winner check if the game is draw */ fun hasDraw() : Boolean { return grid.getColumns().any { list -> list.any { it == Player.NONE } }.not() } /** * Attempts to drop a piece in a certain column. If a piece can be successfully dropped, the function returns that [Piece]. If not, the function returns null. * @param column the column in which to drop a piece * @return the dropped [Piece], if successful; null otherwise * 如果人松手那就drop那个东西下去看看是不是成功 如果成功returns piece */ fun dropPiece(column: Int, player: Player): Piece? { val row = grid.getColumn(column).count { it.player == Player.NONE } // number of unoccupied spots in the column if (row == 0) return null // if none ... return null grid.setCell(column, row - 1, player) // set ownership for piece furthest down in the column return grid.getCell(column, row - 1) // return piece } }
0
Kotlin
0
0
4d998822044fc16e5181a813a1ac272c839d9c0a
4,111
Android-Apps
MIT License
calendar/day10/Day10.kt
maartenh
572,433,648
false
{"Kotlin": 50914}
package day10 import Day import Lines class Day10 : Day() { override fun part1(input: Lines): Any { val cpu = CPU() val statesOverTime = listOf(cpu.state) + input.map { instruction -> cpu.execute(instruction) cpu.state } val measurementCycles = 20..220 step 40 return measurementCycles.sumOf { cycle -> statesOverTime.stateAt(cycle).x * cycle } } override fun part2(input: Lines): Any { val cpu = CPU() val statesOverTime = listOf(cpu.state) + input.map { instruction -> cpu.execute(instruction) cpu.state } val cycles = 1..240 val output = cycles .map { cycle -> val x = statesOverTime.stateAt(cycle).x val position = (cycle - 1) % 40 if (position in x - 1..x + 1) { '#' } else { '.' } } .chunked(40) .joinToString(separator = "\n") { it.joinToString(separator = "") } return "\n" + output } } private fun List<CPU.State>.stateAt(targetCycle: Int): CPU.State = last { it.time <= targetCycle } class CPU(var state: State = State(1, 1)) { fun execute(instruction: String) { when { instruction == "noop" -> state = state.copy( time = state.time + 1 ) instruction.startsWith("addx ") -> state = state.copy( time = state.time + 2, x = state.x + instruction.substring(5).toInt() ) } } data class State(val time: Int, val x: Int) }
0
Kotlin
0
0
4297aa0d7addcdc9077f86ad572f72d8e1f90fe8
1,927
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2021/Geometry.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright 2021 by <NAME> */ package com.ginsberg.advent2021 import kotlin.math.absoluteValue import kotlin.math.sign data class Point2d(val x: Int, val y: Int) { infix fun sharesAxisWith(that: Point2d): Boolean = x == that.x || y == that.y infix fun lineTo(that: Point2d): List<Point2d> { val xDelta = (that.x - x).sign val yDelta = (that.y - y).sign val steps = maxOf((x - that.x).absoluteValue, (y - that.y).absoluteValue) return (1..steps).scan(this) { last, _ -> Point2d(last.x + xDelta, last.y + yDelta) } } fun neighbors(): List<Point2d> = listOf( Point2d(x, y + 1), Point2d(x, y - 1), Point2d(x + 1, y), Point2d(x - 1, y) ) fun allNeighbors(): List<Point2d> = neighbors() + listOf( Point2d(x - 1, y - 1), Point2d(x - 1, y + 1), Point2d(x + 1, y - 1), Point2d(x + 1, y + 1) ) } data class Point3d(val x: Int, val y: Int, val z: Int) { infix fun distanceTo(other: Point3d): Int = (this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue + (this.z - other.z).absoluteValue operator fun plus(other: Point3d): Point3d = Point3d(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point3d): Point3d = Point3d(x - other.x, y - other.y, z - other.z) fun face(facing: Int): Point3d = when (facing) { 0 -> this 1 -> Point3d(x, -y, -z) 2 -> Point3d(x, -z, y) 3 -> Point3d(-y, -z, x) 4 -> Point3d(y, -z, -x) 5 -> Point3d(-x, -z, -y) else -> error("Invalid facing") } fun rotate(rotating: Int): Point3d = when (rotating) { 0 -> this 1 -> Point3d(-y, x, z) 2 -> Point3d(-x, -y, z) 3 -> Point3d(y, -x, z) else -> error("Invalid rotation") } companion object { fun of(rawInput: String): Point3d = rawInput.split(",").let { part -> Point3d(part[0].toInt(), part[1].toInt(), part[2].toInt()) } } }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
2,203
advent-2021-kotlin
Apache License 2.0
src/day21/Day21.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day21 import java.io.File fun main() { val data = parse("src/day21/Day21.txt") println("🎄 Day 21 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private fun solve(data: List<List<Char>>, start: Pair<Int, Int>, n: Int): Long { var plots = setOf(start) repeat(n) { val next = mutableSetOf<Pair<Int, Int>>() for ((px, py) in plots) { for ((dx, dy) in listOf((-1 to 0), (1 to 0), (0 to -1), (0 to 1))) { val nx = px + dx val ny = py + dy if (nx in data.indices && ny in data.indices) { if (data[ny][nx] != '#') { next += nx to ny } } } } plots = next } return plots.size.toLong() } private fun part1(data: List<List<Char>>): Long { for ((y, row) in data.withIndex()) { for ((x, col) in row.withIndex()) { if (col == 'S') { return solve(data, Pair(x, y), 64) } } } error("Starting point not found.") } private fun part2(data: List<List<Char>>): Long { val size = data.size val steps = 26_501_365 val sx = size / 2 val sy = size / 2 val n = (steps / size - 1).toLong() val evenGrids = n * n val evenCount = evenGrids * solve(data, start = Pair(sx, sy), n = 2 * size + 1) val oddGrids = (n + 1) * (n + 1) val oddCount = oddGrids * solve(data, start = Pair(sx, sy), n = 2 * size) val corners = solve(data, start = Pair(sx, size - 1), n = size - 1) + // Top solve(data, start = Pair(size - 1, sy), n = size - 1) + // Left solve(data, start = Pair(sx, 0), n = size - 1) + // Bottom solve(data, start = Pair(0, sy), n = size - 1) // Right val smallSections = solve(data, start = Pair(size - 1, size - 1), n = size / 2 - 1) + // Top-left solve(data, start = Pair(size - 1, 0), n = size / 2 - 1) + // Bottom-left solve(data, start = Pair(0, 0), n = size / 2 - 1) + // Bottom-right solve(data, start = Pair(0, size - 1), n = size / 2 - 1) // Top-right val largeSections = solve(data, start = Pair(size - 1, size - 1), n = size * 3 / 2 - 1) + // Top-left solve(data, start = Pair(size - 1, 0), n = size * 3 / 2 - 1) + // Bottom-left solve(data, start = Pair(0, 0), n = size * 3 / 2 - 1) + // Bottom-right solve(data, start = Pair(0, size - 1), n = size * 3 / 2 - 1) // Top-right return evenCount + oddCount + corners + (n + 1) * smallSections + n * largeSections }
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
3,010
advent-of-code-2023
MIT License
src/Day05.kt
kkaptur
573,511,972
false
{"Kotlin": 14524}
import java.io.File import java.util.* fun main() { val input = File("src", "Day05.txt").readText().split("\n\n") val testInput = File("src", "Day05_test.txt").readText().split("\n\n") fun getStacksWithElements(input: List<String>): MutableList<Stack<String>> = mutableListOf<Stack<String>>().apply { addAll(input[0].lines().last().filter { str -> str.isDigit() }.map { Stack() }) input[0] .lines() .dropLast(1) .reversed() .map { it.drop(1) .windowed(1, 4) .forEachIndexed { index, crate -> if (crate.isNotBlank()) this[index].push(crate) } } } fun getNumberData(input: List<String>): List<List<Int>> = input[1].lines().map { Regex("[0-9]+").findAll(it) .map(MatchResult::value) .map { result -> result.toInt() } .toList() } fun part1(input: List<String>): String { val stacks = getStacksWithElements(input) getNumberData(input).forEach { numbers -> for (move: Int in 1..numbers[0]) { stacks[numbers[2] - 1].push(stacks[numbers[1] - 1].pop()) } } return stacks.joinToString("") { it.peek().toString() } } fun part2(input: List<String>): String { val stacks = getStacksWithElements(input) getNumberData(input).forEach { numbers -> val movedElements = mutableListOf<String>() for (move: Int in 1..numbers[0]) { movedElements.add(stacks[numbers[1] - 1].pop()) } stacks[numbers[2] - 1].addAll(movedElements.reversed()) } return stacks.joinToString("") { it.peek().toString() } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
055073b7c073c8c1daabbfd293139fecf412632a
1,953
AdventOfCode2022Kotlin
Apache License 2.0
src/Day01.kt
riFaulkner
576,298,647
false
{"Kotlin": 9466}
fun main() { fun getElfCalorieTotals(input: List<String>): List<Int> { val elfTotals = ArrayList<Int>() var currentElfCalorieCount = 0 input.forEach{ if (it.equals("")) { elfTotals.add(currentElfCalorieCount) currentElfCalorieCount = 0 } else { currentElfCalorieCount += it.toInt() } } elfTotals.add(currentElfCalorieCount) return elfTotals } fun getTotalForTopElfs(input: List<String>, numberOfElfs: Int = 1): Int { val elfTotals = getElfCalorieTotals(input).sortedDescending() return elfTotals.subList(0, numberOfElfs).sum() } fun part1(input: List<String>): Int { return getTotalForTopElfs(input) } fun part2(input: List<String>): Int { return getTotalForTopElfs(input, 3) } // test if implementation meets criteria from the description, like: val testInput = readInput("inputs/Day01-example") part1(testInput).println() part2(testInput).println() check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("inputs/Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
33ca7468e17c47079fe2e922a3b74fd0887e1b62
1,244
aoc-kotlin-2022
Apache License 2.0
src/Day02.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { fun part1(input: List<String>): Int { val scores = mapOf<String, Int>( "A X" to 4, "A Y" to 8, "A Z" to 3, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 7, "C Y" to 2, "C Z" to 6, ) var score = 0 input.forEach { score += scores[it]!! } return score } fun part2(input: List<String>): Int { val scores = mapOf<String, Int>( "A X" to 3, "A Y" to 4, "A Z" to 8, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 2, "C Y" to 6, "C Z" to 7, ) var score = 0 input.forEach { score += scores[it]!! } return score } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
1,033
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TopKFrequent.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import java.util.LinkedList import java.util.PriorityQueue import java.util.TreeMap /** * 692. Top K Frequent Words */ fun interface TopKFrequent { operator fun invoke(words: Array<String>, k: Int): List<String> } private class Comparator1 : Comparator<Map.Entry<String, Int>> { override fun compare(o1: Map.Entry<String, Int>, o2: Map.Entry<String, Int>): Int { val word1: String = o1.key val freq1: Int = o1.value val word2: String = o2.key val freq2: Int = o2.value return if (freq1 != freq2) { freq1 - freq2 } else { word2.compareTo(word1) } } } class Comparator2 : Comparator<Map.Entry<String, Int>> { override fun compare(o1: Map.Entry<String, Int>, o2: Map.Entry<String, Int>): Int { val word1 = o1.key val freq1 = o1.value val word2 = o2.key val freq2 = o2.value return if (freq1 != freq2) { freq2 - freq1 } else { word1.compareTo(word2) } } } class TopKFrequentSorting : TopKFrequent { override operator fun invoke(words: Array<String>, k: Int): List<String> { val map: MutableMap<String, Int> = HashMap() for (word in words) { map[word] = map.getOrDefault(word, 0) + 1 } val l: MutableList<Map.Entry<String, Int>> = LinkedList() for (e in map.entries) { l.add(e) } l.sortWith(Comparator2()) val ans: MutableList<String> = LinkedList() for (i in 0 until k) { ans.add(l[i].key) } return ans } } class TopKFrequentMinHeap : TopKFrequent { override operator fun invoke(words: Array<String>, k: Int): List<String> { val map: MutableMap<String, Int> = HashMap() for (word in words) { map[word] = map.getOrDefault(word, 0) + 1 } val comparator = Comparator1() val pq: PriorityQueue<Map.Entry<String, Int>> = PriorityQueue(comparator) for (e in map.entries) { // If minHeap's size is smaller than K, we just add the entry if (pq.size < k) { pq.offer(e) } else { if (pq.peek() != null && comparator.compare(e, pq.peek()) > 0) { pq.poll() pq.offer(e) } } } val ans: MutableList<String> = LinkedList() for (i in 0 until k) { ans.add(0, pq.poll().key) } return ans } } class TopKFrequentMap : TopKFrequent { override operator fun invoke(words: Array<String>, k: Int): List<String> { val result: MutableList<String> = LinkedList() val map: MutableMap<String, Int> = HashMap() for (i in words.indices) { if (map.containsKey(words[i])) map[words[i]] = map[words[i]]!! + 1 else map[words[i]] = 1 } val pq: PriorityQueue<Map.Entry<String, Int>> = PriorityQueue { a, b -> if (a.value == b.value) b.key.compareTo(a.key) else a.value - b.value } for (entry in map.entries) { pq.offer(entry) if (pq.size > k) { pq.poll() } } while (pq.isNotEmpty()) result.add(0, pq.poll().key) return result } } class TopKFrequentTrie : TopKFrequent { override operator fun invoke(words: Array<String>, k: Int): List<String> { val map: MutableMap<String, Int> = HashMap() for (word in words) { map[word] = map.getOrDefault(word, 0) + 1 } val buckets = arrayOfNulls<Trie>(words.size) for ((word, freq) in map) { // for each word, add it into trie at its bucket if (buckets[freq] == null) { buckets[freq] = Trie() } buckets[freq]?.addWord(word) } val ans: MutableList<String> = LinkedList() for (i in buckets.indices.reversed()) { // for trie in each bucket, get all the words with same frequency in lexicographic order. // Compare with k and get the result if (buckets[i] != null) { val l: MutableList<String> = LinkedList() buckets[i]?.getWords(buckets[i]?.root, l) if (l.size < k) { ans.addAll(l) k - l.size } else { for (j in 0 until k) { ans.add(l[j]) } break } } } return ans } class TrieNode { var children = arrayOfNulls<TrieNode>(ALPHABET_LETTERS_COUNT) var word: String? = null } class Trie { var root = TrieNode() fun addWord(word: String) { var cur: TrieNode? = root for (c in word.toCharArray()) { if (cur!!.children[c.code - 'a'.code] == null) { cur.children[c.code - 'a'.code] = TrieNode() } cur = cur.children[c.code - 'a'.code] } cur?.word = word } fun getWords(node: TrieNode?, ans: MutableList<String>) { if (node == null) { return } if (node.word != null) { ans.add(node.word ?: return) } for (i in 0 until ALPHABET_LETTERS_COUNT) { if (node.children[i] != null) { getWords(node.children[i], ans) } } } } } class TopKFrequentBucketSort : TopKFrequent { override operator fun invoke(words: Array<String>, k: Int): List<String> { val map: MutableMap<String, Int> = HashMap() for (word in words) { map[word] = map.getOrDefault(word, 0) + 1 } val buckets: Array<TreeMap<String, Int>?> = arrayOfNulls(words.size) for ((word, freq) in map) { if (buckets[freq] == null) { buckets[freq] = TreeMap { a: String, b: String? -> a.compareTo(b!!) } } buckets[freq]!![word] = freq } val ans: MutableList<String> = LinkedList() for (i in buckets.indices.reversed()) { if (buckets[i] != null) { var k0 = k val temp = buckets[i] ?: return emptyList() if (temp.size < k0) { k0 -= temp.size while (temp.isNotEmpty()) { ans.add(temp.pollFirstEntry().key) } } else { while (k0 > 0) { ans.add(temp.pollFirstEntry().key) k0-- } break } } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
7,616
kotlab
Apache License 2.0
codeforces/kotlinheroes6/g_wrong.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.kotlinheroes6 import java.util.* import kotlin.system.exitProcess fun main() { for (n in 1..20) solve(n) solve(readInt()) } private fun solve(n: Int) { val set = List(2 * n + 1) { TreeSet<Int>() } val score = IntArray(n + 1) { 0 } val divs = List(n + 1) { mutableListOf<Int>() } for (i in 1..n) set[0].add(i) fun change(x: Int, delta: Int) { set[n + score[x]].remove(x) score[x] += delta set[n + score[x]].add(x) } fun remove(x: Int) { set[n + score[x]].remove(x) score[x] = -1 } for (i in 1..n) { for (j in 2 * i..n step i) { change(j, +1) divs[j].add(i) } } val ans = mutableListOf(0) var bestScore = set.lastIndex for (k in 1..n) { while (set[bestScore].isEmpty()) bestScore-- var bonus = bestScore - n val x = set[bestScore].last() remove(x) for (j in 2 * x..n step x) { if (score[j] == -1) { bonus-- continue } } ans.add(ans.last() + bonus) } val fullSearch = researchFullSearch(n) if (!fullSearch.contentEquals(ans.toIntArray())) { println("! $n") println(ans.drop(1).joinToString(" ")) println(fullSearch.drop(1).joinToString(" ")) println(researchStupid(n).drop(1).joinToString(" ")) exitProcess(0) } println(ans.drop(1).joinToString(" ")) } private fun researchFullSearch(n: Int): IntArray { val ans = IntArray(n + 1) { 0 } for (mask in 0 until (1 shl n)) { var count = 0 for (i in 0 until n) if (mask.hasBit(i)) for (j in 0 until n) if (!mask.hasBit(j) && (i + 1) % (j + 1) == 0) { count++ } if (count >= 17) { println(count) println(n) println(mask.toString(2)) } val size = mask.countOneBits() ans[size] = maxOf(ans[size], count) } return ans } private fun researchStupid(n: Int): IntArray { val ans = IntArray(n + 1) { val k = n - it var s = 0 for (i in k + 1..n) for (j in 1..k) { if (i % j == 0) s++ } s } return ans } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun Int.bit(index: Int) = shr(index) and 1 private fun Int.hasBit(index: Int) = bit(index) != 0
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,063
competitions
The Unlicense
Kotlin/src/main/kotlin/org/algorithm/problems/0046_odd_even_jump.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
// Problem Statement // You are given an integer array A. From some starting index, you can make a // series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd // numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps. // // You may from index i jump forward to index j (with i < j) in the following way: // // *During odd numbered jumps (ie. jumps 1, 3, 5, ...), you jump to the index j // such that A[i] <= A[j] and A[j] is the smallest possible value. // If there are multiple such indexes j, you can only jump to the smallest such index j. // *During even numbered jumps (ie. jumps 2, 4, 6, ...), you jump to the index j // such that A[i] >= A[j] and A[j] is the largest possible value. // If there are multiple such indexes j, you can only jump to the smallest such index j. // *(It may be the case that for some index i, there are no legal jumps.) // // A starting index is good if, starting from that index, you can reach the end of // the array (index A.length - 1) by jumping some number of times (possibly 0 or more than once.) // // Return the number of good starting indexes. package org.algorithm.problems class BST { data class Node( var value: Int, var index: Int, var left: Node? = null, var right: Node? = null ) private var root: Node? = null fun add(value: Int, index: Int) { if (root == null) { root = Node(value, index) } else { var it = root while (it != null) { if (it.value == value) { it.index = index break } else if (it.value < value) { if (it.right == null) { it.right = Node(value, index) break } else { it = it.right } } else { if (it.left == null) { it.left = Node(value, index) break } else { it = it.left } } } } } fun getMaxSmallest(value: Int): Int? { var it = root var curr: Node? = null while (it != null) { if (it.value <= value) { curr = it it = it.right } else { it = it.left } } return curr?.index } fun getMinBiggest(value: Int): Int? { var it = root var curr: Node? = null while (it != null) { if (it.value >= value) { curr = it it = it.left } else { it = it.right } } return curr?.index } } class `0046_odd_even_jump` { fun oddEvenJumps(A: IntArray): Int { val bst = BST() var result = 0 val oddJump = IntArray(A.size) { 0 } val evenJump = IntArray(A.size) { 0 } oddJump[A.size - 1] = 1 evenJump[A.size - 1] = 1 bst.add(A[A.size - 1], A.size - 1) for (i in A.size - 2 downTo 0) { val indexOdd = bst.getMinBiggest(A[i]) val indexEven = bst.getMaxSmallest(A[i]) indexEven?.let { evenJump[i] = oddJump[indexEven] } indexOdd?.let { oddJump[i] = evenJump[indexOdd] } bst.add(A[i], i) } for (jump in oddJump) { result += jump } return result } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
3,671
algorithms
MIT License
korlibs-datastructure/src/korlibs/datastructure/_GenericSort.kt
korlibs
80,095,683
false
{"WebAssembly": 14293935, "Kotlin": 9727891, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
package korlibs.datastructure import kotlin.math.min fun <T> genericSort(subject: T, left: Int, right: Int, ops: SortOps<T>): T = genericSort(subject, left, right, ops, false) fun <T> genericSort(subject: T, left: Int, right: Int, ops: SortOps<T>, reversed: Boolean): T = subject.also { timSort(subject, left, right, ops, reversed) } private fun Int.negateIf(doNegate: Boolean) = if (doNegate) -this else this private fun <T> insertionSort(arr: T, left: Int, right: Int, ops: SortOps<T>, reversed: Boolean) { for (n in left + 1..right) { var m = n - 1 while (m >= left) { if (ops.compare(arr, m, n).negateIf(reversed) <= 0) break m-- } m++ if (m != n) ops.shiftLeft(arr, m, n) } } private fun <T> merge(arr: T, start: Int, mid: Int, end: Int, ops: SortOps<T>, reversed: Boolean) { var s = start var m = mid var s2 = m + 1 if (ops.compare(arr, m, s2).negateIf(reversed) <= 0) return while (s <= m && s2 <= end) { if (ops.compare(arr, s, s2).negateIf(reversed) <= 0) { s++ } else { ops.shiftLeft(arr, s, s2) s++ m++ s2++ } } } private fun <T> mergeSort(arr: T, l: Int, r: Int, ops: SortOps<T>, reversed: Boolean) { if (l < r) { val m = l + (r - l) / 2 mergeSort(arr, l, m, ops, reversed) mergeSort(arr, m + 1, r, ops, reversed) merge(arr, l, m, r, ops, reversed) } } private fun <T> timSort(arr: T, l: Int, r: Int, ops: SortOps<T>, reversed: Boolean, RUN: Int = 32) { val n = r - l + 1 for (i in 0 until n step RUN) { insertionSort(arr, l + i, l + min((i + RUN - 1), (n - 1)), ops, reversed) } var size = RUN while (size < n) { for (left in 0 until n step (2 * size)) { val rize = min(size, n - left - 1) val mid = left + rize - 1 val right = min((left + 2 * rize - 1), (n - 1)) merge(arr, l + left, l + mid, l + right, ops, reversed) } size *= 2 } } abstract class SortOps<T> { abstract fun compare(subject: T, l: Int, r: Int): Int abstract fun swap(subject: T, indexL: Int, indexR: Int) open fun shiftLeft(subject: T, indexL: Int, indexR: Int) { for (n in indexR downTo indexL + 1) swap(subject, n - 1, n) } open fun reverse(subject: T, indexL: Int, indexR: Int) { val count = indexR - indexL + 1 for (n in 0 until count / 2) { swap(subject, indexL + n, indexR - n) } } } object SortOpsComparable : SortOps<MutableList<Comparable<Any>>>() { override fun compare(subject: MutableList<Comparable<Any>>, l: Int, r: Int): Int = subject[l].compareTo(subject[r]) override fun swap(subject: MutableList<Comparable<Any>>, indexL: Int, indexR: Int) { val tmp = subject[indexL] subject[indexL] = subject[indexR] subject[indexR] = tmp } } fun <T : Comparable<T>> MutableList<T>.genericSort(left: Int = 0, right: Int = size - 1): MutableList<T> = genericSort(this, left, right, SortOpsComparable as SortOps<MutableList<T>>, false) fun <T : Comparable<T>> List<T>.genericSorted(left: Int = 0, right: Int = size - 1): List<T> = this.subList(left, right + 1).toMutableList().genericSort() fun <T : Comparable<T>> List<T>.timSorted(): List<T> = this.toMutableList().also { it.timSort() } fun <T : Comparable<T>> MutableList<T>.timSort(left: Int = 0, right: Int = size - 1): MutableList<T> { timSort(this, left, right, SortOpsComparable as SortOps<MutableList<T>>, false) //genericSort(this, left, right, SortOpsComparable as SortOps<MutableList<T>>, false) return this }
438
WebAssembly
118
2,188
11993ae7828c96ee261b5d610904c8ca5430b8d2
3,750
korge
Apache License 2.0
src/main/kotlin/g1901_2000/s1926_nearest_exit_from_entrance_in_maze/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1926_nearest_exit_from_entrance_in_maze // #Medium #Array #Breadth_First_Search #Matrix #Graph_Theory_I_Day_6_Matrix_Related_Problems // #2023_06_20_Time_351_ms_(94.44%)_Space_45.4_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { fun nearestExit(maze: Array<CharArray>, entrance: IntArray): Int { val m = maze.size val n = maze[0].size val directions = intArrayOf(0, 1, 0, -1, 0) val queue: Queue<IntArray> = LinkedList() queue.offer(intArrayOf(entrance[0], entrance[1], 0)) val visited = Array(m) { BooleanArray(n) } visited[entrance[0]][entrance[1]] = true var shortestSteps = m * n while (queue.isNotEmpty()) { val curr = queue.poll() for (i in 0 until directions.size - 1) { val nextX = curr[0] + directions[i] val nextY = curr[1] + directions[i + 1] if (nextX >= 0 && nextX < m && nextY >= 0 && nextY < n && maze[nextX][nextY] == '.' && !visited[nextX][nextY] ) { visited[nextX][nextY] = true if (nextX == 0 || nextX == m - 1 || nextY == 0 || nextY == n - 1) { shortestSteps = Math.min(shortestSteps, curr[2] + 1) } else { queue.offer(intArrayOf(nextX, nextY, curr[2] + 1)) } } } } return if (shortestSteps == m * n) -1 else shortestSteps } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,563
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/paulshields/aoc/Day15.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 15: Chiton */ package dev.paulshields.aoc import dev.paulshields.aoc.common.Point import dev.paulshields.aoc.common.readFileAsString fun main() { println(" ** Day 15: Chiton ** \n") val riskLevelMap = readFileAsString("/Day15RiskLevelMap.txt") val startingPosition = Point(0, 0) val cave = ChitonCave(riskLevelMap) var finishingPosition = Point(cave.width - 1, cave.height - 1) var riskLevelsFromStartingPosition = cave.findShortestDistanceThroughCave(startingPosition) println("The least risky distance through the cave is ${riskLevelsFromStartingPosition[finishingPosition]}") val fullCave = FullChitonCave(riskLevelMap) finishingPosition = Point(fullCave.width - 1, fullCave.height - 1) riskLevelsFromStartingPosition = fullCave.findShortestDistanceThroughCave(startingPosition) println("The least risky distance through the full cave is ${riskLevelsFromStartingPosition[finishingPosition]}") } class FullChitonCave(rawRiskLevelMap: String) : ChitonCave(rawRiskLevelMap) { private val cellWidth = super.width private val cellHeight = super.height override var width = cellWidth * 5 override var height = cellHeight * 5 override fun getRiskAtNode(node: Point): Int { val xPos = node.x % cellWidth val yPos = node.y % cellHeight val widthIterations = node.x / cellWidth val heightIterations = node.y / cellHeight return ((riskLevelMap[yPos][xPos] + widthIterations + heightIterations - 1) % 9) + 1 } } open class ChitonCave(rawRiskLevelMap: String) { protected val riskLevelMap = parseRiskLevelMap(rawRiskLevelMap) open var width = riskLevelMap[0].size protected set open var height = riskLevelMap.size protected set private fun parseRiskLevelMap(riskLevelMap: String): List<List<Int>> { return riskLevelMap.lines().map { it.toCharArray().map { it.digitToInt() } } } /** * Using a lightly modified Dijkstra's Algorithm * * Performance on this is still dodgy. Worth a revisit sometime. Might be the use of linked collections for storage types. */ fun findShortestDistanceThroughCave(startingPosition: Point): Map<Point, Int> { val numberOfNodes = width * height val riskLevelsOverDistance = mutableMapOf(startingPosition to 0) val settledNodes = mutableSetOf<Point>() val unsettledNodes = mutableSetOf(startingPosition) while (settledNodes.size < numberOfNodes) { val closestNode = unsettledNodes.minByOrNull { riskLevelsOverDistance[it] ?: Int.MAX_VALUE } ?: unsettledNodes.first() val closestNodeRiskLevel = riskLevelsOverDistance[closestNode] ?: Int.MAX_VALUE settledNodes.add(closestNode) unsettledNodes.remove(closestNode) val adjacentNodes = getAdjacentNodes(closestNode) .filter { adjacentNode -> !settledNodes.contains(adjacentNode) } unsettledNodes.addAll(adjacentNodes) adjacentNodes .forEach { adjacentNode -> val currentRiskLevel = riskLevelsOverDistance[adjacentNode] ?: Int.MAX_VALUE val proposedRiskLevel = closestNodeRiskLevel + getRiskAtNode(adjacentNode) if (proposedRiskLevel < currentRiskLevel) { riskLevelsOverDistance[adjacentNode] = proposedRiskLevel } } } return riskLevelsOverDistance.toMap() } protected open fun getRiskAtNode(node: Point) = riskLevelMap[node.y][node.x] private fun getAdjacentNodes(node: Point): List<Point> { val topNode = if (node.y > 0) Point(node.x, node.y - 1) else null val leftNode = if (node.x > 0) Point(node.x - 1, node.y) else null val bottomNode = if (node.y < height - 1) Point(node.x, node.y + 1) else null val rightNode = if (node.x < width - 1) Point(node.x + 1, node.y) else null return listOfNotNull(topNode, leftNode, bottomNode, rightNode) } }
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
4,067
AdventOfCode2021
MIT License
kotlin/src/com/daily/algothrim/leetcode/MaxNumEdgesToRemove.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 1579. 保证图可完全遍历 * * Alice 和 Bob 共有一个无向图,其中包含 n 个节点和 3  种类型的边: * * 类型 1:只能由 Alice 遍历。 * 类型 2:只能由 Bob 遍历。 * 类型 3:Alice 和 Bob 都可以遍历。 * 给你一个数组 edges ,其中 edges[i] = [typei, ui, vi] 表示节点 ui 和 vi 之间存在类型为 typei 的双向边。请你在保证图仍能够被 Alice和 Bob 完全遍历的前提下,找出可以删除的最大边数。如果从任何节点开始,Alice 和 Bob 都可以到达所有其他节点,则认为图是可以完全遍历的。 * * 返回可以删除的最大边数,如果 Alice 和 Bob 无法完全遍历图,则返回 -1 。 */ class MaxNumEdgesToRemove { companion object { @JvmStatic fun main(args: Array<String>) { println(MaxNumEdgesToRemove().solution(4, arrayOf( intArrayOf(3, 1, 2), intArrayOf(3, 2, 3), intArrayOf(1, 1, 3), intArrayOf(1, 2, 4), intArrayOf(1, 1, 2), intArrayOf(2, 3, 4) ))) println(MaxNumEdgesToRemove().solution(2, arrayOf( intArrayOf(1, 1, 2), intArrayOf(2, 1, 2), intArrayOf(3, 1, 2) ))) } } // n = 2, edges = [[1,1,2],[2,1,2],[3,1,2]] // n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] fun solution(n: Int, edges: Array<IntArray>): Int { val unionFoundX = UnionFound(n) val unionFoundY = UnionFound(n) var result = 0 edges.forEach { if (it[0] == 3) { if (!unionFoundX.setUnion(it[1], it[2])) { result++ } else { unionFoundY.setUnion(it[1], it[2]) } } } edges.forEach { if (it[0] == 1) { if (!unionFoundX.setUnion(it[1], it[2])) { result++ } } else if (it[0] == 2) { if (!unionFoundY.setUnion(it[1], it[2])) { result++ } } } if (unionFoundX.count != 1 || unionFoundY.count != 1) return -1 return result } class UnionFound(n: Int) { private val p = Array(n + 1) { it } var count = n private fun find(index: Int): Int = if (p[index] == index) index else { p[index] = find(p[index]) find(p[index]) } fun setUnion(x: Int, y: Int): Boolean { val xP = find(x) val yP = find(y) if (xP == yP) return false p[xP] = yP count-- return true } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,882
daily_algorithm
Apache License 2.0
src/Day21.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
//val monkeys= readInput("day21_input_test").map { // getMonkey(it) //} ////e.g. ////* root = pppw = sjmn (we know sjmm is 150) so pppw must be 150 as well ////* pppw = cczh / lfqf (we know lfgf is 4 so it becomes 150 = cczh / 4 so cczh = 600 ////* cczh = sllz + lgvd (we know cczh is 600, sllz is 4 so lgvd is 596) ... and so on // //fun main() { //// prLongln(monkeys) // val root = monkeys.indexOfFirst { it.first == "pppw" } // // val rootMonkey = monkeys[root].second as Monkey.OperatorMonkey // val rf = monkeys.first { it.first == rootMonkey.firstMonkey }.second // val rs = monkeys.first { it.first == rootMonkey.secondMonkey }.second // println(calculateMonkey(rf, rs, rootMonkey.operator)) //} // //fun calculateMonkey(firstMonkey: Monkey, secondMonkey: Monkey, operator: String): Long { // if (firstMonkey is Monkey.NumberMonkey && secondMonkey is Monkey.NumberMonkey) { // return calculate(firstMonkey.number, secondMonkey.number, operator) // } // else if (firstMonkey is Monkey.OperatorMonkey && secondMonkey is Monkey.NumberMonkey) { // val f = monkeys.first { it.first == firstMonkey.firstMonkey }.second // val s = monkeys.first { it.first == firstMonkey.secondMonkey }.second // return calculate(calculateMonkey(f, s, firstMonkey.operator), secondMonkey.number, operator) // } // else if (firstMonkey is Monkey.NumberMonkey && secondMonkey is Monkey.OperatorMonkey) { // val f = monkeys.first { it.first == secondMonkey.firstMonkey }.second // val s = monkeys.first { it.first == secondMonkey.secondMonkey }.second // return calculate(firstMonkey.number, calculateMonkey(f, s, secondMonkey.operator), operator) // } else if (firstMonkey is Monkey.OperatorMonkey && secondMonkey is Monkey.OperatorMonkey) { // // both operator // val ff = monkeys.first { it.first == firstMonkey.firstMonkey }.second // val fs = monkeys.first { it.first == firstMonkey.secondMonkey }.second // // val sf = monkeys.first { it.first == secondMonkey.firstMonkey }.second // val ss = monkeys.first { it.first == secondMonkey.secondMonkey }.second // return calculate(calculateMonkey(ff, fs, firstMonkey.operator), calculateMonkey(sf, ss, secondMonkey.operator), operator) // } // return -1 //} // //private fun calculate(first: Long, second: Long, operator: String): Long { // return when(operator) { // "+" -> return first + second // "-" -> return first - second // "*" -> return first * second // "/" -> return first / second // else -> { -1 } // } //} //// ////fun calculateMonkey(firstMonkeyName: String, secondMonkeyName: String, operator: String): Long { //// val firstMonkey = monkeys.first { it.first == firstMonkeyName } //// val secondMonkey = monkeys.first { it.first == secondMonkeyName } //// if (firstMonkey.second is Monkey.NumberMonkey && secondMonkey.second is Monkey.NumberMonkey) { //// val numberFirstMonkey = firstMonkey.second as Monkey.NumberMonkey //// val numberSecondMonkey = secondMonkey.second as Monkey.NumberMonkey //// when(operator) { //// "+" -> return numberFirstMonkey.number + numberSecondMonkey.number //// "-" -> return numberFirstMonkey.number + numberSecondMonkey.number //// "*" -> return numberFirstMonkey.number + numberSecondMonkey.number //// "/" -> return numberFirstMonkey.number + numberSecondMonkey.number //// } //// //// return -1 //// } //// else if (firstMonkey.second is Monkey.OperatorMonkey && secondMonkey.second is Monkey.NumberMonkey){ //// return //// } //// else if (firstMonkey.second is Monkey.NumberMonkey && secondMonkey.second is Monkey.OperatorMonkey){ //// //// } else { //// //// } //// //// return -1 ////} // // ////fun getMonkey(t: String): Pair<String, Monkey> { //// val s = t.split(" ") //// val monkey = s[0].substringBefore(":") //// return if (t.contains(Regex("""[+-/*]"""))) { //// //// val firstMonkey = s[1] //// val operator = s[2] //// val secondMonkey = s[3] //// monkey to Monkey.OperatorMonkey(monkey, operator, firstMonkey, secondMonkey) //// } else { //// monkey to Monkey.NumberMonkey(monkey = monkey, number = s[1].toLong() ) //// } ////} //// ////sealed class Monkey(open val monkey: String) { //// data class OperatorMonkey(override val monkey: String, val operator: String, val firstMonkey: String, val secondMonkey: String):Monkey() //// //// data class NumberMonkey(override val monkey: String, val number: Long): Monkey() ////} ////
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
4,677
advent22
Apache License 2.0
year2023/day07/cards/src/main/kotlin/com/curtislb/adventofcode/year2023/day07/cards/Hand.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2023.day07.cards import com.curtislb.adventofcode.common.collection.Counter import com.curtislb.adventofcode.common.comparison.compareLists /** * A hand of Camel Cards, consisting of an ordered list of cards and a bid amount. * * @property cards The cards contained in the hand, from left to right. * @property bid The bid amount for the hand. * * @constructor Creates a new instance of [Hand] with the given [cards] and [bid] amount. */ data class Hand(val cards: List<Card>, val bid: Long) : Comparable<Hand> { /** * Counts of all distinct card labels in the hand, in descending order. * * Used to compare hands by type (e.g. "full house" vs. "two of a kind"). */ private val countsDescending: List<Int> init { // Count each distinct card label val cardCounter = Counter.fromItems(cards) countsDescending = when (val jokerCount = cardCounter[Card.JOKER].toInt()) { // If no jokers, sort the card counts as-is 0 -> cardCounter.counts.map { it.toInt() }.sortedDescending() // If all jokers, treat them as the same card cards.size -> listOf(jokerCount) // Treat all jokers as the most common card else -> cardCounter.entries .filter { it.key != Card.JOKER } .map { it.value.toInt() } .toMutableList() .also { counts -> counts.sortDescending() counts[0] += jokerCount } } } override fun compareTo(other: Hand): Int { // Compare hand types, which are ordered by descending counts val countsResult = compareLists(countsDescending, other.countsDescending) if (countsResult != 0) { return countsResult } // Compare cards by strength, from left to right val cardsResult = compareLists(cards, other.cards) if (cardsResult != 0) { return cardsResult } // Compare the bid amounts return bid.compareTo(other.bid) } companion object { /** * A regex used to parse the cards and bid for a hand. */ private val HAND_REGEX = Regex("""(\w+)\s+(\d+)""") /** * Returns a [Hand] with cards and bid amount read from the given [string]. * * The [string] must have the format `"$cards $bid"`, where `cards` is an ordered sequence * of [Card] labels and `bid` is a decimal integer representing the bid amount. * * If [useJokerRule] is `true`, the label `J` will be treated as [Card.JOKER]. Otherwise, it * will be treated as [Card.JACK]. * * @throws IllegalArgumentException If [string] has the wrong format. */ fun fromString(string: String, useJokerRule: Boolean): Hand { val matchResult = HAND_REGEX.matchEntire(string) require(matchResult != null) { "Malformed hand string: $string" } val (cardsString, bidString) = matchResult.destructured val cards = cardsString.map { Card.fromChar(it, useJokerRule) } val bid = bidString.toLong() return Hand(cards, bid) } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,301
AdventOfCode
MIT License
kotlin-leetcode/src/main/kotlin/io/github/dreamylost/Leetcode_1372.kt
jxnu-liguobin
123,690,567
false
null
/* Licensed under Apache-2.0 @梦境迷离 */ package io.github.dreamylost import kotlin.math.max /** * 1372. 二叉树中的最长交错路径 * * 给你一棵以 root 为根的二叉树,二叉树中的交错路径定义如下: * 选择二叉树中 任意 节点和一个方向(左或者右)。 * 如果前进方向为右,那么移动到当前节点的的右子节点,否则移动到它的左子节点。 * 改变前进方向:左变右或者右变左。 * 重复第二步和第三步,直到你在树中无法继续移动。 * 交错路径的长度定义为:访问过的节点数目 - 1(单个节点的路径长度为 0 )。 * 请你返回给定树中最长 交错路径 的长度。 * @author 梦境迷离 * @version 1.0,2020/10/10 */ class Leetcode_1372 { /** * 404 ms,100.00% * 46.5 MB,100.00% */ fun longestZigZag(root: TreeNode?): Int { var ret = 0 fun dfs(r: TreeNode?, isLeft: Boolean): Int { if (r == null) return 0 val l = dfs(r.left, true) val r = dfs(r.right, false) ret = max(ret, max(l, r)) return if (isLeft) { r + 1 } else l + 1 } dfs(root, true) return ret } }
13
Java
190
526
a97159e99fc6592bec5032d18391d18b84708175
1,272
cs-summary-reflection
Apache License 2.0
src/twentytwo/Day05.kt
mihainov
573,105,304
false
{"Kotlin": 42574}
package twentytwo import readInputTwentyTwo import java.util.* import java.util.stream.Collectors typealias Crate = Char typealias Stack = LinkedList<Crate> fun List<String>.createDock(): Dock { // does not work correctly when nCrates == 0, but that's impossible val nCrates = (this.first().length + 1) / 4 val dock = Dock(nCrates) // filter starting crates this.forEach { for (i in 0 until nCrates) { val relevantChar = it[1 + (i * 4)] if (relevantChar.isLetter()) { dock.stacks[i].addLast(relevantChar) } } } return dock } // to support destructuring declaration with 6 elements private operator fun <E> List<E>.component6(): E { return this[5] } class Dock(nStacks: Int) { val stacks = mutableListOf<Stack>() init { repeat(nStacks) { stacks.add(Stack()) } } fun getCrateTops(): String { return stacks.stream().map { it.peek().toString() }.collect(Collectors.joining()) } fun handleOperationWithCrateMover9000(operation: String) { // move 3 from 2 to 1 val (_, nCrates, _, fromStack, _, toStack) = operation.split(' ') operateCrateMover9000(nCrates!!.toInt(), fromStack.toInt(), toStack.toInt()) } private fun operateCrateMover9000(nCrates: Int, fromStack: Int, toStack: Int) { repeat(nCrates) { val crateInTransit = stacks[fromStack - 1].pop() stacks[toStack - 1].addFirst(crateInTransit) } } fun handleOperationWithCrateMover9001(operation: String) { // move 3 from 2 to 1 val (_, nCrates, _, fromStack, _, toStack) = operation.split(' ') operateCrateMover9001(nCrates!!.toInt(), fromStack.toInt(), toStack.toInt()) } private fun operateCrateMover9001(nCrates: Int, fromStack: Int, toStack: Int) { val cratesInTransit = mutableListOf<Crate>() repeat(nCrates) { cratesInTransit.add(stacks[fromStack - 1].pollFirst()) } cratesInTransit.reversed().forEach(stacks[toStack - 1]::addFirst) } } fun main() { fun part1(input: List<String>): String { val dockCreationCommands = input.filter { it.contains("[") } val dockOperationsCommands = input.filter { it.contains("move") } val dock = dockCreationCommands.createDock() dockOperationsCommands.forEach(dock::handleOperationWithCrateMover9000) return dock.getCrateTops() } fun part2(input: List<String>): String { val dockCreationCommands = input.filter { it.contains("[") } val dockOperationsCommands = input.filter { it.contains("move") } val dock = dockCreationCommands.createDock() dockOperationsCommands.forEach(dock::handleOperationWithCrateMover9001) return dock.getCrateTops() } // test if implementation meets criteria from the description, like: val testInput = readInputTwentyTwo("Day05_test") check(part1(testInput).also(::println) == "CMZ") check(part2(testInput).also(::println) == "MCD") val input = readInputTwentyTwo("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a9aae753cf97a8909656b6137918ed176a84765e
3,196
kotlin-aoc-1
Apache License 2.0
BinaryGap.kt
getnahid
267,415,396
false
null
/* BinaryGap Find longest sequence of zeros in binary representation of an integer. A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps. Write a function: class Solution { public int solution(int N); } that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..2,147,483,647].*/ fun solution(n: Int): Int { val stringBinary = Integer.toBinaryString(n) var part = Integer.toBinaryString(n).substring(0, stringBinary.lastIndexOf("1")) val parts = part.split("1", part) var max = 0; for (p in parts) { if (p.length > max) max = p.length } return max; }
0
Kotlin
0
0
589c392237334f6c53513dc7b75bd8fa81ad3b79
1,582
programing-problem-solves-kotlin
Apache License 2.0
src/Day03.kt
timj11dude
572,900,585
false
{"Kotlin": 15953}
import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { fun Char.toPriority(): Int = when { isUpperCase() -> code - (65 - 27) isLowerCase() -> code - (96) else -> throw IllegalArgumentException("unknown char [$this]") } fun bagList(input: Collection<String>) = input.map(String::toList) fun part1(input: Collection<String>): Int { return bagList(input) .map { (it.take(it.size / 2).toSet() to it.drop(it.size / 2).toSet()) } // split to groups .sumOf { (it.first intersect it.second).single().toPriority() } // intersect two groups, find 1, get Priority number } fun part2(input: Collection<String>): Int { return bagList(input) .windowed(3, 3) { group -> // a group has 3 lines group .map { it.toSet() } .reduce(Set<Char>::intersect) .single() .toPriority() }.sum() } // test if implementation meets criteria from the description, like: check(part1(readInput("Day03_test")) == 157) check(part2(readInput("Day03_test")) == 70) val duration = measureTime { println(part1(readInput("Day03"))) println(part2(readInput("Day03"))) } println(duration) }
0
Kotlin
0
0
28aa4518ea861bd1b60463b23def22e70b1ed481
1,364
advent-of-code-2022
Apache License 2.0