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
LeetCode/Largest Magic Square/main.kt
thedevelopersanjeev
112,687,950
false
null
class Solution { private fun isGood(grid: Array<IntArray>, x: Int, y: Int, len: Int): Boolean { val st = HashSet<Int>() for (i in x until x + len) { var curr = 0 for (j in y until y + len) curr += grid[i][j] st.add(curr) } for (j in y until y + len) { var curr = 0 for (i in x until x + len) curr += grid[i][j] st.add(curr) } if (st.size > 1) return false var (i, j, curr) = arrayOf(x, y, 0) while (i < x + len && j < y + len) { curr += grid[i][j] ++i ++j } st.add(curr) if (st.size > 1) return false i = x; j = y + len - 1; curr = 0 while (i < x + len && j >= y) { curr += grid[i][j] ++i --j } st.add(curr) return st.size == 1 } private fun solve(grid: Array<IntArray>, n: Int, m: Int): Int { for (len in n downTo 1) { for (i in 0 until n - len + 1) { for (j in 0 until m - len + 1) { if (isGood(grid, i, j, len)) return len } } } return 1 } fun largestMagicSquare(grid: Array<IntArray>): Int { val (n, m) = arrayOf(grid.size, grid[0].size) return if (n < m) { solve(grid, n, m) } else { val arr = Array(m) { IntArray(n) } for (i in grid.indices) { for (j in grid[0].indices) { arr[j][i] = grid[i][j] } } solve(arr, m, n) } } }
0
C++
58
146
610520cc396fb13a03c606b5fb6739cfd68cc444
1,729
Competitive-Programming
MIT License
src/day16/Day16pt2.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
package day16 import readInput import kotlin.math.max import kotlin.math.pow class StepData(val data: ShortArray, val totalValves: Int, val usefulValves: Int, val players: Int) { companion object { fun numberOfValveConfigurations(usefulValves: Int): Int { return (2).toDouble().pow(usefulValves).toInt() } fun create(totalValves: Int, usefulValves: Int, players: Int): StepData { val numberOfPositions = totalValves.toDouble().pow(players).toInt() return StepData( ShortArray(numberOfPositions * numberOfValveConfigurations(usefulValves)) { _ -> -1 }, totalValves, usefulValves, players ) } } private fun numberOfValveConfigurations(): Int { return Companion.numberOfValveConfigurations(usefulValves) } fun unpack(state: Int): State { val openValvesMask = state % numberOfValveConfigurations() var encodedPositions = state / numberOfValveConfigurations() val positions = mutableListOf<Int>() for (i in 0 until players) { positions.add(encodedPositions % totalValves) encodedPositions /= totalValves } val openValves = mutableSetOf<Int>() for (i in 0 until usefulValves) { if (openValvesMask and (1 shl i) != 0) { openValves.add(i) } } return State(positions, openValves) } fun pack(state: State): Int { var openValvesMask = 0 for (i in 0 until usefulValves) { if (i in state.openValves) { openValvesMask = openValvesMask or (1 shl i) } } var encodedPositions = 0 for (player in state.positions.reversed()) { encodedPositions += player encodedPositions *= totalValves } encodedPositions /= totalValves return encodedPositions * numberOfValveConfigurations() + openValvesMask } operator fun set(state: State, value: Short) { data[pack(state)] = value } operator fun get(state: State): Short { return data[pack(state)] } } data class EncodedValve(val rate: Int, val tunnels: List<Int>) sealed class Transition { class Move(val direction: Int) : Transition() { override fun toString(): String { return "move to $direction" } } class OpenValve(val valve: Int) : Transition() { override fun toString(): String { return "open valve $valve" } } } class ValveInfo( private val valves: List<EncodedValve>, val usefulValvesCount: Int, val startValve: Int, val numbersToNames: Map<Int, String> ) { companion object { fun create(input: List<String>): ValveInfo { val parsedValves = parseValves(input) val usefulValves = parsedValves.filter { e -> e.value.rate > 0 }.toList() val uselessValves = parsedValves.filter { e -> e.value.rate == 0 }.toList() val orderedValves = usefulValves + uselessValves val namesToNumbers = mutableMapOf<String, Int>() orderedValves.forEachIndexed { index, valve -> namesToNumbers[valve.first] = index } val valves = orderedValves .map { valve -> EncodedValve(valve.second.rate, valve.second.tunnels.map { v -> namesToNumbers[v]!! }) } return ValveInfo(valves, usefulValves.size, namesToNumbers["AA"]!!, namesToNumbers.entries.associateBy({ it.value }) { it.key }) } } fun production(state: State): Short { return state.openValves.sumOf { v -> valves[v].rate }.toShort() } private fun isUseful(valve: Int): Boolean { return valve < usefulValvesCount } fun totalValves(): Int { return valves.size } private fun transitions(position: Int, openValves: Set<Int>): List<Transition> { val options = valves[position].tunnels.map { v -> Transition.Move(v) } if (isUseful(position) && !openValves.contains(position)) { return options + listOf(Transition.OpenValve(position)) } return options } fun adjacentStates(state: State): List<State> { val stepComponents = List(state.positions.size) { i -> transitions(state.positions[i], state.openValves) } // println("Step components: $stepComponents") val firstPlayerOptions = stepComponents[0] var stepDescriptions = firstPlayerOptions.map{ listOf(it)} for (playerOptions in stepComponents.drop(1)) { val newStepDescriptions = mutableListOf<List<Transition>>() for (option in playerOptions) { for (stepDescription in stepDescriptions) { newStepDescriptions.add(stepDescription + option) } } stepDescriptions = newStepDescriptions } // println("Step descriptions: $stepDescriptions") val answer = mutableListOf<State>() for (description in stepDescriptions) { val newPositions = description.mapIndexed { i, d -> when(d) { is Transition.OpenValve -> state.positions[i] is Transition.Move -> d.direction } } val newOpenValves = state.openValves + description .filterIsInstance<Transition.OpenValve>().map { d -> d.valve }.toSet() answer.add(State(newPositions, newOpenValves)) } return answer } @Suppress("Unused") fun stateToString(state: State): String { return state.positions.map { it to numbersToNames[it] }.toString() + "-" + state.openValves.map { it to numbersToNames[it] } } } data class State(val positions: List<Int>, val openValves: Set<Int>) fun nextStep(stepData: StepData, valveInfo: ValveInfo): StepData { val next = StepData.create(stepData.totalValves, stepData.usefulValves, stepData.players) for (i in stepData.data.indices) { if (stepData.data[i] > (-1).toShort()) { val state = stepData.unpack(i) // println("Current state: ${valveInfo.stateToString(state)}") val adjacentStates = valveInfo.adjacentStates(state) // println("Adjacent states: ${adjacentStates.map{valveInfo.stateToString(it)}}") for (nextState in adjacentStates) { next[nextState] = max( next[nextState].toInt(), stepData.data[i] + valveInfo.production(state) ).toShort() } } } return next } fun solve(input: List<String>, players: Int, stepCount: Int): Short { val valveInfo = ValveInfo.create(input) val stepZero = StepData.create(valveInfo.totalValves(), valveInfo.usefulValvesCount, players) val startingPositions = List(players) { _ -> valveInfo.startValve } stepZero[State(startingPositions, setOf())] = 0 var currentStep = stepZero repeat(stepCount) { currentStep = nextStep(currentStep, valveInfo) println("$it: ${currentStep.data.max()}") } println() return currentStep.data.max() } fun testEncoding(totalValves: Int, usefulValves: Int, players: Int) { val stepData = StepData.create(totalValves, usefulValves, players) for (i in stepData.data.indices) { val state = stepData.unpack(i) val packedBack = stepData.pack(state) if (packedBack != i) { throw Exception("Encoding problems $i -> $state -> $packedBack") } } } fun main() { println("Day 16 rewritten") val testInput = readInput("Day16-test") val input = readInput("Day16") testEncoding(10, 5, 1) testEncoding(10, 5, 2) // testEncoding(57, 14, 1) // testEncoding(57, 14, 2) println("part 1 test: ${solve(testInput, 1, 30)}") println("part 1 real: ${solve(input, 1, 30)}") println("part 2 test: ${solve(testInput, 2, 26)}") println("part 2 real: ${solve(input, 2, 26)}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
8,165
aoc-2022
Apache License 2.0
src/main/kotlin/name/valery1707/problem/leet/code/BinaryGapK.kt
valery1707
541,970,894
false
null
package name.valery1707.problem.leet.code import kotlin.math.max /** * # 868. Binary Gap * * Given a positive integer `n`, find and return the **longest distance** between any two **adjacent** `1`'s in the *binary representation* of `n`. * If there are no two adjacent `1`'s, return `0`. * * Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). * The **distance** between two `1`'s is the absolute difference between their bit positions. * For example, the two `1`'s in "1001" have a distance of `3`. * * ### Constraints * * `1 <= n <= 10^9` * * @see <a href="https://leetcode.com/problems/binary-gap/">868. Binary Gap</a> */ interface BinaryGapK { fun binaryGap(n: Int): Int @Suppress("EnumEntryName", "unused") enum class Implementation : BinaryGapK { naive { override fun binaryGap(n: Int): Int { var max = 0 var mask = 1 var curr = 0 var prev = -1 while (mask < n) { if (n.and(mask) == mask) { if (prev in 0 until curr) { max = max(curr - prev, max) } prev = curr } mask = mask shl 1 curr++ } return max } }, } }
3
Kotlin
0
0
76d175f36c7b968f3c674864f775257524f34414
1,417
problem-solving
MIT License
src/Day01.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
fun main() { fun parseElves(input: List<String>): List<Int> { return input.fold(mutableListOf(0)) { elves, line -> elves.apply { if (line.isBlank()) add(0) else this[size - 1] += line.toInt() } } } // find the highest-calorie elf fun part1(input: List<String>): Int { return parseElves(input).max() } fun part2(input: List<String>): Int { return parseElves(input).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
f74331778fdd5a563ee43cf7fff042e69de72272
786
advent-of-code-2022
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2021/calendar/day09/Day09.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2021.calendar.day09 import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import javax.inject.Inject import kotlin.Int.Companion.MAX_VALUE typealias Topography = List<List<Int>> class Day09 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun findLowPointSum(fileName: String) = generatorFactory.forFile(fileName).readAs(::heights) { input -> input.toList().findLowPoints().sumOf { it.height + 1 } } fun findLargestBasinProduct(fileName: String) = generatorFactory.forFile(fileName).readAs(::heights) { input -> val floor = input.toList() val minLocations = floor.findLowPoints() val basins = minLocations.map { (value, y, x) -> val initialLocation = Location(value, y, x) val spacesInBasin = mutableSetOf(initialLocation) val spacesToExplore = mutableSetOf<Location>().apply { addAll(initialLocation.generateExploringNeighbors()) } while(spacesToExplore.isNotEmpty()) { val spaceToExplore = spacesToExplore.first().also { spacesToExplore.remove(it) } val valueOfMe = floor.findHeight(spaceToExplore.y, spaceToExplore.x) if (valueOfMe in (spaceToExplore.height + 1)..8) { val exploredLocation = Location(valueOfMe, spaceToExplore.y, spaceToExplore.x) spacesInBasin.add(exploredLocation) spacesToExplore.addAll(exploredLocation.generateExploringNeighbors()) } } spacesInBasin } basins.sortedByDescending { it.size } .take(3) .map { it.size } .reduce(Int::times) } private fun heights(line: String) = line.map(Character::getNumericValue) private fun Topography.findLowPoints(): List<Location> { val minLocations = mutableListOf<Location>() repeat(this[0].size) { x -> repeat(this.size) { y -> val me = this[y][x] val myLocation = Location(me, y, x) val neighbors = myLocation.generateExploringNeighbors().map { findHeight(it.y, it.x) } if (neighbors.all { me < it }) { minLocations.add(myLocation) } } } return minLocations } private fun Topography.findHeight(y: Int, x: Int) = if (y in (0 until size) && x in (0 until this[y].size)) { this[y][x] } else { MAX_VALUE } private data class Location(val height: Int, val y: Int, val x: Int) { fun generateExploringNeighbors() = setOf( Location(height, y - 1, x), Location(height, y + 1, x), Location(height, y, x - 1), Location(height, y, x + 1) ) } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,584
advent-of-code
MIT License
src/2022/Day23.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import common.Linearizer import common.Offset import common.* import java.io.File import java.util.* fun main() { Day23().solve() } class Day23 { val input1 = """ ....#.. ..###.# #...#.# .#...## #.###.. ##.#.## .#..#.. """.trimIndent() val input2 = """ ..... ..##. ..#.. ..... ..##. ..... """.trimIndent() data class Rule(val check: List<Offset>, val thenDo: Offset) class Offsets(val l: Linearizer) { fun get(dir: String): Offset { return when (dir) { "N" -> l.offset(0, -1) "NE" -> l.offset(1, -1) "NW" -> l.offset(-1, -1) "W" -> l.offset(-1, 0) "E" -> l.offset(1, 0) "S" -> l.offset(0, 1) "SE" -> l.offset(1, 1) "SW" -> l.offset(-1, 1) else -> throw RuntimeException() } } fun get(dir: List<String>): List<Offset> { return dir.map{get(it)} } fun rule(check: List<String>, apply: String): Rule { return Rule(get(check), get(apply)) } } fun ranges(elves: Set<Int>, l: Linearizer): Pair<IntRange, IntRange> { val min = l.toCoordinates(elves.first()) val max = l.toCoordinates(elves.first()) for (e in elves) { val xy = l.toCoordinates(e) for (i in 0..1) { if (xy[i] < min[i]) { min[i] = xy[i] } if (xy[i] > max[i]) { max[i] = xy[i] } } } return min[0]..max[0] to min[1]..max[1] } fun render(elves: Set<Int>, l: Linearizer): String { val sb = StringBuilder() val ranges = ranges(elves, l) sb.appendLine(ranges.toString()) for (y in ranges.second) { for (x in ranges.first) { if (elves.contains(l.toIndex(x,y))) { sb.append("#") } else { sb.append(".") } } sb.appendLine() } return sb.toString() } fun emptyTiles(elves: Set<Int>, l: Linearizer): Int { val ranges = ranges(elves, l) var emptyTiles = 0 for (y in ranges.second) { for (x in ranges.first) { if (!elves.contains(l.toIndex(x,y))) { ++emptyTiles } } } return emptyTiles } fun spread(elves: Set<Int>, startRule: Int, rules: List<Rule>, allAdjacent: List<Offset>, l: Linearizer): Pair<Set<Int>, Boolean> { val oldToNewPos = mutableMapOf<Int, Int>() val newToOldPos = mutableMapOf<Int, Int>() val conflicting = mutableSetOf<Int>() for (e in elves) { var e1 = e if (allAdjacent.around(e).any{elves.contains(it)}) { for (i in 0..3) { val rix = (i + startRule) % 4 val rule = rules[rix] if (rule.check.around(e).all { !elves.contains(it) }) { e1 = rule.thenDo.apply(e)!! break } } } oldToNewPos[e] = e1 if (newToOldPos.contains(e1)) { conflicting.add(e) conflicting.add(newToOldPos[e1]!!) } newToOldPos[e1] = e } var updated = false val elves1 = elves.map{ if (conflicting.contains(it)) { it } else { val newPos = oldToNewPos[it]!! if (newPos != it) { updated = true } newPos } }.toSet() return elves1 to updated } fun solve() { val startOffset = 1000 val dimension = 2000 val f = File("src/2022/inputs/day23.in") val s = Scanner(f) // val s = Scanner(input1) val l = Linearizer(dimension, dimension) val o = Offsets(l) val allAdjacent = o.get(listOf("NW", "N", "NE", "W", "E", "SW", "S", "SE")) val rules = listOf( o.rule(listOf("N", "NE", "NW"), "N"), o.rule(listOf("S", "SE", "SW"), "S"), o.rule(listOf("W", "NW", "SW"), "W"), o.rule(listOf("E", "NE", "SE"), "E") ) val elves = mutableSetOf<Int>() var y0 = 0 while (s.hasNextLine()) { val line = s.nextLine().trim() for (x0 in 0 until line.length) { if (line[x0] == '#') { elves.add(l.toIndex(x0 + startOffset, y0 + startOffset)) } } ++y0 } var ruleIx = 0 var round = 1 var r = spread(elves, ruleIx, rules, allAdjacent, l) // while (r.second && round<11) { while (r.second) { ++ruleIx println("After round ${round++}") println(render(r.first, l)) println(emptyTiles(r.first, l)) r = spread(r.first, ruleIx, rules, allAdjacent, l) } println(render(r.first, l)) } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
5,446
advent-of-code
Apache License 2.0
src/Day04.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
// Advent of Code 2022, Day 04, Camp Cleanup fun main() { fun part1(input: List<String>): Int { var total = 0 input.forEach { line -> val ass = line.split(",", "-").map { it.toInt() } if ((ass[0] <= ass[2] && ass[1] >= ass[3]) || (ass[0] >= ass[2] && ass[1] <= ass[3])) { total++ } } return total } fun part2(input: List<String>): Int { var total = 0 input.forEach { line -> val ass = line.split(",", "-").map { it.toInt() } if (ass[2] <= ass[1] && ass[3] >= ass[0]) { total++ } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
959
AdventOfCode2022
Apache License 2.0
core/src/main/kotlin/edu/umontreal/kotlingrad/typelevel/TypeClassing.kt
ileasile
390,895,055
true
{"Kotlin": 134062, "Java": 21933}
@file:Suppress("NonAsciiCharacters") package edu.umontreal.kotlingrad.typelevel import kotlin.math.roundToInt /** Corecursive Fibonacci sequence of [Nat]s **/ tailrec fun <T> Nat<T>.fibonacci( n: T, seed: Pair<T, T> = nil to one, fib: (Pair<T, T>) -> Pair<T, T> = { (a, b) -> b to a + b }, i: T = nil, ): T = if (i == n) fib(seed).first else fibonacci(n = n, seed = fib(seed), i = i.next()) /** Returns [n]! **/ fun <T> Nat<T>.factorial(n: T): T = prod(seq(to = n.next())) /** Returns a sequence of [Nat]s starting from [from] until [to] **/ tailrec fun <T> Nat<T>.seq( from: T = one, to: T, acc: Set<T> = emptySet() ): Set<T> = if (from == to) acc else seq(from.next(), to, acc + from) /** Returns true iff [t] is prime **/ fun <T> Nat<T>.isPrime(t: T, kps: Set<T> = emptySet()): Boolean = // Take Cartesian product, filter distinct pairs due to commutativity (if (kps.isNotEmpty()) kps * kps else seq(to = t) * seq(to = t)) .distinctBy { (l, r) -> setOf(l, r) } .all { (i, j) -> if (i == one || j == one) true else i * j != t } /** Returns [total] prime [Nat]s **/ tailrec fun <T> Nat<T>.primes( total: T, // total number of primes i: T = nil, // counter c: T = one.next(), // prime candidate kps: Set<T> = emptySet() // known primes ): Set<T> = when { i == total -> kps isPrime(c) -> primes(total, i.next(), c.next(), kps + c) else -> primes(total, i, c.next(), kps) } // Returns the Cartesian product of two sets operator fun <T> Set<T>.times(s: Set<T>) = flatMap { l -> s.map { r -> l to r }.toSet() }.toSet() /** Returns the sum of two [Nat]s **/ tailrec fun <T> Nat<T>.plus(l: T, r: T, acc: T = l, i: T = nil): T = if (i == r) acc else plus(l, r, acc.next(), i.next()) /** Returns the product of two [Nat]s **/ tailrec fun <T> Nat<T>.times(l: T, r: T, acc: T = nil, i: T = nil): T = if (i == r) acc else times(l, r, acc + l, i.next()) tailrec fun <T> Nat<T>.pow(base: T, exp: T, acc: T = one, i: T = one): T = if (i == exp) acc else pow(base, exp, acc * base, i.next()) fun <T> Nat<T>.sum(list: Iterable<T>): T = list.reduce { acc, t -> acc + t } fun <T> Nat<T>.prod(list: Iterable<T>): T = list.reduce { acc, t -> (acc * t) } interface Nat<T> { val nil: T val one: T get() = nil.next() fun T.next(): T operator fun T.plus(t: T) = plus(this, t) operator fun T.times(t: T) = times(this, t) infix fun T.pow(t: T) = pow(this, t) companion object { operator fun <T> invoke(nil: T, next: T.() -> T): Nat<T> = object: Nat<T> { override val nil: T = nil override fun T.next(): T = next() } } } interface Group<T>: Nat<T> { override fun T.next(): T = this + one override fun T.plus(t: T): T companion object { operator fun <T> invoke(nil: T, one: T, plus: (T, T) -> T): Group<T> = object: Group<T> { override fun T.plus(t: T) = plus(this, t) override val nil: T = nil override val one: T = one } } } interface Ring<T>: Group<T> { override fun T.plus(t: T): T override fun T.times(t: T): T companion object { operator fun <T> invoke( nil: T, one: T, plus: (T, T) -> T, times: (T, T) -> T ): Ring<T> = object: Ring<T> { override fun T.plus(t: T) = plus(this, t) override fun T.times(t: T) = times(this, t) override val nil: T = nil override val one: T = one } } } @Suppress("NO_TAIL_CALLS_FOUND") /** Returns the result of subtracting two [Field]s **/ tailrec fun <T> Field<T>.minus(l: T, r: T, acc: T = nil, i: T = nil): T = TODO() @Suppress("NO_TAIL_CALLS_FOUND") /** Returns the result of dividing of two [Field]s **/ tailrec fun <T> Field<T>.div(l: T, r: T, acc: T = l, i: T = nil): T = TODO() interface Field<T>: Ring<T> { operator fun T.minus(t: T): T = minus(this, t) operator fun T.div(t: T): T = div(this, t) companion object { operator fun <T> invoke( nil: T, one: T, plus: (T, T) -> T, times: (T, T) -> T, minus: (T, T) -> T, div: (T, T) -> T ): Field<T> = object: Field<T> { override fun T.plus(t: T) = plus(this, t) override fun T.times(t: T) = times(this, t) override fun T.minus(t: T) = minus(this, t) override fun T.div(t: T) = div(this, t) override val nil: T = nil override val one: T = one } } } interface Vector<T> { val ts: List<T> fun vmap(map: (T) -> T) = Vector(ts.map { map(it) }) fun zip(other: Vector<T>, merge: (T, T) -> T) = Vector(ts.zip(other.ts).map { (a, b) -> merge(a, b) }) companion object { operator fun <T> invoke(vararg ts: T): Vector<T> = invoke(ts.toList()) operator fun <T> invoke(ts: List<T>): Vector<T> = object: Vector<T> { override val ts: List<T> = ts override fun toString() = ts.joinToString(",", "${ts.javaClass.simpleName}[", "]") } } } interface VectorField<T, V: Vector<T>, F: Field<T>> { val v: V val f: F operator fun Vector<T>.plus(vec: Vector<T>): Vector<T> = zip(vec) { a, b -> f.plus(a, b) } infix fun T.dot(p: Vector<T>): Vector<T> = p.vmap { f.times(it, this) } companion object { operator fun <T, F: Field<T>> invoke(v: Vector<T> = Vector(), f: F) = object: VectorField<T, Vector<T>, F> { override val v: Vector<T> get() = v override val f: F get() = f } } } // http://www.math.ucsd.edu/~alina/oldcourses/2012/104b/zi.pdf data class GaussInt(val a: Int, val b: Int) { operator fun plus(o: GaussInt): GaussInt = GaussInt(a + o.a, b + o.b) operator fun times(o: GaussInt): GaussInt = GaussInt(a * o.a - b * o.b, a * o.b + b * o.a) } class Rational { constructor(i: Int, j: Int = 1) { if (j == 0) throw ArithmeticException("Denominator must not be zero!") canonicalRatio = reduce(i, j) a = canonicalRatio.first b = canonicalRatio.second } private val canonicalRatio: Pair<Int, Int> val a: Int val b: Int operator fun times(r: Rational) = Rational(a * r.a, b * r.b) operator fun plus(r: Rational) = Rational(a * r.b + r.a * b, b * r.b) operator fun minus(r: Rational) = Rational(a * r.b - r.a * b, b * r.b) operator fun div(r: Rational) = Rational(a * r.b, b * r.a) override fun toString() = "$a/$b" override fun equals(other: Any?) = (other as? Rational).let { a == it!!.a && b == it.b } override fun hashCode() = toString().hashCode() companion object { val ZERO = Rational(0, 1) val ONE = Rational(1, 1) fun reduce(a: Int, b: Int) = Pair( (a.toFloat() / a.gcd(b).toFloat()).roundToInt(), (b.toFloat() / a.gcd(b).toFloat()).roundToInt() ) private tailrec fun Int.gcd(that: Int): Int = when { this == that -> this this in 0..1 || that in 0..1 -> 1 this > that -> (this - that).gcd(that) else -> gcd(that - this) } } }
0
null
0
0
56a6d4d03544db1bcaa93c31ffc7e075bc564e64
6,867
kotlingrad
Apache License 2.0
2022/src/main/kotlin/day25.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Graph import utils.Parser import utils.Solution import utils.Vec2i import utils.badInput import utils.mapParser fun main() { Day25.run(skipPart2 = true) } object Day25 : Solution<List<String>>() { override val name = "day25" override val parser = Parser.lines private fun parseSnafuNumber(s: String): Long { return s.reversed().map { when (it) { '2' -> 2L '1' -> 1L '0' -> 0L '-' -> -1L '=' -> -2L else -> badInput() } }.foldRight(0) { n, acc -> acc * 5L + n } } private fun toSnafuNumber(number: Long): String { if (number == 0L) return "0" return buildString { var num = number while (num != 0L) { val bit = num % 5L if (bit == 3L) { append("=") num += 5 } else if (bit == 4L) { append("-") num += 5 } else { append(bit.toString()) } num /= 5L } }.reversed() } override fun part1(input: List<String>): String { val sum = input.sumOf { parseSnafuNumber(it) } return toSnafuNumber(sum) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,130
aoc_kotlin
MIT License
kotlin/src/katas/kotlin/leetcode/longest_substring_palindrome/LongestPalindromeTests.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
@file:Suppress("DuplicatedCode", "unused") package katas.kotlin.leetcode.longest_substring_palindrome import nonstdlib.measureDuration import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/longest-palindromic-substring */ class LongestPalindromeTests { @Test fun `trivial examples`() { findLongestPalindrome("") shouldEqual "" findLongestPalindrome("a") shouldEqual "a" findLongestPalindrome("b") shouldEqual "b" findLongestPalindrome("c") shouldEqual "c" } @Test fun `match at the beginning of the string`() { findLongestPalindrome("abc") shouldEqual "a" findLongestPalindrome("aabc") shouldEqual "aa" findLongestPalindrome("ababc") shouldEqual "aba" } @Test fun `match in the middle of the string`() { findLongestPalindrome("abbc") shouldEqual "bb" findLongestPalindrome("aabbbc") shouldEqual "bbb" findLongestPalindrome("abaabc") shouldEqual "baab" } @Test fun `match at the end of the string`() { findLongestPalindrome("abcc") shouldEqual "cc" findLongestPalindrome("abaab") shouldEqual "baab" } @Test fun `match long palindrome`() { findLongestPalindrome(longPalindrome) shouldEqual longPalindrome } } private val chars = (0..100_000).map { it.toChar() } private val longChars = chars.joinToString("") private val longPalindrome = chars .let { chars -> (chars + chars.reversed()).joinToString("") } class PalindromeTests { @Test fun `check that string is a palindrome`() { "".isPalindrome() shouldEqual true "a".isPalindrome() shouldEqual true "ab".isPalindrome() shouldEqual false "aba".isPalindrome() shouldEqual true "abba".isPalindrome() shouldEqual true "abcba".isPalindrome() shouldEqual true "abccba".isPalindrome() shouldEqual true "abcba_".isPalindrome() shouldEqual false } @Test fun `check that long string is a palindrome`() { measureDuration { longPalindrome.isPalindrome() shouldEqual true } } } private fun findLongestPalindrome(s: String): String { val map = HashMap<Char, MutableList<Int>>() (0 until s.length).forEach { i -> map.getOrPut(s[i], { ArrayList() }).add(i) } var result = "" (0 until s.length).forEach { i -> println(i) if (s.length - i <= result.length) return result val nextIndices = map[s[i]]!! for (j in nextIndices.asReversed()) { val substringLength = j + 1 - i if (j < i || substringLength <= result.length) break val substring = s.subSequence(i, j + 1) if (substring.length > result.length && substring.isPalindrome()) { result = s.substring(i, j + 1) } } } return result } private fun CharSequence.isPalindrome(): Boolean { if (length <= 1) return true var i = 0 var j = length - 1 while (i <= j) { if (this[i] != this[j]) return false i++ j-- } return true } private fun findLongestPalindrome_func(s: String): String { return (0..s.length) .flatMap { start -> (start..s.length).map { end -> start..end } } .map { range -> s.substring(range.first, range.last) } .filter { it.isPalindrome() } .fold("") { acc, it -> if (it.length > acc.length) it else acc } } private fun String.isPalindrome_(): Boolean { if (length <= 1) return true var i = 0 var j = length - 1 while (i <= j) { if (this[i] != this[j]) return false i++ j-- } return true }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,694
katas
The Unlicense
src/iii_conventions/MyDate.kt
edwardz10
136,737,762
false
{"Kotlin": 75614, "Java": 4952}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { val compareYears = year.compareTo(other.year) val compareMonths = month.compareTo(other.month) val compareDays = dayOfMonth.compareTo(other.dayOfMonth) return if (compareYears == 0) if (compareMonths == 0) compareDays else compareMonths else compareYears } val daysInMonth = when(this.month){ 0 -> 31 1 -> 28 2 -> 31 3 -> 30 4 -> 31 5 -> 30 6 -> 31 7 -> 31 8 ->30 9 -> 31 10 -> 30 else -> 31 } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(timeInterval: TimeInterval) : MyDate { return when(timeInterval) { TimeInterval.DAY -> { if (daysInMonth == dayOfMonth) { MyDate(year, month + 1, 1) } else { MyDate(year, month, dayOfMonth + 1) } } TimeInterval.WEEK -> { if (daysInMonth < dayOfMonth + 7) { MyDate(year, month + 1, 7 - (daysInMonth - dayOfMonth)) } else { MyDate(year, month, dayOfMonth + 7) } } TimeInterval.YEAR -> MyDate(year + 1, month, dayOfMonth) } } operator fun MyDate.plus(repeatedTimeInterval: RepeatedTimeInterval) : MyDate { return when(repeatedTimeInterval.ti) { TimeInterval.DAY -> { var date = this for (i in 0 .. repeatedTimeInterval.n - 1) { date = date + TimeInterval.DAY } return date } TimeInterval.WEEK -> { var date = this for (i in 0 .. repeatedTimeInterval.n - 1) { date = date + TimeInterval.WEEK } return date } TimeInterval.YEAR -> MyDate(this.year + repeatedTimeInterval.n, this.month, this.dayOfMonth) } } operator fun TimeInterval.times(n: Int) : RepeatedTimeInterval { return RepeatedTimeInterval(this, n) } data class RepeatedTimeInterval(val ti: TimeInterval, val n: Int) enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { override fun iterator(): Iterator<MyDate> { return DateIterator(start, endInclusive) } operator fun contains(d: MyDate) : Boolean { return d >= start && d <= endInclusive } } class DateIterator(val start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> { var current = start override fun hasNext(): Boolean { return current <= endInclusive } override fun next(): MyDate { return current.apply { current = current.nextDay() } } }
0
Kotlin
0
0
446d349a459b8624a7da9469b618eea7df3f5cba
2,933
kotlin-koans-completed
MIT License
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day17.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2022 import com.dvdmunckhof.aoc.common.MutableBitSet import com.dvdmunckhof.aoc.common.Point class Day17(input: String, shapesInput: String) { private val directions = input.map { c -> Direction.values().first { it.c == c } } private val rocks = shapesInput.split("\n\n").map { block -> parseRock(block.lines()) } fun solvePart1() = solve(2022) fun solvePart2() = solve(1_000_000_000_000L) private fun solve(targetStep: Long): Long { val cave = Cave(7) var step = 0 val states = mutableMapOf<State, Pair<Int, Int>>() while (true) { val rock = rocks[step++ % rocks.size] cave.dropRock(rock) val state = cave.state() if (state !in states) { states[state] = step to cave.height continue } val (prefixStep, prefixHeight) = states.getValue(state) val patternSteps = step - prefixStep val patternHeight = cave.height - prefixHeight val remainingSteps = targetStep - step if (remainingSteps % patternSteps == 0L) { val patternCount = remainingSteps / patternSteps return cave.height + patternCount * patternHeight } } } private inner class Cave(val width: Int) { private val grid = mutableListOf<MutableBitSet>() private var directionIndex = -1 val height: Int get() = grid.size fun dropRock(rock: Rock) { val startPosition = Point(this.height + 3, 2) val position = dropRockDirection(rock, startPosition, false) for (offset in rock.points) { this.set(position.r + offset.r, position.c + offset.c) } } private fun dropRockDirection(rock: Rock, position: Point, down: Boolean): Point { val direction = if (down) { Direction.DOWN } else { directionIndex = (directionIndex + 1) % directions.size directions[directionIndex] } val positionNew = position + direction.offset return if (isValidPosition(rock, positionNew)) { dropRockDirection(rock, positionNew, !down) } else if (!down) { dropRockDirection(rock, position, true) } else { position } } private fun isValidPosition(rock: Rock, position: Point): Boolean { if (position.r < 0 || position.c < 0 || position.c + rock.width > this.width) { return false } return rock.points.none { offset -> this.get(position.r + offset.r, position.c + offset.c) } } private fun get(r: Int, c: Int): Boolean { return if (r < grid.size) grid[r][c] else false } private fun set(r: Int, c: Int) { while (grid.lastIndex < r) { grid += MutableBitSet() } grid[r][c] = true } fun state(): State { val hash = grid.takeLast(2).foldIndexed(0L) { i, acc, bitSet -> acc or (bitSet.value shl (i * width)) } return State(this.directionIndex, hash) } } private fun parseRock(lines: List<String>): Rock { val points = lines .reversed() .flatMapIndexed { r, line -> line.mapIndexedNotNull { c, char -> if (char == '#') Point(r, c) else null } } return Rock(points, lines.first().length, lines.size) } private data class Rock(val points: List<Point>, val width: Int, val height: Int) private enum class Direction(val c: Char, val offset: Point) { LEFT('<', Point(0, -1)), RIGHT('>', Point(0, 1)), DOWN('>', Point(-1, 0)), } private data class State(val direction: Int, val gridHash: Long) }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
4,004
advent-of-code
Apache License 2.0
LeetCode/0435. Non overlapping Intervals/Solution.kt
InnoFang
86,413,001
false
{"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410}
/** * Created by <NAME> on 2018/1/31. */ class Interval( var start: Int = 0, var end: Int = 0 ) /** * Dynamic Programming 动态规划 * 将应该删去多少个区间,转化为最大的不重叠区间是几个 * 这样要求应该删去多少个区间,就可以用 区间个数 - 最大连续区间数 得到 * 类似于最长上升子序列问题 LIS * * 18 / 18 test cases passed. * Runtime: 1651 ms */ class Solution { fun eraseOverlapIntervals(intervals: Array<Interval>): Int { if (intervals.isEmpty()) return 0 // 先对区间进行排序 // 规则:按区间开始位置排序 // 1. 若区间开始位置不同,则哪个区间开始位置在前,哪个区间在前 // 2. 若区间开始位置相同,则哪个区间的结束位置在前,哪个区间 intervals.sortWith(Comparator { o1, o2 -> if (o1.start != o2.start) o1.start - o2.start else o1.end - o2.end }) // 保存每个区间位置之前有多少个不重叠区间 val dp = MutableList(intervals.size, { 1 }) // 对区间进行遍历 (1 until intervals.size).forEach { i -> (0 until i).forEach { j -> if (intervals[i].start >= intervals[j].end) dp[i] = maxOf(dp[i], 1 + dp[j]) } } // 应删去的区间数 = 区间总数 - 最大的不重叠区间数 return intervals.size - dp.max()!! } } /** * Greedy 贪心算法 * 将应该删去多少个区间,转化为最大的不重叠区间是几个 * 这样要求应该删去多少个区间,就可以用 区间个数 - 最大连续区间数 得到 * * 18 / 18 test cases passed. * Runtime: 423 ms */ class Solution2 { fun eraseOverlapIntervals(intervals: Array<Interval>): Int { if (intervals.isEmpty()) return 0 // 先对区间进行排序 // 规则:按区间结束位置排序 // 1. 若区间结束位置不同,则哪个区间开始位置在前,哪个区间在前 // 2. 若区间结束位置相同,则哪个区间的结束位置在前,哪个区间 intervals.sortWith(Comparator { o1, o2 -> if (o1.end != o2.end) o1.end - o2.end else o1.start - o2.start }) var res = 1 var pre = 0 (1 until intervals.size).forEach { if (intervals[it].start >= intervals[pre].end) { res++; pre = it } } return intervals.size - res } } fun main(args: Array<String>) { Solution2().eraseOverlapIntervals(arrayOf(Interval(1, 2))).let(::println) // 0 Solution2().eraseOverlapIntervals(arrayOf( Interval(1, 2), Interval(2, 3), Interval(3, 4), Interval(1, 3) )).let(::println) // 1 Solution2().eraseOverlapIntervals(arrayOf( Interval(1, 2), Interval(1, 2), Interval(1, 2) )).let(::println) // 2 Solution2().eraseOverlapIntervals(arrayOf( Interval(1, 2), Interval(2, 3) )).let(::println) // 0 }
0
C++
8
20
2419a7d720bea1fd6ff3b75c38342a0ace18b205
3,178
algo-set
Apache License 2.0
advent_of_code/2018/solutions/day_12_b.kt
migafgarcia
63,630,233
false
{"C++": 121354, "Kotlin": 38202, "C": 34840, "Java": 23043, "C#": 10596, "Python": 8343}
import java.io.File // 2463 fun main(args: Array<String>) { assert(score(".#....##....#####...#######....#.#..##.", 3) == 325) val regex = Regex(".* => .*") val margin = 3 val lines = File(args[0]).readLines() var leftPots = 0 var state = StringBuilder(lines[0].split(":")[1].trim()) val transitions = lines.filter { it.matches(regex) }.map { line -> val split = line.split("=>") Pair(split[0].trim(), split[1].trim()[0]) }.toMap() println("0 -> $state") for (gen in 1..20) { val leftEmptyPots = CharArray(maxOf(margin - state.indexOf('#'), 0)) { '.' } state.insert(0, leftEmptyPots) leftPots += leftEmptyPots.size val rightEmptyPots = CharArray(maxOf(margin - (state.length - state.lastIndexOf('#')), 0) + 1) { '.' } state.append(rightEmptyPots) val nextState = StringBuilder(state) transitions.forEach { t, u -> var patternIndex = state.indexOf(t, 0) while (patternIndex != -1) { nextState[patternIndex + 2] = u patternIndex = state.indexOf(t, patternIndex + 1) } } state = nextState println("$gen -> $state") } val sum = score(state.toString(), leftPots) println(sum) } private fun score(state: String, leftPots: Int): Int = (0 until state.length) .filter { state[it] == '#' } .sumBy { it - leftPots }
0
C++
3
9
82f5e482c0c3c03fd39e46aa70cab79391ed2dc5
1,468
programming-challenges
MIT License
src/Day08.kt
diego09310
576,378,549
false
{"Kotlin": 28768}
fun main() { fun part1(input: List<String>): Int { val map: MutableList<List<Int>> = mutableListOf() input.forEach{ line -> map.add(line.toCharArray().map{it.digitToInt()})} var v = 0 for (i in map.indices) { for (j in map[0].indices) { if (i == 0 || j == 0 || i == map.size-1 || j == map[0].size-1) { v++ continue } val height = map[i][j] val visible = arrayOf(true, true, true, true) for (k in 0 until i) { if (map[k][j] >= height) { visible[0] = false break } } for (k in i+1 until map.size) { if (map[k][j] >= height) { visible[1] = false break } } for (k in 0 until j) { if (map[i][k] >= height) { visible[2] = false break } } for (k in j+1 until map[0].size) { if (map[i][k] >= height) { visible[3] = false break } } if (visible.any{it}) { v++ } } } return v } fun part2(input: List<String>): Int { val map: MutableList<List<Int>> = mutableListOf() input.forEach{ line -> map.add(line.toCharArray().map{it.digitToInt()})} val score = Array(map.size) { Array(map[0].size) {0} } for (i in map.indices) { for (j in map[0].indices) { if (i == 0 || j == 0 || i == map.size-1 || j == map[0].size-1) { continue } val height = map[i][j] var d1 = 0 for (k in i-1 downTo 0) { d1++ if (map[k][j] >= height) { break } } var d2 = 0 for (k in i+1 until map.size) { d2++ if (map[k][j] >= height) { break } } var d3 = 0 for (k in j-1 downTo 0) { d3++ if (map[i][k] >= height) { break } } var d4 = 0 for (k in j+1 until map[0].size) { d4++ if (map[i][k] >= height) { break } } score[i][j] = d1 * d2 * d3 * d4 } } return score.maxOf { it.max() } } // test if implementation meets criteria from the description, like: val testInput = readInput("../../8linput") check(part1(testInput) == 21) val input = readInput("../../8input") println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
644fee9237c01754fc1a04fef949a76b057a03fc
3,236
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc2023/day2/day2Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day2 import lib.* suspend fun main() { setupChallenge().solveChallenge() } val baseCubeCount = mapOf(Pair("red", 0), Pair("green", 0), Pair("blue", 0)) fun setupChallenge(): Challenge<List<List<List<String>>>> { return setup { day(2) year(2023) parser { it.readLines() .map { it.split(": ").last() } .map { it.split("; ").map { it.split(", ") } } } partOne { val limits = mapOf(Pair("red", 12), Pair("green", 13), Pair("blue", 14)) it.mapIndexed { index, rounds -> val cubesPerRound = rounds.map { it.getCubes() } val maxCubes = cubesPerRound.fold(baseCubeCount) { current, other -> current.mapValues { entry -> maxOf(entry.value, other[entry.key]!!)} } if (maxCubes.all { limits[it.key]!! >= it.value }) index + 1 else 0 } .sum() .toString() } partTwo { it.map { rounds -> val cubesPerRound = rounds.map { it.getCubes() } val maxCubes = cubesPerRound.fold(baseCubeCount) { current, other -> current.mapValues { entry -> maxOf(entry.value, other[entry.key]!!)} } maxCubes.values.fold(1L) { n, i -> n * i } } .sum() .toString() } } } fun List<String>.getCubes(): Map<String, Int> { val res = baseCubeCount.toMutableMap() this.forEach { val parts = it.split(" ") val number = parts[0].toInt() val colour = parts[1] if (number > res[colour]!!) { res[colour] = number } } return res }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
1,752
AoC-2023-DDJ
MIT License
Aoe/src/Principal.kt
aranzabe
403,376,804
false
{"Kotlin": 57514, "Java": 269}
import Factoria.factoriaAldeano import Factoria.factoriaCivilizacion import kotlin.random.Random fun asignacionAldeano(): Int { var cod = 0 val alea = Random.nextInt(0, 100) if (alea < 40) { cod = 1 } else if (alea < 60) { cod = 2 } return cod } fun extraerRecursos(m: Mina, civ: Civilizacion): Int { var recursosExtraidos = 0 for (i in 0 .. m.cuantosCurrantesTotal()-1) { if (m.getMineros(i) != null) { var al:Aldeano = m.getMineros(i) if (al.civ.nombre.equals(civ.nombre)) { if (m.hayMineral()) { m.items = m.items - 1 when (m.tipo) { "ORO" -> civ.almacenOro = civ.almacenOro + 1 "PIEDRA" -> civ.almacenPiedra = civ.almacenPiedra + 1 } recursosExtraidos++ } } } } return recursosExtraidos } fun wololo(m: Mina, esp: Civilizacion, biz: Civilizacion): Boolean { var conseguido = false while (!conseguido && m.cuantosMineros(esp) > 0) { val alea = Random.nextInt(0, m.cuantosCurrantesTotal()) if (m.getMineros(alea) != null && m.getMineros(alea).civ.equals(esp)) { m.getMineros(alea).civ = biz conseguido = true } } return conseguido } fun main(args: Array<String>) { var t: Int var codAld: Int val esp = Factoria.factoriaCivilizacion(Tipos.Español) val biz = Factoria.factoriaCivilizacion(Tipos.Bizantino) var ald: Aldeano val mina:Mina = Mina() println(esp) println(biz) t = 0 while (t < 60) { //Los aldeanos se unen a la mina if (t % 2 == 0) { codAld = asignacionAldeano() when (codAld) { 1 -> { ald = factoriaAldeano(200, esp) esp.addAldeano(ald) mina.addAldeano(ald) println("Se ha añadido un aldeano del Imperio Español a la mina") } 2 -> { ald = factoriaAldeano(250, biz) biz.addAldeano(ald) mina.addAldeano(ald) println("Se ha añadido un aldeano del Imperio Bizantino a la mina") } } } //Los aldeanos pican recursos println("El Imperio Español ha extraído " + extraerRecursos(mina, esp) + " items de " + mina.tipo) println("El Imperio Bizantino ha extraído " + extraerRecursos(mina, biz) + " items de " + mina.tipo) //Ataque del cura bizantino if (t % 5 == 0) { if (wololo(mina, esp, biz)) { println("Un cura bizantino ha convertido a uno de los mineros españoles") } } println("Estado de la partida:") println(esp) println(biz) Thread.sleep(1000) t++ } println("Fin de la simulación.") }
0
Kotlin
0
0
d287547ea6cacc644802713a3fd514fa333613a4
3,004
kotlin
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day02.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution fun main() = Day02.solve() object Day02 : AdventSolution(2020, 2, "Password Philosophy") { override fun solvePartOne(input: String) = input .lineSequence() .map(::parse) .count { (ch, l, h, pwd) -> pwd.count { it == ch } in l..h } override fun solvePartTwo(input: String) = input .lineSequence() .map(::parse) .count { (ch, l, h, pwd) -> (pwd[l - 1] == ch) xor (pwd[h - 1] == ch) } private val regex = """(\d+)-(\d+) (.): (.+)""".toRegex() private fun parse(input: String): Policy { val (low, high, character, password) = regex.matchEntire(input)!!.destructured return Policy(character[0], low.toInt(), high.toInt(), password) } private data class Policy(val ch: Char, val l: Int, val h: Int, val pwd: String) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
876
advent-of-code
MIT License
src/adventofcode/blueschu/y2017/day16/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day16 import adventofcode.blueschu.y2017.day10.rotate import java.io.File import kotlin.test.assertEquals val input: List<String> by lazy { File("resources/y2017/day16.txt") .bufferedReader() .use { r -> r.readText().trim() } .split(',') } fun main(args: Array<String>) { assertEquals("baedc", part1(listOf("s1", "x3/4", "pe/b"), floorSize = 5)) println("Part 1: ${part1(input)}") part2(listOf("s1", "x3/4", "pe/b"), floorSize = 5) println("Part 2: ${part2(input)}") } sealed class DanceMove data class Spin(val mag: Int) : DanceMove() data class Exchange(val posA: Int, val posB: Int) : DanceMove() data class Partner(val dancerA: Char, val dancerB: Char) : DanceMove() fun parseDanceMove(token: String): DanceMove { val move = token[0] val components = token.slice(1 until token.length).split('/') return when (move) { 's' -> Spin(components[0].toInt()) 'x' -> Exchange(components[0].toInt(), components[1].toInt()) 'p' -> Partner(components[0].first(), components[1].first()) else -> throw IllegalArgumentException("Dance move could not be parsed: $token") } } class DanceFloor(floorSize: Int, charGen: CharIterator) { constructor(floorSize: Int = 16, charRange: CharRange = 'a'..'p') : this(floorSize, charRange.iterator()) val dancers = Array(floorSize) { charGen.nextChar() } fun runMove(danceMove: DanceMove) { when (danceMove) { is Spin -> dancers.rotate(danceMove.mag) is Exchange -> exchangeDancers(danceMove.posA, danceMove.posB) is Partner -> exchangeDancers( dancers.indexOf(danceMove.dancerA), dancers.indexOf(danceMove.dancerB) ) } } private fun exchangeDancers(posA: Int, posB: Int) { if (posA !in 0 until dancers.size || posB !in 0 until dancers.size) { throw IllegalArgumentException("Illegal position exchange: $posA <=> $posB") } val tmp = dancers[posA] dancers[posA] = dancers[posB] dancers[posB] = tmp } override fun toString() = dancers.joinToString(separator = "") } fun part1(moveStrings: List<String>, floorSize: Int = 16): String { val moves = moveStrings.map { parseDanceMove(it) } return DanceFloor(floorSize).also { floor -> moves.forEach { move -> floor.runMove(move) } }.toString() } fun part2(moveStrings: List<String>, floorSize: Int = 16): String { val moves = moveStrings.map { parseDanceMove(it) } val floor = DanceFloor(floorSize) val previousPositions = mutableListOf<String>() var totalDances = 0 // add starting position previousPositions.add(floor.toString()) // Find point of repetition while (true) { totalDances++ val positions = floor.also { moves.forEach { move -> floor.runMove(move) } }.toString() if (positions in previousPositions) break previousPositions.add(positions) } // determine position after billionth dance val finalPosition = 1_000_000_000 % totalDances return previousPositions[finalPosition] }
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
3,209
Advent-Of-Code
MIT License
aoc-2015/src/main/kotlin/aoc/AocDay13.kt
triathematician
576,590,518
false
{"Kotlin": 615974}
package aoc import aoc.util.chunk import aoc.util.chunkint import aoc.util.permutations class AocDay13: AocDay(13) { companion object { @JvmStatic fun main(args: Array<String>) { AocDay13().run() } } override val testinput = """ Alice would gain 54 happiness units by sitting next to Bob. Alice would lose 79 happiness units by sitting next to Carol. Alice would lose 2 happiness units by sitting next to David. Bob would gain 83 happiness units by sitting next to Alice. Bob would lose 7 happiness units by sitting next to Carol. Bob would lose 63 happiness units by sitting next to David. Carol would lose 62 happiness units by sitting next to Alice. Carol would gain 60 happiness units by sitting next to Bob. Carol would gain 55 happiness units by sitting next to David. David would gain 46 happiness units by sitting next to Alice. David would lose 7 happiness units by sitting next to Bob. David would gain 41 happiness units by sitting next to Carol. """.trimIndent().lines() data class Seating(val pers: String, val gain: String, val units: Int, val nextTo: String) { val delta = if (gain == "gain") units else -units } fun String.parse() = Seating(chunk(0), chunk(2), chunkint(3), chunk(10).dropLast(1)) fun List<Seating>.score(a: String, b: String) = filter { (it.pers == a && it.nextTo == b) || (it.pers == b && it.nextTo == a) }.sumOf { it.delta } override fun calc1(input: List<String>): Int = input.map { it.parse() }.let { val people = it.map { it.pers }.toSet() people.toList().permutations().maxOf { p -> (p + p.first()).zipWithNext().sumOf { (a, b) -> it.score(a, b) } } } override fun calc2(input: List<String>): Int = input.map { it.parse() }.let { val people = it.map { it.pers }.toSet() + "you" people.toList().permutations().maxOf { p -> (p + p.first()).zipWithNext().sumOf { (a, b) -> it.score(a, b) } } } }
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
2,130
advent-of-code
Apache License 2.0
src/main/kotlin/g2901_3000/s2981_find_longest_special_substring_that_occurs_thrice_i/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2981_find_longest_special_substring_that_occurs_thrice_i // #Medium #String #Hash_Table #Binary_Search #Counting #Sliding_Window // #2024_01_19_Time_208_ms_(90.70%)_Space_39.1_MB_(23.26%) import java.util.Collections import java.util.TreeMap import kotlin.math.max class Solution { fun maximumLength(s: String): Int { val buckets: MutableList<MutableList<Int>> = ArrayList() for (i in 0..25) { buckets.add(ArrayList()) } var cur = 1 for (i in 1 until s.length) { if (s[i] != s[i - 1]) { val index = s[i - 1].code - 'a'.code buckets[index].add(cur) cur = 1 } else { cur++ } } val endIndex = s[s.length - 1].code - 'a'.code buckets[endIndex].add(cur) var result = -1 for (bucket in buckets) { result = max(result, generate(bucket)) } return result } private fun generate(list: List<Int>): Int { Collections.sort(list, Collections.reverseOrder()) val map = TreeMap<Int, Int>(Collections.reverseOrder()) var i = 0 while (i < list.size && i < 3) { val cur = list[i] var num = map.getOrDefault(cur, 0) map[cur] = num + 1 if (cur >= 2) { num = map.getOrDefault(cur - 1, 0) map[cur - 1] = num + 2 } if (cur >= 3) { num = map.getOrDefault(cur - 2, 0) map[cur - 2] = num + 3 } i++ } for ((key, value) in map) { if (value >= 3) { return key } } return -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,772
LeetCode-in-Kotlin
MIT License
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p02/Leet230.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p02 import java.util.* class Leet230 { class Solution { fun kthSmallest(root: TreeNode?, k: Int): Int { val list = LinkedList<TreeNode>() bTreeToLinkedList(root, list) return list.getOrNull(k - 1)?.`val` ?: 0 } private fun bTreeToLinkedList( node: TreeNode?, list: LinkedList<TreeNode>, ) { // if (node != null) { // // // result.addAll(bTreeToLinkedList(node.left)) // result.add(node) // result.addAll(bTreeToLinkedList(node.right)) // } // return result } } data class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } companion object { @JvmStatic fun main(args: Array<String>) { val testCase1 = Data("[3,1,4,null,2]", 1, 1) doWork(testCase1) val testCase2 = Data("[5,3,6,2,4,null,null,1]", 3, 3) doWork(testCase2) // val testCase3 = Data("[3,1,4,null,2]", 1, 1) // doWork(testCase3) } private fun doWork(data: Data) { val solution = Solution() val result = solution.kthSmallest(data.getTreeNode(), data.k) println("Data: $data") println("Result: $result\n") } } data class Data( val nodes: String, val k: Int, val expected: Int, ) { fun getTreeNode(): TreeNode { val list = nodes.trim('[', ']').split(",") .map { it.toIntOrNull() } val root = TreeNode(list.first()!!) val queueToFill: Queue<TreeNode?> = LinkedList<TreeNode?>().apply { offer(root) } var index = 1 while (index < list.size) { val toFill = queueToFill.poll() toFill?.left = list.getOrNull(index)?.let { TreeNode(it) }.also { queueToFill.offer(it) } toFill?.right = list.getOrNull(index + 1)?.let { TreeNode(it) }.also { queueToFill.offer(it) } index += 2 } return root } } }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
2,223
playground
MIT License
src/main/kotlin/g0301_0400/s0378_kth_smallest_element_in_a_sorted_matrix/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0378_kth_smallest_element_in_a_sorted_matrix // #Medium #Top_Interview_Questions #Array #Sorting #Binary_Search #Matrix #Heap_Priority_Queue // #2022_09_11_Time_522_ms_(59.78%)_Space_56.6_MB_(79.61%) class Solution { fun kthSmallest(matrix: Array<IntArray>?, k: Int): Int { if (matrix == null || matrix.size == 0) { return -1 } var start = matrix[0][0] var end = matrix[matrix.size - 1][matrix[0].size - 1] // O(log(max-min)) time while (start + 1 < end) { val mid = start + (end - start) / 2 if (countLessEqual(matrix, mid) < k) { // look towards end start = mid } else { // look towards start end = mid } } // leave only with start and end, one of them must be the answer // try to see if start fits the criteria first return if (countLessEqual(matrix, start) >= k) { start } else { end } } // countLessEqual // O(n) Time private fun countLessEqual(matrix: Array<IntArray>, target: Int): Int { // binary elimination from top right var row = 0 var col: Int = matrix[0].size - 1 var count = 0 while (row < matrix.size && col >= 0) { if (matrix[row][col] <= target) { // get the count in current row count += col + 1 row++ } else if (matrix[row][col] > target) { // eliminate the current col col-- } } return count } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,682
LeetCode-in-Kotlin
MIT License
kotlin/src/com/daily/algothrim/leetcode/CheckStraightLine.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 1232. 缀点成线 * * 在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。 * 请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。 * * 输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] * 输出:true * * 输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] * 输出:false */ class CheckStraightLine { companion object { @JvmStatic fun main(args: Array<String>) { println(CheckStraightLine().solution(arrayOf( intArrayOf(1, 2), intArrayOf(2, 3), intArrayOf(3, 4), intArrayOf(4, 5), intArrayOf(5, 6), intArrayOf(6, 7) ))) println(CheckStraightLine().solution(arrayOf( intArrayOf(1, 1), intArrayOf(2, 2), intArrayOf(3, 4), intArrayOf(4, 5), intArrayOf(5, 6), intArrayOf(7, 7) ))) } } fun solution(coordinates: Array<IntArray>): Boolean { return binary(coordinates, 0, coordinates.size - 1) } private fun binary(coordinates: Array<IntArray>, start: Int, end: Int): Boolean { // 注意 end - 1,代表区间就两个数就不需要判断 if (start < end - 1) { val mid = (start + end).shr(1) val startX = coordinates[start][0] val startY = coordinates[start][1] val midX = coordinates[mid][0] val midY = coordinates[mid][1] val endX = coordinates[end][0] val endY = coordinates[end][1] if ((midX - startX).times(endY - midY) != (midY - startY).times(endX - midX)) return false if (!binary(coordinates, start, mid) || !binary(coordinates, mid, end)) return false } return true } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,144
daily_algorithm
Apache License 2.0
src/main/kotlin/com/leetcode/top100LikedQuestions/easy/symetric_binary_tree/Main.kt
frikit
254,842,734
false
null
package com.leetcode.top100LikedQuestions.easy.symetric_binary_tree fun main() { println("Test case 1:") val t1 = TreeNode(1) t1.left = TreeNode(2) t1.right = TreeNode(2) t1.left!!.left = TreeNode(3) t1.left!!.right = TreeNode(4) t1.right!!.left = TreeNode(4) t1.right!!.right = TreeNode(3) println(Solution().isSymmetric(t1)) println("Test case 2:") val t2 = TreeNode(1) t2.left = TreeNode(2) t2.right = TreeNode(2) t2.left!!.right = TreeNode(3) t2.right!!.right = TreeNode(3) println(Solution().isSymmetric(t2)) println() } /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun isSymmetric(root: TreeNode?): Boolean { return isSymmetric(root?.left, root?.right) } fun isSymmetric(left: TreeNode?, right: TreeNode?): Boolean { if (left != null && right == null) return false if (left == null && right != null) return false if (left == null && right == null) return true if (left?.`val` != null && left.`val` != right?.`val`) { return false } return isSymmetric(left?.left, right?.right) && isSymmetric(left?.right, right?.left) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,474
leet-code-problems
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[103]二叉树的锯齿形层序遍历.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 // // 例如: //给定二叉树 [3,9,20,null,null,15,7], // // // 3 // / \ // 9 20 // / \ // 15 7 // // // 返回锯齿形层序遍历如下: // // //[ // [3], // [20,9], // [15,7] //] // // Related Topics 栈 树 广度优先搜索 // 👍 355 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun zigzagLevelOrder(root: TreeNode?): List<List<Int>> { //二叉树层序遍历 使用 队列 //时间复杂度 O(n) val res = ArrayList<ArrayList<Int>>() if(root == null) return res val queue = LinkedList<TreeNode>() queue.add(root) //遍历层级 var level = 0 while (!queue.isEmpty()){ val count = queue.size val temp = ArrayList<Int>() for (i in 0 until count){ val node = queue.removeLast() if(node.left!=null) queue.addFirst(node.left) if(node.right!=null) queue.addFirst(node.right) temp.add(node.`val`) } if(level % 2 !=0){ //奇数行反转 temp.reverse() } level++ res.add(temp) } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,786
MyLeetCode
Apache License 2.0
src/main/kotlin/land/tbp/y2019/day_7_amplification_circuit/Problem1.kt
TheBestPessimist
124,364,980
false
{"Python": 111986, "Kotlin": 67608}
package land.tbp.y2019.day_7_amplification_circuit import land.tbp.y2019.intcode.computer.Computer import land.tbp.y2019.intcode.computer.Memory import loadResourceFile import stringToInt fun main() { val s = loadResourceFile("./land/tbp/y2019/day_7_amplification_circuit/in.txt") val maxThrusterSignal = solve(s) println(maxThrusterSignal) } internal fun solve(s: String): Int { val ints = stringToInt(s) val outputs = mutableListOf<Int>() for (i1 in 0..4) { for (i2 in 0..4) { for (i3 in 0..4) { for (i4 in 0..4) { for (i5 in 0..4) { val phaseInputs = listOf(i1, i2, i3, i4, i5) if (!phaseInputsValid(phaseInputs)) { continue } val initialInputSignal = 0 val output = calculateOutput(ints, phaseInputs, initialInputSignal) outputs.add(output) } } } } } return outputs.max()!! } private fun phaseInputsValid(phaseInputs: List<Int>): Boolean { val size = phaseInputs .groupingBy { it } .eachCount() .size return size == 5 } private tailrec fun calculateOutput(ints: List<Int>, phaseInputs: List<Int>, computedInputSignal: Int): Int { if (phaseInputs.isEmpty()) { return computedInputSignal } val inputs = mutableListOf(phaseInputs[0], computedInputSignal) val outputs = mutableListOf<Long>() Computer( Memory(ints), inputs.map { it.toLong() }.toMutableList(), outputs) .runProgram() return calculateOutput(ints, phaseInputs.drop(1), outputs[0].toInt()) }
0
Python
0
0
ee9c97f7d85b7f5ebc0bea285938ca75f2fdfddc
1,810
Advent-of-Code-Problems
Do What The F*ck You Want To Public License
src/Day06.kt
kedvinas
572,850,757
false
{"Kotlin": 15366}
fun main() { fun part1(input: List<String>): Int { val buffer = input[0] for (i in buffer.indices) { val differentChars = buffer.substring(i, i + 4) .toCharArray() .toSet() .size if (differentChars == 4) { return i + 4 } } return input.size } fun part2(input: List<String>): Int { val buffer = input[0] val charMap = mutableMapOf<Char, Int>() buffer.take(14) .forEach { charMap[it] = charMap.getOrDefault(it, 0) + 1 } for (i in buffer.indices) { if (charMap.size == 14) { return i + 14 } val oldChar = buffer[i] val newChar = buffer[i + 14] val charCount = charMap[oldChar] if (charCount == 1) { charMap.remove(oldChar) } else { charMap[oldChar] = charMap.getValue(oldChar) - 1 } charMap[newChar] = charMap.getOrDefault(newChar, 0) + 1 } return input.size } val testInput = readInput("Day06_test") check(part1(testInput) == 11) println(part2(testInput)) check(part2(testInput) == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
04437e66eef8cf9388fd1aaea3c442dcb02ddb9e
1,394
adventofcode2022
Apache License 2.0
src/test/kotlin/adventofcode/common/PermutationsSpec.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.common import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe class PermutationsSpec : FreeSpec({ "Collection<T>.permutations()" - { "returns no permutations for an empty list" { emptyList<Any>().permutations() shouldBe listOf(emptyList()) } "returns the only permutation for a list of a single element" { listOf("A").permutations() shouldContainExactlyInAnyOrder listOf(listOf("A")) } "returns all permutations for a set of two elements" { setOf("A", "B").permutations() shouldContainExactlyInAnyOrder listOf(listOf("A", "B"), listOf("B", "A")) } "returns all permutations for a list of three elements" { listOf(1, 2, 3).permutations() shouldContainExactlyInAnyOrder listOf( listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1) ) } } "Collection<T>.powersets()" - { "returns the powerset of an empty collection" { emptySet<Any>().powersets() shouldBe listOf(emptyList()) } "returns the powerset of a collection with 1 element" { setOf(1).powersets() shouldContainExactlyInAnyOrder listOf(emptyList(), listOf(1)) } "returns the powerset of a collection with 2 elements" { setOf(1, 2).powersets() shouldContainExactlyInAnyOrder listOf(emptyList(), listOf(1), listOf(2), listOf(1, 2)) } "returns the powerset of a collection with 3 elements" { setOf(1, 2, 3).powersets() shouldContainExactlyInAnyOrder listOf( emptyList(), listOf(1), listOf(2), listOf(3), listOf(1, 2), listOf(1, 3), listOf(2, 3), listOf(1, 2, 3) ) } "returns the powerset of a collection containing duplicate elements" { listOf(1, 1, 2).powersets() shouldContainExactlyInAnyOrder listOf( emptyList(), listOf(1), listOf(1), listOf(2), listOf(1, 1), listOf(1, 2), listOf(1, 2), listOf(1, 1, 2) ) } } })
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,493
AdventOfCode
MIT License
src/main/kotlin/y2023/Day6.kt
juschmitt
725,529,913
false
{"Kotlin": 18866}
package y2023 import utils.Day class Day6 : Day(6, 2023, false) { override fun partOne(): Any { return inputString.split("\n").map { line -> line.split(":").last().trim().split(" ").mapNotNull { it.toIntOrNull() } }.zipWithNext { times, distances -> times.zip(distances) { time, distance -> time to distance } } .flatten() .map { (time, dist) -> calculateNumOfWaysToWin(time.toLong(), dist.toLong()) } .reduce { acc, i -> acc * i } } override fun partTwo(): Any { return inputString.split("\n").map { line -> line.split(":").last().filter { it.isDigit() }.toLong() }.zipWithNext { time, dist -> calculateNumOfWaysToWin(time, dist) } .reduce { acc, i -> acc * i } } } private fun calculateNumOfWaysToWin(time: Long, distance: Long) = (1..<time) .map { press -> press * (time - press) } .count { dist -> dist > distance }
0
Kotlin
0
0
b1db7b8e9f1037d4c16e6b733145da7ad807b40a
964
adventofcode
MIT License
src/Day14.kt
erikthered
572,804,470
false
{"Kotlin": 36722}
fun main() { data class Point(var x: Int, var y: Int) fun generateRocks(input: List<String>): MutableSet<Pair<Int, Int>> { return input.flatMap { line -> line.split(" -> ") .map { it.split(",").let { (x, y) -> x.toInt() to y.toInt() } } .windowed(2, 1) .flatMap { (first, second) -> if(first.first == second.first && first.second < second.second) { (first.second..second.second).map { first.first to it } } else if(first.first == second.first && first.second > second.second) { (first.second downTo second.second).map { first.first to it } } else if(first.second == second.second && first.first < second.first) { (first.first..second.first).map { it to first.second} } else { (first.first downTo second.first).map { it to first.second} } } }.toMutableSet() } fun part1(input: List<String>): Int { val occupied = generateRocks(input) val source = 500 to 0 occupied.add(source) val leftBound = occupied.minBy { it.first }.first val rightBound = occupied.maxBy { it.first }.first val upperBound = occupied.maxBy { it.second }.second var sandAtRest = 0 var done = false val sand = Point(500,0) while(!done) { // OOB if(sand.x < leftBound || sand.x > rightBound || sand.y > upperBound) { done = true } // At Rest if(occupied.containsAll(listOf( sand.x to sand.y+1, sand.x-1 to sand.y+1, sand.x+1 to sand.y+1 ))) { occupied.add(sand.x to sand.y) sandAtRest++ sand.x = 500 sand.y = 0 } // Down if(!occupied.contains(sand.x to sand.y+1)) { sand.y++ } else if(!occupied.contains(sand.x-1 to sand.y+1)) { sand.y++ sand.x-- } else if(!occupied.contains(sand.x+1 to sand.y+1)) { sand.y++ sand.x++ } } return sandAtRest } fun part2(input: List<String>): Int { val occupied = generateRocks(input) val source = 500 to 0 val upperBound = occupied.maxBy { it.second }.second + 2 var sandAtRest = 0 var done = false val sand = Point(500,0) while(!done) { if(occupied.contains(source)) { done = true } // At Rest if(occupied.containsAll(listOf( sand.x to sand.y+1, sand.x-1 to sand.y+1, sand.x+1 to sand.y+1 )) || sand.y == upperBound-1) { occupied.add(sand.x to sand.y) sandAtRest++ sand.x = 500 sand.y = 0 } else { // Down if (!occupied.contains(sand.x to sand.y + 1)) { sand.y++ } else if (!occupied.contains(sand.x - 1 to sand.y + 1)) { sand.y++ sand.x-- } else if (!occupied.contains(sand.x + 1 to sand.y + 1)) { sand.y++ sand.x++ } } } return sandAtRest-1 } val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3946827754a449cbe2a9e3e249a0db06fdc3995d
3,816
aoc-2022-kotlin
Apache License 2.0
src/Day01.kt
SerggioC
573,171,085
false
{"Kotlin": 8824}
fun main() { fun part1(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val input: List<String> = readInput("Day01") val indexes = mutableListOf<Int>() indexes.add(0) input.forEachIndexed { index, s -> if (s.isEmpty()) { indexes.add(index - 1) indexes.add(index + 1) } } indexes.add(input.size - 1) val ranges: MutableList<IntRange> = mutableListOf() for (index in 0 until indexes.size step 2) { ranges.add(indexes.get(index)..indexes.get(index + 1)) } val slices: MutableList<List<String>> = mutableListOf() ranges.forEach {range -> slices.add(input.slice(range)) } val max = slices.maxOf { it.sumOf { it.toInt() } } // part 1 println("max is $max") // part 2 slices.sortByDescending { it.sumOf { it.toInt() } } val top3 = slices.take(3).sumOf { it.sumOf { it.toInt() } } println("Top3 sum is $top3") }
0
Kotlin
0
0
d56fb119196e2617868c248ae48dcde315e5a0b3
1,076
aoc-2022
Apache License 2.0
src/Day08.kt
cagriyildirimR
572,811,424
false
{"Kotlin": 34697}
import kotlin.math.max fun day08Part1(){ val input = readInput("Day08") var result = input.first().length * 4 - 4 println(input) for (i in 1 until input.lastIndex){ for (j in 1 until input.lastIndex) { if (visible(input[i], j)) { result++ // println("${input[i][j]} row") } else if (visible(takeColumn(input, j), i)) { // println("${input[i][j]} column") result++ } } } println(result) } fun visible(l: String, index: Int): Boolean { var i = index - 1 var left = true var right = true while (i >= 0) { if (l[i] < l[index]) i-- else { left = false break } } i = index + 1 while (i <= l.lastIndex) { if (l[i] < l[index]) i++ else { right = false break } } return left || right } fun takeColumn(l: List<String>, j: Int): String { var r = "" l.forEach{ r += it[j] } return r } fun day08Part2() { val input = readInput("Day08Test") var maxTree = 0 for (i in input.indices) { for (j in input.indices) { val r = check(input, i, j) if (r > maxTree) { maxTree = r println("i: $i j: $j max: $maxTree") } } } println(maxTree) } fun check(input: List<String>, i: Int, j: Int): Int { // to right var left = 0 var right = 0 var up = 0 var down = 0 var c = '0' for (k in j+1..input[i].lastIndex) { c = input[i][k] right++ if (c >= input[i][j]) break } for (k in j-1 downTo 0) { c = input[i][k] left++ if (c >= input[i][j]) break } for (k in i+1..input.lastIndex) { c = input[k][j] down++ if (c >= input[i][j]) break } for (k in i-1 downTo 0) { c = input[k][j] up++ if (c >= input[i][j]) break } return left * down * right * up }
0
Kotlin
0
0
343efa0fb8ee76b7b2530269bd986e6171d8bb68
2,066
AoC
Apache License 2.0
src/main/kotlin/monster/1-binary-search.kt
dzca
581,929,762
false
{"Kotlin": 75573}
package monster /** * utility */ class ArrayConverter<T,V> { /** * covert each item T in source into array Type V */ fun map(a: Array<T>, fn: (T) -> V): List<V>{ return a.map(fn) } } fun intsToBools(a: Array<Int>): Array<Boolean>{ val c = ArrayConverter<Int, Boolean>() val b = c.map(a) { x -> x != 0 } return b.toTypedArray() } /** * find the index of first true in an ordered boolean array * * example: * [false, false, true, true, true] => 2 */ fun firstTrue(a: Array<Boolean>): Int{ val n = a.size var l = 0 var r = n-1 var p = -1 while(l <= r){ var m = l + (r-l)/2 if(a[m]) { p = m r = m -1 } else { l = m + 1 } } return p } /** * Given an array of integers sorted in increasing order and a target, * find the index of the first element in the array that is larger * than or equal to the target. Assume that it is guaranteed to find * a satisfying number. * fn( a[m] >= k ) */ fun firstNoLessThan(a: Array<Int>, k: Int): Int{ val n = a.size var l = 0 var r = n - 1 var p = -1 while(l <= r){ val m = l + (r-l)/2 if(a[m] >= k) { p = m r = m - 1 } else { l = m + 1 } } return p } /** * Given a sorted array of integers and a target integer, find the * first occurrence of the target and return its index. * Return -1 if the target is not in the array. * example: * arr = [1, 3, 3, 3, 3, 6, 10, 10, 10, 100], target = 3, Output: 1 */ fun firstMatch(a: Array<Int>, k: Int): Int{ val n = a.size var l = 0 var r = n - 1 var p = -1 while(l <= r){ val m = l + (r-l)/2 if(a[m] == k){ p=m r = m - 1 } else if(a[m] > k){ r = m - 1 } else { l = m + 1 } } return p } /** * Given an integer, find its square root without * using the built-in square root function. Only * return the integer part (truncate the decimals). */ fun squareRoot(n: Int): Int{ var l = 1 var r = n var p = 0 while(l <= r ){ val m = l + (r-l)/2 val t = m*m if(t == n) return m if(t > n){ r = m - 1 } else { p = m l = m + 1 } } return p } /** * A sorted array of unique integers was rotated at an unknown pivot. * * For example, [10, 20, 30, 40, 50] becomes [30, 40, 50, 10, 20]. * * Find the index of the minimum element in this array. * * [30, 40, 50, 10, 20] => 3 * Explanation: the smallest element is 10 and its index is 3. * * [3, 5, 7, 11, 13, 17, 19, 2]=> 7 * Explanation: the smallest element is 2 and its index is 7. */ fun findMinRotated(a: Array<Int>): Int{ val n = a.size var l = 0 var r = n - 1 var p = -1 while(l<=r ){ val m = l + (r -l)/2 if(a[m] <= a[r]) { p = m r = m-1 } else{ l = m + 1 } } return p } /** * Find the index of the peak element. Assume there is only one peak element. * Example: * a = (0 1 2 3 2 1 0) => 3 * Explanation: the largest element is 3 and its index is 3. */ fun peakOfMountain(a: Array<Int>): Int{ val n = a.size var l = 0 var r = n - 1 var p = -1 while(l <= r){ val m = l + (r-l)/2 if(a[m]> a[m+1]){ p = m r = m - 1 } else { l = m + 1 } } return p }
0
Kotlin
0
0
b1e7d1cb739e21ed7e8b7484d6efcd576857830f
3,575
kotlin-algrithm
MIT License
src/main/kotlin/com/tonnoz/adventofcode23/day13/Day13.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day13 import com.tonnoz.adventofcode23.utils.* import kotlin.math.min import kotlin.system.measureTimeMillis object Day13 { @JvmStatic fun main(args: Array<String>) { val input = "input13.txt".readInputSpaceDelimited() val time = measureTimeMillis { input.map { MirrorPath(it) } .sumOf { it.toMirrorPathExitSmudged() } //use .toMirrorPathExit() to solve for part 1 .let { println("P2: $it") } } println("P2 time: $time ms") } data class MirrorPath(val mirrorGrid : List<String>) private fun MirrorPath.toMirrorPathExit(): Long = verticalMirrorIndex() + horizontalMirrorIndex() * 100 private fun MirrorPath.verticalMirrorIndex(previous: Int = -1): Long { for (i in 1 until mirrorGrid[0].length) { if (i == previous) continue //do not check the previous column, if provided val minCols = min(i, mirrorGrid[0].length - i) var match = true for (r in 1..minCols) { if (mirrorGrid.map { it[i - r] } != mirrorGrid.map { it[i + r - 1] }) { match = false break } } if (match) return i.toLong() } return 0L } private fun MirrorPath.horizontalMirrorIndex(mir: Int = -1): Long { for (i in 1 until mirrorGrid.size) { if(i == mir) continue //do not check the previous row, if provided val minRows = min(i, mirrorGrid.size - i) var match = true for (r in 1..minRows) { if (mirrorGrid[i - r] != mirrorGrid[i + r - 1]) { match = false break } } if (match) return i.toLong() } return 0L } private fun MirrorPath.toMirrorPathExitSmudged(): Long { val initialVertical = this.verticalMirrorIndex() val initialHorizontal = this.horizontalMirrorIndex() val newGrid = mirrorGrid.map { it.toMutableList() }.toMutableList() for (y in mirrorGrid.indices) { for (x in mirrorGrid[y].indices) { invertElementInGrid(newGrid, y, x) val newMirrorPath = MirrorPath(newGrid.map { it.joinToString("") }) val newVertical = newMirrorPath.verticalMirrorIndex(initialVertical.toInt()) if (newVertical > 0) return newVertical //skip horizontal and all next inverted grids if vertical is found val newHorizontal = newMirrorPath.horizontalMirrorIndex(initialHorizontal.toInt()) if (newHorizontal > 0) return newHorizontal * 100 invertElementInGrid(newGrid, y, x) } } throw IllegalStateException("Not possible") } private fun invertElementInGrid(newGrid: MutableList<MutableList<Char>>, y: Int, x: Int) { when (newGrid[y][x]) { '.' -> newGrid[y][x] = '#' '#' -> newGrid[y][x] = '.' } } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
2,730
adventofcode23
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-10.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2016 fun main() { println("Part1:") println(part1(testInput1, 2, 5)) println(part1(input, 17, 61)) } private fun part1(input: String, v1: Int, v2: Int): Pair<String, Int> { val bots = mutableMapOf<String, Bot>() val instructions = mutableMapOf<String, BotInstruction>() val outputs = mutableMapOf<String, Int>() val valueRegex = """value (\d+) goes to bot (\d+)""".toRegex() val givesRegex = """bot (\d+) gives low to (bot|output) (\d+) and high to (bot|output) (\d+)""".toRegex() input.lines().filter { valueRegex.matches(it) } .forEach { val (value, bot) = valueRegex.matchEntire(it)!!.destructured val current = bots.getOrPut(bot) { Bot(bot, mutableListOf()) } current.chips.apply { add(value.toInt()) }.sort() } input.lines().filter { givesRegex.matches(it) } .forEach { val (b1, lowType, lowNum, highType, highNum) = givesRegex.matchEntire(it)!!.destructured instructions[b1] = BotInstruction(b1, lowType, lowNum, highType, highNum) } while (instructions.isNotEmpty()) { val (key, instruction) = instructions.entries.first { bots[it.key]?.chips?.size == 2 } instructions -= key val bot = bots[key]!! if (instruction.lowTarget == "bot") { val low = bots.getOrPut(instruction.lowName) { Bot(instruction.lowName, mutableListOf()) } low.chips.apply { add(bot.chips[0]) }.sort() } else { outputs[instruction.lowName] = bot.chips[0] } if (instruction.highTarget == "bot") { val high = bots.getOrPut(instruction.highName) { Bot(instruction.highName, mutableListOf()) } high.chips.apply { add(bot.chips[1]) }.sort() } else { outputs[instruction.highName] = bot.chips[1] } } val result = bots.values.first { it.chips == listOf(v1, v2) } return result.name to outputs["0"]!! * outputs["1"]!! * outputs["2"]!! } private data class BotInstruction(val name: String, val lowTarget: String, val lowName: String, val highTarget: String, val highName: String) private data class Bot(val name: String, val chips: MutableList<Int>) private const val testInput1 = """value 5 goes to bot 2 bot 2 gives low to bot 1 and high to bot 0 value 3 goes to bot 1 bot 1 gives low to output 1 and high to bot 0 bot 0 gives low to output 2 and high to output 0 value 2 goes to bot 2""" private const val input = """value 23 goes to bot 208 bot 125 gives low to bot 58 and high to bot 57 value 13 goes to bot 161 bot 178 gives low to bot 88 and high to bot 172 value 59 goes to bot 128 bot 173 gives low to bot 83 and high to bot 202 bot 189 gives low to bot 35 and high to bot 55 bot 123 gives low to bot 90 and high to bot 169 bot 148 gives low to bot 101 and high to bot 134 bot 36 gives low to bot 78 and high to bot 105 bot 196 gives low to bot 171 and high to bot 45 bot 157 gives low to bot 179 and high to bot 87 bot 124 gives low to bot 25 and high to bot 80 bot 55 gives low to bot 99 and high to bot 201 value 17 goes to bot 4 bot 127 gives low to bot 118 and high to bot 142 bot 9 gives low to bot 61 and high to bot 198 bot 71 gives low to bot 86 and high to bot 96 bot 86 gives low to bot 98 and high to bot 149 bot 176 gives low to bot 89 and high to bot 171 bot 38 gives low to bot 107 and high to bot 63 bot 67 gives low to bot 77 and high to bot 7 bot 131 gives low to output 6 and high to bot 151 bot 97 gives low to bot 33 and high to bot 16 bot 89 gives low to bot 27 and high to bot 36 bot 29 gives low to bot 185 and high to bot 11 bot 92 gives low to bot 189 and high to bot 122 bot 77 gives low to output 7 and high to bot 191 bot 14 gives low to bot 152 and high to bot 179 bot 49 gives low to bot 76 and high to bot 64 value 2 goes to bot 155 bot 159 gives low to bot 182 and high to bot 49 bot 129 gives low to bot 141 and high to bot 40 bot 50 gives low to output 1 and high to bot 47 bot 93 gives low to output 5 and high to bot 167 bot 112 gives low to output 13 and high to bot 51 bot 165 gives low to bot 163 and high to bot 123 bot 13 gives low to bot 75 and high to bot 74 bot 141 gives low to bot 178 and high to bot 207 bot 37 gives low to bot 42 and high to bot 139 value 31 goes to bot 92 bot 44 gives low to bot 16 and high to bot 91 bot 172 gives low to bot 84 and high to bot 27 bot 39 gives low to bot 44 and high to bot 154 bot 170 gives low to bot 95 and high to bot 146 bot 98 gives low to bot 193 and high to bot 17 bot 4 gives low to bot 26 and high to bot 109 bot 197 gives low to bot 71 and high to bot 106 bot 132 gives low to bot 161 and high to bot 181 bot 54 gives low to bot 156 and high to bot 148 bot 140 gives low to bot 0 and high to bot 25 bot 59 gives low to output 10 and high to bot 93 bot 206 gives low to bot 2 and high to bot 200 bot 5 gives low to bot 201 and high to bot 173 bot 81 gives low to bot 24 and high to bot 30 bot 33 gives low to bot 100 and high to bot 113 bot 73 gives low to bot 60 and high to bot 129 bot 43 gives low to output 14 and high to bot 204 bot 143 gives low to bot 176 and high to bot 196 bot 182 gives low to bot 70 and high to bot 76 bot 139 gives low to bot 117 and high to bot 180 bot 31 gives low to bot 131 and high to bot 137 bot 179 gives low to bot 31 and high to bot 28 bot 74 gives low to bot 29 and high to bot 160 bot 7 gives low to bot 191 and high to bot 21 bot 83 gives low to bot 165 and high to bot 116 bot 142 gives low to bot 144 and high to bot 107 bot 187 gives low to bot 129 and high to bot 68 value 61 goes to bot 32 bot 32 gives low to bot 72 and high to bot 53 bot 53 gives low to bot 121 and high to bot 199 bot 79 gives low to bot 143 and high to bot 196 bot 0 gives low to bot 92 and high to bot 194 bot 8 gives low to bot 56 and high to bot 209 value 43 goes to bot 72 bot 95 gives low to output 18 and high to bot 112 bot 104 gives low to bot 41 and high to bot 185 bot 198 gives low to bot 103 and high to bot 48 bot 17 gives low to bot 69 and high to bot 156 bot 138 gives low to output 0 and high to bot 77 bot 76 gives low to bot 127 and high to bot 164 bot 110 gives low to bot 206 and high to bot 60 bot 60 gives low to bot 200 and high to bot 141 bot 134 gives low to bot 67 and high to bot 7 bot 90 gives low to bot 12 and high to bot 192 bot 208 gives low to bot 155 and high to bot 182 bot 87 gives low to bot 28 and high to bot 195 bot 108 gives low to bot 53 and high to bot 186 bot 150 gives low to bot 154 and high to bot 56 bot 204 gives low to output 17 and high to bot 58 bot 174 gives low to bot 138 and high to bot 67 bot 195 gives low to bot 147 and high to bot 81 bot 24 gives low to bot 146 and high to bot 3 bot 12 gives low to bot 119 and high to bot 9 value 37 goes to bot 35 bot 137 gives low to bot 151 and high to bot 170 bot 1 gives low to output 2 and high to bot 22 bot 63 gives low to bot 150 and high to bot 8 bot 133 gives low to bot 140 and high to bot 124 bot 154 gives low to bot 91 and high to bot 110 bot 145 gives low to bot 47 and high to bot 18 bot 109 gives low to bot 159 and high to bot 82 bot 202 gives low to bot 116 and high to bot 37 bot 168 gives low to bot 133 and high to bot 177 bot 193 gives low to bot 93 and high to bot 69 bot 191 gives low to output 16 and high to bot 21 bot 135 gives low to bot 82 and high to bot 163 bot 130 gives low to bot 102 and high to bot 114 bot 26 gives low to bot 208 and high to bot 159 bot 152 gives low to bot 22 and high to bot 31 bot 118 gives low to bot 136 and high to bot 144 bot 149 gives low to bot 17 and high to bot 54 bot 64 gives low to bot 164 and high to bot 119 bot 120 gives low to bot 64 and high to bot 12 bot 180 gives low to bot 188 and high to bot 130 bot 203 gives low to bot 204 and high to bot 125 bot 3 gives low to bot 46 and high to bot 104 bot 114 gives low to bot 205 and high to bot 79 bot 25 gives low to bot 194 and high to bot 20 bot 65 gives low to bot 181 and high to bot 118 bot 169 gives low to bot 192 and high to bot 117 bot 51 gives low to output 8 and high to bot 50 bot 41 gives low to bot 50 and high to bot 145 bot 20 gives low to bot 23 and high to bot 10 bot 106 gives low to bot 96 and high to bot 126 bot 23 gives low to bot 5 and high to bot 6 value 11 goes to bot 43 value 47 goes to bot 189 value 5 goes to bot 115 bot 46 gives low to bot 51 and high to bot 41 bot 115 gives low to bot 43 and high to bot 203 bot 209 gives low to bot 73 and high to bot 187 bot 16 gives low to bot 113 and high to bot 62 bot 101 gives low to bot 174 and high to bot 134 bot 167 gives low to output 20 and high to bot 158 value 3 goes to bot 133 bot 184 gives low to bot 125 and high to bot 100 bot 155 gives low to bot 166 and high to bot 70 bot 88 gives low to bot 81 and high to bot 84 value 19 goes to bot 0 bot 171 gives low to bot 36 and high to bot 45 bot 186 gives low to bot 199 and high to bot 97 bot 111 gives low to bot 209 and high to bot 85 bot 22 gives low to output 4 and high to bot 131 bot 166 gives low to bot 132 and high to bot 65 bot 6 gives low to bot 173 and high to bot 52 bot 75 gives low to bot 104 and high to bot 29 bot 91 gives low to bot 62 and high to bot 206 bot 164 gives low to bot 142 and high to bot 38 bot 15 gives low to bot 160 and high to bot 197 bot 66 gives low to bot 198 and high to bot 188 bot 199 gives low to bot 184 and high to bot 33 bot 122 gives low to bot 55 and high to bot 5 bot 68 gives low to bot 40 and high to bot 143 bot 128 gives low to bot 4 and high to bot 94 bot 27 gives low to bot 13 and high to bot 78 bot 34 gives low to bot 195 and high to bot 88 bot 94 gives low to bot 109 and high to bot 135 bot 158 gives low to output 3 and high to bot 138 bot 47 gives low to output 15 and high to bot 59 bot 163 gives low to bot 120 and high to bot 90 bot 48 gives low to bot 111 and high to bot 102 bot 40 gives low to bot 207 and high to bot 176 bot 144 gives low to bot 153 and high to bot 39 bot 201 gives low to bot 162 and high to bot 83 bot 72 gives low to bot 115 and high to bot 121 bot 156 gives low to bot 19 and high to bot 101 bot 185 gives low to bot 145 and high to bot 183 bot 103 gives low to bot 8 and high to bot 111 bot 192 gives low to bot 9 and high to bot 66 value 71 goes to bot 140 bot 205 gives low to bot 68 and high to bot 79 bot 151 gives low to output 11 and high to bot 95 bot 153 gives low to bot 97 and high to bot 44 bot 105 gives low to bot 15 and high to bot 175 bot 11 gives low to bot 183 and high to bot 86 bot 160 gives low to bot 11 and high to bot 71 bot 56 gives low to bot 110 and high to bot 73 bot 207 gives low to bot 172 and high to bot 89 bot 181 gives low to bot 108 and high to bot 136 bot 175 gives low to bot 197 and high to bot 106 bot 69 gives low to bot 167 and high to bot 19 bot 58 gives low to output 9 and high to bot 1 bot 78 gives low to bot 74 and high to bot 15 bot 21 gives low to output 12 and high to output 19 bot 190 gives low to bot 168 and high to bot 177 value 29 goes to bot 190 bot 107 gives low to bot 39 and high to bot 150 bot 61 gives low to bot 63 and high to bot 103 bot 52 gives low to bot 202 and high to bot 37 value 53 goes to bot 168 bot 30 gives low to bot 3 and high to bot 75 bot 116 gives low to bot 123 and high to bot 42 bot 85 gives low to bot 187 and high to bot 205 bot 99 gives low to bot 94 and high to bot 162 bot 126 gives low to bot 54 and high to bot 148 bot 19 gives low to bot 158 and high to bot 174 bot 82 gives low to bot 49 and high to bot 120 bot 42 gives low to bot 169 and high to bot 139 value 41 goes to bot 190 bot 188 gives low to bot 48 and high to bot 130 bot 113 gives low to bot 14 and high to bot 157 bot 177 gives low to bot 124 and high to bot 80 bot 18 gives low to bot 59 and high to bot 193 bot 96 gives low to bot 149 and high to bot 126 bot 62 gives low to bot 157 and high to bot 2 bot 45 gives low to bot 105 and high to bot 175 bot 2 gives low to bot 87 and high to bot 34 bot 147 gives low to bot 170 and high to bot 24 bot 70 gives low to bot 65 and high to bot 127 bot 162 gives low to bot 135 and high to bot 165 bot 117 gives low to bot 66 and high to bot 180 bot 100 gives low to bot 57 and high to bot 14 bot 57 gives low to bot 1 and high to bot 152 bot 121 gives low to bot 203 and high to bot 184 bot 10 gives low to bot 6 and high to bot 52 bot 84 gives low to bot 30 and high to bot 13 value 7 goes to bot 166 bot 136 gives low to bot 186 and high to bot 153 bot 161 gives low to bot 32 and high to bot 108 bot 102 gives low to bot 85 and high to bot 114 bot 80 gives low to bot 20 and high to bot 10 bot 200 gives low to bot 34 and high to bot 178 bot 119 gives low to bot 38 and high to bot 61 bot 28 gives low to bot 137 and high to bot 147 bot 35 gives low to bot 128 and high to bot 99 value 67 goes to bot 132 bot 146 gives low to bot 112 and high to bot 46 bot 194 gives low to bot 122 and high to bot 23 value 73 goes to bot 26 bot 183 gives low to bot 18 and high to bot 98"""
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
13,053
advent-of-code
MIT License
src/main/kotlin/dayfive/DayFive.kt
pauliancu97
619,525,509
false
null
package dayfive import getLines typealias State = MutableList<MutableList<Char>> private data class Instruction( val quantity: Int, val source: Int, val destination: Int ) { companion object { private val REGEX = """move (\d+) from (\d+) to (\d+)""".toRegex() fun fromString(string: String): Instruction? { val match = REGEX.matchEntire(string) ?: return null val quantity = match.groupValues.getOrNull(1)?.toIntOrNull() ?: return null val source = match.groupValues.getOrNull(2)?.toIntOrNull() ?: return null val destination = match.groupValues.getOrNull(3)?.toIntOrNull() ?: return null return Instruction(quantity, source - 1, destination - 1) } } } private fun getState(lines: List<String>): State { val rows = lines.size val numOfStacks = (lines.last().length - 3) / 4 + 1 val state = MutableList(numOfStacks) { mutableListOf<Char>() } for (stackIndex in 0 until numOfStacks) { val col = 4 * stackIndex + 1 for (row in 0 until (rows - 1)) { if (col < lines[row].length && lines[row][col].isUpperCase()) { state[stackIndex].add(lines[row][col]) } } } return state } private fun executeInstruction(state: State, instruction: Instruction) { val top = state[instruction.source].take(instruction.quantity) state[instruction.source] = state[instruction.source].drop(instruction.quantity).toMutableList() state[instruction.destination] = (top + state[instruction.destination]).toMutableList() } private fun execute(state: State, instructions: List<Instruction>) { for (instruction in instructions) { executeInstruction(state, instruction) } } private fun getInput(path: String): Pair<State, List<Instruction>> { val lines = getLines(path) val emptyLineIndex = lines.indexOfFirst { it.isEmpty() } val stateLines = lines.take(emptyLineIndex) val instructionsLines = lines.drop(emptyLineIndex + 1) val state = getState(stateLines) val instructions = instructionsLines.mapNotNull { Instruction.fromString(it) } return state to instructions } private fun State.getAnswer(): String = this.mapNotNull { it.firstOrNull() }.joinToString(separator = "") private fun solvePartOne() { val (state, instructions) = getInput("day_5.txt") execute(state, instructions) println(state.getAnswer()) } fun main() { solvePartOne() }
0
Kotlin
0
0
78af929252f094a34fe7989984a30724fdb81498
2,499
advent-of-code-2022
MIT License
src/main/kotlin/day01/day02.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day01 import readInput import java.util.PriorityQueue fun main() { fun part1(input: List<String>): Int { return input.fold(0 to 0) { acc, v -> if (v.isEmpty()) { maxOf(acc.first, acc.second) to 0 } else { acc.first to acc.second + v.toInt() } }.first } fun part2(input: List<String>): Int { val (q, acc) = input.fold(PriorityQueue<Int>(reverseOrder()) to 0) { (q, acc), v -> if (v.isEmpty()) { q.add(acc) q to 0 } else { q to acc + v.toInt() } } q.add(acc) var result = 0 repeat(3) { result += q.remove() } return result } // 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", "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
1,080
aoc2022
Apache License 2.0
src/Day05.kt
Vlisie
572,110,977
false
{"Kotlin": 31465}
import java.io.File fun main() { fun maakAntwoordString(stapelLijst: List<ArrayDeque<Char>>): String { var eindString = "" for (stack in stapelLijst.asIterable()) { eindString += if (stack.isNotEmpty()) stack.last() else "" } return eindString } fun part1(file: File): String { val stapelLijst: List<ArrayDeque<Char>> = List(9) { ArrayDeque() } file.readText() .split("\n".toRegex()) .map { elem -> var lastOccur = 0 for (char in elem) { if (char == '[') { lastOccur = elem.indexOf("[", lastOccur) stapelLijst[lastOccur / 4].addFirst(elem[lastOccur + 1]) lastOccur++ } } if (elem.startsWith("move")) { val cijfers = Regex("[0-9]+").findAll(elem) .map(MatchResult::value) .toList() repeat(cijfers[0].toInt()) { stapelLijst[(cijfers[2].toInt() - 1)].addLast(stapelLijst[(cijfers[1].toInt() - 1)].removeLast()) } } } return maakAntwoordString(stapelLijst) } fun part2(file: File): String { val stapelLijst: List<ArrayDeque<Char>> = List(9) { ArrayDeque() } file.readText() .split("\n".toRegex()) .map { elem -> var lastOccur = 0 for (char in elem) { if (char == '[') { lastOccur = elem.indexOf("[", lastOccur) stapelLijst[lastOccur / 4].addFirst(elem[lastOccur + 1]) lastOccur++ } } if (elem.startsWith("move")) { val cijfers = Regex("[0-9]+").findAll(elem) .map(MatchResult::value) .toList() val kraanStapel = ArrayDeque<Char>() repeat(cijfers[0].toInt()) { kraanStapel.addFirst(stapelLijst[(cijfers[1].toInt() - 1)].removeLast()) } repeat(kraanStapel.size) { stapelLijst[(cijfers[2].toInt() - 1)].addLast(kraanStapel.removeFirst()) } } } return maakAntwoordString(stapelLijst) } // test if implementation meets criteria from the description, like: val testInput = File("src/input", "testInput.txt") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = File("src/input", "input5.txt") println("Part 1 -----------") println(part1(input)) println("Part 2 -----------") println(part2(input)) }
0
Kotlin
0
0
b5de21ed7ab063067703e4adebac9c98920dd51e
2,878
AoC2022
Apache License 2.0
src/Day10/Day10.kt
tomashavlicek
571,148,715
false
{"Kotlin": 23780}
package Day10 import readInput fun main() { fun part1(input: List<String>): Int { val signals = mutableListOf<Int>() var x = 1 var cycle = 1 input.forEach { s -> if (s == "noop") { cycle++ } else { cycle++ if (cycle % 40 == 20) { println("cycle: $cycle X $x") signals.add(cycle * x) } cycle++ x += s.split(' ')[1].toInt() } if (cycle % 40 == 20) { println("cycle: $cycle X $x") signals.add(cycle * x) } } return signals.sum() } fun part2(input: List<String>) { val picture = List(7) { CharArray(40) } var x = 1 var cycle = 0 var row: Int var pixelDrawn: Int fun draw() { row = cycle / 40 pixelDrawn = cycle % 40 if (pixelDrawn in IntRange(x - 1, x + 1)) { picture[row][pixelDrawn] = '#' } else { picture[row][pixelDrawn] = '.' } } input.forEach { s -> if (s == "noop") { cycle++ } else { cycle++ draw() cycle++ x += s.split(' ')[1].toInt() } draw() } picture.forEach { println(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10/Day10_test") part1(testInput).also { println(it) check(it == 13140) } val input = readInput("Day10/Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
899d30e241070903fe6ef8c4bf03dbe678310267
1,778
aoc-2022-in-kotlin
Apache License 2.0
bulb-switcher/Solution.kt
Javran
25,217,166
false
null
import java.lang.Math /* math problem in disguise. First we figure out what determines the end state of i-th bulb (1-based): take n = 5 as an example. 1st bulb is on because 1 has the only factor 1 2nd is off because 2 has two factors: 1,2 3rd is off because 3 has two factors: 1,3 4th: on, factors: 1,2,4 5th: off, factors: 1,5 now note that when i>1, i-th bulb is on if and only if i has odd number of factors for any integer N, we can do factorization: N = p1^a1 * p2^a2 ... * pk^ak where p are prime numbers and the number of factors will be T = (a1 + 1)*(a2 + 1)* ... *(ak + 1) if T is an odd, we know i-th bulb will be on. since we need T = (a1 + 1)*(a2 + 1)* ... *(ak + 1) to be odd, all of (a_ + 1) needs to be odd because any of them being even will cause T to be even, which means all (a_) needs to be even. N = p1^(b1*2) * p2^(b2*2) * ... * pk^(bk*2) where a_ = b_*2 ... well, now we know that N has to be a square number. Given n bulbs, if we count the # of square numbers in range of 1 .. n, that is the anwser to the question - just do floor(sqrt(n)) and we are done. */ class Solution { fun bulbSwitch(n: Int): Int { return Math.floor(Math.sqrt(n.toDouble())).toInt() } companion object { @JvmStatic fun main(args: Array<String>) { println(Solution().bulbSwitch(10)) } } }
0
JavaScript
0
3
f3899fe1424d3cda72f44102bab6dd95a7c7a320
1,356
leetcode
MIT License
src/Day13.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.jsonArray fun main() { // ktlint-disable filename fun parseIntoQueue(line: String): JsonArray { val jsonArray = Json.decodeFromString(JsonArray.serializer(), line) return jsonArray } fun isInOrder(left: JsonArray, right: JsonArray): Boolean { println("comparing $left and $right") if (left.size > right.size) return false var equalElements = true for (i in left.indices) { when { i >= right.size -> { return !equalElements } left[i] is JsonArray && right[i] is JsonArray -> { if (!isInOrder(left[i].jsonArray, right[i].jsonArray)) return false } left[i] !is JsonArray && right[i] !is JsonArray -> { if (left[i].toString().toInt() > right[i].toString().toInt()) return false // handle weird case where at least one element must be non-equal if (left[i].toString().toInt() < right[i].toString().toInt()) equalElements = false } left[i] !is JsonArray && right[i] is JsonArray -> { if (right[i].jsonArray.isEmpty()) return false if (right[i].jsonArray[0] is JsonArray) return false if (left[i].toString().toInt() > right[i].jsonArray[0].toString().toInt() ) return false } left[i] is JsonArray && right[i] !is JsonArray -> { if (left[i].jsonArray.isEmpty()) return false if (left[i].jsonArray[0] is JsonArray) return false if (left[i].jsonArray[0].toString().toInt() > right[i].toString() .toInt() ) return false // handle weird case where at least one element must be non-equal if (left[i].jsonArray[0].toString().toInt() < right[i].toString().toInt()) equalElements = false } } } return true } fun part1(input: List<String>): Int { val validIndexes = mutableListOf<Int>() for (i in input.indices step 3) { val left = parseIntoQueue(input[i]) val right = parseIntoQueue(input[i + 1]) if (isInOrder(left, right)) validIndexes.add(i / 3 + 1) } println("Valid indexes: $validIndexes") return validIndexes.sum() } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") println("Test Sum of matching pair indices: ${part1(testInput)}") check(part1(testInput) == 13) // println("Test Fewest steps to bottom: ${part2(testInput)}") // check(part2(testInput) == 29) val input = readInput("Day13_input") println("Sum of matching pair indices: ${part1(input)}") // println("Fewest steps to bottom: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
3,175
KotlinAdventOfCode2022
Apache License 2.0
src/dynamicprogramming/LongestIncreasingSubsequence.kt
faniabdullah
382,893,751
false
null
package dynamicprogramming class LongestIncreasingSubsequence { fun lis(intArray: IntArray): Int { val sizeTable = intArray.size val lookupTable = IntArray(sizeTable) { 1 } for (i in 1 until intArray.size) { for (j in 0 until i) { if (intArray[i] > intArray[j] && lookupTable[i] < lookupTable[j] + 1 ) { lookupTable[i] = lookupTable[i] + 1 } } } var counter = 0 println(lookupTable.contentToString()) for (i in 0 until sizeTable) { counter = maxOf(counter, lookupTable[i]) } return counter } fun increasingTriplet(nums: IntArray): Boolean { var first: Int? = null var second: Int? = null nums.forEach { when { first == null -> { first = nums[it] } it <= first as Int -> { first = nums[it] } second == null -> { second = nums[it] } it <= second as Int -> { second = it } else -> { return true } } } return false } fun longestIncreasingSubSequence(intArray: IntArray): Int { val lookupTable = IntArray(intArray.size) { 1 } for (i in 1 until intArray.size) { for (j in 0 until i) { if (intArray[i] > intArray[j] && lookupTable[i] < lookupTable[j] + 1 ) { lookupTable[i] = lookupTable[i] + 1 } } } println(lookupTable.contentToString()) var max = 0 lookupTable.forEach { max = maxOf(max, it) } return max } private val lookupTable = IntArray(200) { -1 } private val nell = -1 fun climbingStairMemoization(n: Int): Int { if (lookupTable[n] == nell) { if (n <= 1) { return 1 } lookupTable[n] = climbingStairMemoization(n - 1) + climbingStairMemoization(n - 2) } return lookupTable[n] } fun climbingStairBottomUp(n: Int): Int { if (n <= 1) { return 1 } val dp = IntArray(n + 1) dp[1] = 1 dp[2] = 2 for (i in 3..n) { dp[i] = dp[i - 1] + dp[i - 2] } return dp[n] } } fun main() { // val lisOFArray = LongestIncreasingSubsequence() // .lis(intArrayOf(0, 1, 0, 3, 2, 3)) // val lisOFArray2 = LongestIncreasingSubsequence() // .longestIncreasingSubSequence(intArrayOf(0, 1, 0, 3, 2, 3)) val nameClass = LongestIncreasingSubsequence() println(nameClass.climbingStairMemoization(2)) println(nameClass.climbingStairMemoization(3)) println(nameClass.climbingStairMemoization(4)) println(nameClass.climbingStairMemoization(5)) println(nameClass.climbingStairMemoization(6)) println(nameClass.climbingStairMemoization(7)) println(nameClass.climbingStairMemoization(8)) println(nameClass.climbingStairMemoization(9)) println(nameClass.climbingStairMemoization(10)) println(nameClass.climbingStairMemoization(11)) println() println(55 + 89) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
3,436
dsa-kotlin
MIT License
src/days/Day01/Day01.kt
SimaoMata
573,172,347
false
{"Kotlin": 3659}
package days.Day01 import readInput fun main() { // test if implementation meets criteria from the description, like: val inputPart1 = readInput("Day01") println(part1(inputPart1)) val inputPart2 = readInput("Day01") println(part2(inputPart2)) } fun part1(input: String): Int { return getMaxCalories(input) } fun getMaxCalories(values: String): Int { return values .split("\n\n") .map { elfValues -> elfValues .split("\n") .sumOf { it.toInt() } } .max() } fun part2(input: String): Int { return getMaxCaloriesOfTheTopN(input, 3) } fun getMaxCaloriesOfTheTopN(values: String, n: Int): Int { return values .split("\n\n") .map { elfValues -> elfValues .split("\n") .sumOf { it.toInt() } } .sortedDescending() .take(n) .sum() }
0
Kotlin
0
0
bc3ba76e725b02c893aacc033c99169d7a022614
935
advent-of-code-2022
Apache License 2.0
src/day_01/Day01.kt
BrumelisMartins
572,847,918
false
{"Kotlin": 32376}
package day_01 import readInput fun main() { fun getListOfCalories(input: List<String>): List<Int> { val listOfSums = arrayListOf<Int>() var sum = 0 input.forEach { if (it.isBlank()) { listOfSums.add(sum) sum = 0 return@forEach } sum += it.toInt() } //in case last element is not an empty line and was not added if (sum != 0) { listOfSums.add(sum) } return listOfSums } fun part1(input: List<String>): Int { val listOfSums = getListOfCalories(input) return listOfSums.max() } fun part2(input: List<String>): Int { val listOfSums = getListOfCalories(input).sortedByDescending { it } return listOfSums.take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("day_01/Day01_test") check(part1(testInput) == 24000) val input = readInput("day_01/Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3391b6df8f61d72272f07b89819c5b1c21d7806f
1,109
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CanBeValid.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.abs /** * 2116. Check if a Parentheses String Can Be Valid * @see <a href="https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/">Source</a> */ fun interface CanBeValid { operator fun invoke(s: String, locked: String): Boolean } class CanBeValidLeftRight : CanBeValid { override operator fun invoke(s: String, locked: String): Boolean { return s.length % 2 == 0 && validate(s, locked, '(') && validate(s, locked, ')') } private fun validate(s: String, locked: String, op: Char): Boolean { var bal = 0 var wild = 0 val sz = s.length val start = if (op == '(') 0 else sz - 1 val dir = if (op == '(') 1 else -1 var i = start while (i in 0 until sz && wild + bal >= 0) { if (locked[i] == '1') bal += if (s[i] == op) 1 else -1 else ++wild i += dir } return abs(bal) <= wild } } class CanBeValidCountingBrackets : CanBeValid { override operator fun invoke(s: String, locked: String): Boolean { if (s.length % 2 == 1) return false var total = 0 var open = 0 var closed = 0 for (i in s.length - 1 downTo 0) { when { locked[i] == '0' -> total += 1 s[i] == '(' -> open += 1 s[i] == ')' -> closed += 1 } if (total - open + closed < 0) return false } total = 0.also { closed = it }.also { open = it } for (i in s.indices) { when { locked[i] == '0' -> total += 1 s[i] == '(' -> open += 1 s[i] == ')' -> closed += 1 } if (total + open - closed < 0) return false } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,434
kotlab
Apache License 2.0
src/Lesson7StacksAndQueues/StoneWall.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Stack /** * 100/100 * @param H * @return */ fun solution(H: IntArray): Int { var blocks = 0 val stack: Stack<Int> = Stack<Int>() // main idea: need to use "stack" to check when we need a new block for (i in H.indices) { // step 1: "stack is not empty" AND "from high to low" // then, "pop" (it is the key point, be careful) while (!stack.isEmpty() && stack.peek() > H[i]) { stack.pop() } // step 2: if the stack is empty if (stack.isEmpty()) { blocks++ // add a block stack.push(H[i]) // push the height } else if (stack.peek() < H[i]) { //step 3: from low to high blocks++ // add a block stack.push(H[i]) // push the height } } return blocks } // Inspiration: https://github.com/Mickey0521/Codility/blob/master/StoneWall.java /** * You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end. * * The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall. * * Write a function: * * class Solution { public int solution(int[] H); } * * that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it. * * For example, given array H containing N = 9 integers: * * H[0] = 8 H[1] = 8 H[2] = 5 * H[3] = 7 H[4] = 9 H[5] = 8 * H[6] = 7 H[7] = 4 H[8] = 8 * the function should return 7. The figure shows one possible arrangement of seven blocks. * * * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [1..100,000]; * each element of array H is an integer within the range [1..1,000,000,000]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
2,245
Codility-Kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CoinChange2.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 /** * 518. Coin Change II * @see <a href="https://leetcode.com/problems/coin-change-ii/">Source</a> */ fun interface CoinChange2 { fun change(amount: Int, coins: IntArray): Int } /** * Approach 1: Top-Down Dynamic Programming */ class CoinChange2TopDown : CoinChange2 { private lateinit var memo: Array<IntArray> private lateinit var coins: IntArray override fun change(amount: Int, coins: IntArray): Int { this.coins = coins memo = Array(coins.size) { IntArray(amount + 1) { -1 } } return numberOfWays(0, amount) } private fun numberOfWays(i: Int, amount: Int): Int { if (amount == 0) { return 1 } if (i == coins.size) { return 0 } if (memo[i][amount] != -1) { return memo[i][amount] } if (coins[i] > amount) { return numberOfWays(i + 1, amount).also { memo[i][amount] = it } } memo[i][amount] = numberOfWays(i, amount - coins[i]) + numberOfWays(i + 1, amount) return memo[i][amount] } } /** * Approach 2: Bottom-Up Dynamic Programming */ class CoinChange2BottomUp : CoinChange2 { override fun change(amount: Int, coins: IntArray): Int { val n: Int = coins.size val dp = Array(n + 1) { IntArray(amount + 1) } for (i in 0 until n) { dp[i][0] = 1 } for (i in 1..amount) { dp[0][i] = 0 } for (i in n - 1 downTo 0) { for (j in 1..amount) { if (coins[i] > j) { dp[i][j] = dp[i + 1][j] } else { dp[i][j] = dp[i + 1][j] + dp[i][j - coins[i]] } } } return dp[0][amount] } } /** * Approach 3: Dynamic Programming with Space Optimization */ class CoinChange2SpaceOpt : CoinChange2 { override fun change(amount: Int, coins: IntArray): Int { val n: Int = coins.size val dp = IntArray(amount + 1) dp[0] = 1 for (i in n - 1 downTo 0) { for (j in coins[i]..amount) { dp[j] += dp[j - coins[i]] } } return dp[amount] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,859
kotlab
Apache License 2.0
src/main/kotlin/org/sjoblomj/travellingantcolony/Bruteforcer.kt
sjoblomj
171,120,735
false
null
package org.sjoblomj.travellingantcolony import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.immutableListOf import kotlinx.collections.immutable.toImmutableList import org.sjoblomj.travellingantcolony.domain.Place import kotlin.math.sqrt typealias Places = ImmutableList<Place> fun Places.tail(): Places = this.removeAt(0) fun bruteforce(places: Places): Places { if (places.size < 2) return places val firstNode = places.first() val permutations = generateAllPermutations(places.removeAt(0)) return findShortestPath(permutations, firstNode) } fun bruteforce2(places: Places): Places { if (places.size < 2) return places val firstNode = places.first() val permutations = generateAllPermutations2(places.removeAt(0)) return findShortestPath2(permutations, firstNode) } private fun generateAllPermutations(places: Places): ImmutableList<Places> { val startTime = System.currentTimeMillis() val permutations = permutation(places) print("Generated ${permutations.size} permutations in ${System.currentTimeMillis() - startTime} ms.\n") return permutations } private fun generateAllPermutations2(places: Places): Sequence<Places> { val startTime = System.currentTimeMillis() val permutations = permutation2(places) print("Generated permutations in ${System.currentTimeMillis() - startTime} ms.\n") return permutations } private fun findShortestPath(permutations: ImmutableList<Places>, firstNode: Place): Places { val greedyTime = System.currentTimeMillis() var bestPerm = greedySolution(permutations[0], firstNode) print("Generated greedy solution in ${System.currentTimeMillis() - greedyTime} ms.\n") var bestLength = calculateLength(bestPerm) ?: Double.MAX_VALUE printPermutation(bestPerm, bestLength) val iterationTime = System.currentTimeMillis() for (places in permutations) { val wholeTrip = (immutableListOf(firstNode) + places + firstNode).toImmutableList() val tripLength = calculateLength(wholeTrip, bestLength) if (tripLength != null) { bestPerm = wholeTrip bestLength = tripLength printPermutation(bestPerm, bestLength) } } print("Found best solution among the ${permutations.size} possible in ${System.currentTimeMillis() - iterationTime} ms.\n") return bestPerm } private fun findShortestPath2(permutations: Sequence<Places>, firstNode: Place): Places { val greedy = greedySolution(permutations.first(), firstNode) val greedyLength = calculateLength(greedy) ?: Double.MAX_VALUE printPermutation(greedy, greedyLength) val startTime = System.currentTimeMillis() val bestPerm = findBestPermutation(permutations.iterator(), firstNode, greedy, greedyLength) print("Found best solution possible in ${System.currentTimeMillis() - startTime} ms.\n") return bestPerm } private tailrec fun findBestPermutation(permutations: Iterator<Places>, firstNode: Place, bestPerm: Places, bestLength: Double): Places { return if (!permutations.hasNext()) { bestPerm } else { val places = permutations.next() // Get the next permutation and move the iterator one step forward val wholeTrip = (immutableListOf(firstNode) + places + firstNode).toImmutableList() val tripLength = calculateLength(wholeTrip, bestLength) val bestPermutation = if (tripLength != null) { printPermutation(wholeTrip, tripLength) wholeTrip } else { bestPerm } return findBestPermutation(permutations, firstNode, bestPermutation, tripLength ?: bestLength) } } private fun findShortestPath3(permutations: Sequence<Places>, firstNode: Place): Places { val startTime = System.currentTimeMillis() val bestPerm = permutations .map { getTripAndLength(it, firstNode) } .minBy { it.second } ?.first ?: permutations.first() printPermutation(bestPerm, calculateLength(bestPerm) ?: Double.MAX_VALUE) print("Found best solution in ${System.currentTimeMillis() - startTime} ms.\n") return bestPerm } private fun getTripAndLength(places: Places, firstNode: Place): Pair<Places, Double> { val wholeTrip = (immutableListOf(firstNode) + places + firstNode).toImmutableList() val tripLength = calculateLength(wholeTrip) return Pair(wholeTrip, tripLength ?: Double.MAX_VALUE) } private fun printPermutation(places: Places, length: Double) { print("Shortest length: ${length.toString().padEnd(18, '0')}. Permutation: $places\n") } fun greedySolution(places: Places, startAndEnd: Place): Places { if (places.isEmpty()) return places val solution = greedySolution(immutableListOf(startAndEnd), places) return (solution + startAndEnd).toImmutableList() } private fun greedySolution(visitedPlaces: Places, unvisitedPlaces: Places): Places { if (unvisitedPlaces.isEmpty()) return visitedPlaces val closestPlace = unvisitedPlaces .map { Pair(it, distance(visitedPlaces.last(), it)) } .minBy { it.second } ?.first ?: unvisitedPlaces.first() return greedySolution(visitedPlaces.add(closestPlace), unvisitedPlaces.remove(closestPlace)) } fun permutation(unvisitedPlaces: Places, visitedPlaces: Places = immutableListOf()): ImmutableList<Places> { if (unvisitedPlaces.isEmpty()) return immutableListOf(visitedPlaces) return unvisitedPlaces .flatMap { permutation(unvisitedPlaces.remove(it), visitedPlaces.add(it)) } .toImmutableList() } fun permutation3(unvisitedPlaces: Places, visitedPlaces: Places = immutableListOf()): Sequence<Places> { if (unvisitedPlaces.isEmpty()) return immutableListOf(visitedPlaces).asSequence() return unvisitedPlaces .flatMap { permutation3(unvisitedPlaces.remove(it), visitedPlaces.add(it)).asIterable() } .asSequence() } /* // https://github.com/dkandalov/kotlin-99/blob/master/src/org/kotlin99/common/collections.kt fun <T> ImmutableList<T>.permutationsSeq(): Sequence<ImmutableList<T>> { if (size <= 1) return sequenceOf(this) val head = first() return tail().permutationsSeq().flatMap { tailPermutation -> (0..tailPermutation.size).asSequence().map { i -> tailPermutation.apply { add(i, head) } } } } */ fun Places.permutationsSeq(): Sequence<Places> { if (size <= 1) return sequenceOf(this) val head = first() return tail().permutationsSeq().flatMap { tailPermutation -> (0..tailPermutation.size).asSequence().map { i -> tailPermutation.add(i, head) } } } fun permutation2(places: Places): Sequence<Places> { if (places.size <= 1) return sequenceOf(places) val head = places.first() return permutation2(places.tail()).flatMap { tailPermutation -> (0..tailPermutation.size).asSequence().map { i -> tailPermutation.add(i, head) } } } fun calculateLength(places: Places, terminationSum: Double = Double.MAX_VALUE, sum: Double = 0.0): Double? { return when { sum >= terminationSum -> null // We are not done calculating, but already know this permutation is suboptimal. places.size < 2 -> sum else -> calculateLength(places.removeAt(0), terminationSum, sum + distance(places[0], places[1])) } } private fun distance(p0: Place, p1: Place): Double { fun pow(a: Double) = Math.pow(a, 2.0) return sqrt(pow(p0.x - p1.x) + pow(p0.y - p1.y)) }
0
Kotlin
0
0
ee8f36e3434f4076eebacfbab80a817b59e197ee
7,398
TravellingAntColony
MIT License
src/day1/Day01.kt
MatthewWaanders
573,356,006
false
null
package day1 import utils.readInput fun main() { val testInput = readInput("Day01_test", "day1") check(part1(testInput) == 24000) val input = readInput("Day01", "day1") println(part1(input)) println(part2(input)) } fun convertInputToCaloriesPerElf(input: List<String>) = input .fold(listOf(listOf<String>())) { acc, s -> if (s.isBlank()) listOf(*(acc.toTypedArray()), emptyList()) else listOf(*(acc.subList(0, acc.size - 1).toTypedArray()), acc.last() + s) } .fold(emptyList<Int>()) { acc, ls -> acc + ls.sumOf { it.toInt() } } fun part1(input: List<String>) = convertInputToCaloriesPerElf(input) .maxOf { it } fun part2(input: List<String>) = convertInputToCaloriesPerElf(input) .sortedDescending() .subList(0, 3) .sum()
0
Kotlin
0
0
f58c9377edbe6fc5d777fba55d07873aa7775f9f
772
aoc-2022
Apache License 2.0
kotlin/aoc2018/src/main/kotlin/Day11.kt
aochsner
160,386,044
false
null
class Day11 { fun part1(serialNumber: Int) : Pair<Int, Int> { val powerGrid = Array(300) { x -> Array(300) { y -> getPowerLevel(x+1, y+1, serialNumber) } } return findLargestSquare(powerGrid, 3).key } private fun findLargestSquare(powerGrid: Array<Array<Int>>, gridSize: Int): Map.Entry<Pair<Int, Int>, Int> { val squareMap = mutableMapOf<Pair<Int, Int>, Int>() for (x in 0..(300-gridSize)) { for (y in 0..(300-gridSize)) { var squareSum = 0 for (rx in 0..(gridSize-1)) { for (ry in 0..(gridSize-1)) { squareSum += powerGrid[x + rx][y + ry] } } squareMap[Pair(x + 1, y + 1)] = squareSum } } return squareMap.maxBy { it.value }!! } fun part2(serialNumber: Int) : Triple<Int, Int, Int> { val powerGrid = Array(300) { x -> Array(300) { y -> getPowerLevel(x+1, y+1, serialNumber) } } val tripleMap = mutableMapOf<Triple<Int, Int, Int>, Int>() for (size in 1..300) { val largeSquare = findLargestSquare(powerGrid, size) tripleMap[Triple(largeSquare.key.first, largeSquare.key.second, size)] = largeSquare.value } return tripleMap.maxBy { it.value }!!.key } fun getPowerLevel(x: Int, y: Int, serialNumber: Int): Int { val rackId = x + 10 var powerLevel = rackId * y powerLevel += serialNumber powerLevel *= rackId powerLevel = (powerLevel / 100) % 10 return powerLevel - 5 } }
0
Kotlin
0
1
7c42ec9c20147c4be056d03e5a1492c137e63615
1,713
adventofcode2018
MIT License
leetcode/src/offer/middle/Offer56_2.kt
zhangweizhe
387,808,774
false
null
package offer.middle fun main() { // 剑指 Offer 56 - II. 数组中数字出现的次数 II // https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/ println(singleNumber1(intArrayOf(1,1,1,-3,-2,-3,-3))) } fun singleNumber(nums: IntArray): Int { // 计算 nums 各个数字,在各个位上1的数量 // 如果某一位上1的数量,不能被3整除,说明这一位上的1就是来自那个只出现一次的数字 var result = 0 for (i in 0..31) { var oneCount = 0 for (j in nums) { oneCount += (j.ushr(i).and(1)) } if (oneCount % 3 != 0) { // i 位上的 1,来自只出现一次的数字,通过把1左移i位,恢复到 result 上 result = result.or(1.shl(i)) } } return result } fun singleNumber1(nums: IntArray): Int { // 计算 nums 各个数字,在各个位上1的数量 // 如果某一位上1的数量,不能被3整除,说明这一位上的1就是来自那个只出现一次的数字 var res = 0 for (i in 0..31) { var oneCount = 0 val shl = 1.shl(i) for (n in nums) { if (n.and(shl) != 0) { oneCount++ } } if (oneCount % 3 != 0) { res = res.or(shl) } } return res }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,352
kotlin-study
MIT License
src/day16/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
package day16 import java.io.File import java.lang.IllegalStateException import kotlin.math.max import kotlin.math.min data class Packet(val length: Int, val versionSum: Int, val value: Long) data class Literal(val length: Int, val value: Long) data class Bits(val input: String) { private var index = 0 private fun getString(length: Int): String { val result = input.substring(index, index + length) index += length return result } private fun getInt(length: Int) = getString(length).toInt(2) private fun getLong(length: Int) = getString(length).toLong(2) private fun getLiteral(): Literal { val startIndex = index var result = "" do { val hasNext = getInt(1) == 1 result += getString(4) } while (hasNext) return Literal(index - startIndex, result.toLong(2)) } fun getPacket(): Packet { val version = getInt(3) val type = getInt(3) if (type == 4) { return getLiteral().let { Packet(it.length + 6, version, it.value) } } else { val lengthType = getInt(1) val subPackets = mutableListOf<Packet>() if (lengthType == 0) { val totalLength = getLong(15) val startIndex = index while (index < startIndex + totalLength) { subPackets += getPacket() } } else { val numSubPackets = getLong(11) for (i in 0 until numSubPackets) { subPackets += getPacket() } } val fn: (Long, Long) -> Long = when (type) { 0 -> Long::plus 1 -> Long::times 2 -> ::min 3 -> ::max 5 -> { p1, p2 -> if (p1 > p2) 1 else 0 } 6 -> { p1, p2 -> if (p1 < p2) 1 else 0 } 7 -> { p1, p2 -> if (p1 == p2) 1 else 0 } else -> throw IllegalStateException() } return subPackets .reduce { p1, p2 -> Packet( p1.length + p2.length, p1.versionSum + p2.versionSum, fn(p1.value, p2.value) ) } .let { it.copy(length = it.length + 6, versionSum = it.versionSum + version) } } } } fun main() { val bits = Bits(File("src/day16/input.txt").readText() .map { hex -> Integer.parseInt(hex.toString(), 16) } .map { int -> Integer.toBinaryString(int) } .map { str -> str.padStart(4, '0') } .joinToString("")) bits.getPacket().let { println(it.versionSum) println(it.value) } }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
2,791
advent-of-code-2021
MIT License
advent2021/src/main/kotlin/year2021/day05/Line.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2021.day05 import kotlin.math.max import kotlin.math.min sealed class Line( val from: Point, val to: Point ) { constructor(string: String) : this(Point(string.split("->")[0]), Point(string.split("->")[1])) abstract val points: Set<Point> protected val minX get() = min(from.x, to.x) protected val maxX get() = max(from.x, to.x) protected val minY get() = min(from.y, to.y) protected val maxY get() = max(from.y, to.y) operator fun contains(p: Point) = p in points } open class SimpleLine(string: String): Line(string) { override val points: Set<Point> get() = when { from.x == to.x -> emptySet<Point>() + (minY..maxY).map { y -> Point(to.x, y) } from.y == to.y -> emptySet<Point>() + (minX..maxX).map { x -> Point(x, to.y) } else -> emptySet() } } class ComplexLine(string: String) : SimpleLine(string) { override val points: Set<Point> get() = if (from.x != to.x && from.y != to.y) { val leftEdge = listOf(to, from).minByOrNull { it.x } ?: throw Error("no left edge found") val rightEdge = listOf(to, from).first { it != leftEdge } val factor = if (leftEdge.y - rightEdge.y >= 0) -1 else 1 val incFunc = { steps: Int -> leftEdge.y + factor * steps } emptySet<Point>() + (minX..maxX).map { x -> Point(x, incFunc(x - minX)) } } else super.points }
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,653
advent-of-code
Apache License 2.0
src/main/kotlin/coursera/algorithms1/week1/assignments/interview/UnionFindWithSpecificCanonicalElement.kt
rupeshsasne
359,696,544
false
null
package coursera.algorithms1.week1.assignments.interview class UnionFindWithSpecificCanonicalElement(n: Int) { private val ids = IntArray(n) { it } private val largestValueAt = IntArray(n) { it } private val size = IntArray(n) { 1 } private fun root(p: Int): Int { var trav = p while (ids[trav] != trav) { ids[trav] = ids[ids[trav]] trav = ids[trav] } return trav } fun find(i: Int): Int = largestValueAt[root(i)] fun connected(p: Int, q: Int): Boolean = root(p) == root(q) fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) if (pRoot == qRoot) return val newRoot: Int val oldRoot: Int if (size[pRoot] > size[qRoot]) { ids[qRoot] = pRoot size[pRoot] += size[qRoot] newRoot = pRoot oldRoot = qRoot } else { ids[pRoot] = qRoot size[qRoot] += size[pRoot] newRoot = qRoot oldRoot = pRoot } if (largestValueAt[newRoot] < largestValueAt[oldRoot]) largestValueAt[newRoot] = largestValueAt[oldRoot] } }
0
Kotlin
0
0
e5a9b1f2d1c497ad7925fb38d9e4fc471688298b
1,213
algorithms-sedgewick-wayne
MIT License
Kotlin/src/main/kotlin/org/algorithm/problems/0023_redundant_connection.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
//Problem Statement // // In this problem, a tree is an undirected graph that is connected and has no cycles. // The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), // with one additional edge added. The added edge has two different vertices chosen // from 1 to N, and was not an edge that already existed. // // The resulting graph is given as a 2D-array of edges. Each element of edges is // a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v. // // Return an edge that can be removed so that the resulting graph is a tree of // N nodes. If there are multiple answers, return the answer that occurs last in // the given 2D-array. The answer edge [u, v] should be in the same format, with u < v. // Input: [[1,2], [1,3], [2,3]] // Output: [2,3] package org.algorithm.problems class `0023_redundant_connection` { private lateinit var parent: IntArray private fun find(x: Int): Int { if (parent[x] == x) { return x } return find(parent[x]) } private fun Union(x: Int, y: Int): Boolean { val xparent = find(x) val yparent = find(y) return if (xparent != yparent) { parent[yparent] = xparent true } else { false } } fun findRedundantConnection(edges: Array<IntArray>): IntArray { parent = IntArray(edges.size + 1) for (i in 0 until parent.size) { parent[i] = i } var result: IntArray = intArrayOf() for (edge in edges) { if (!Union(edge[0], edge[1])) { result = edge } } return result; } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
1,727
algorithms
MIT License
word-generator/src/main/kotlin/com/github/pjozsef/wordgenerator/WordGenerator.kt
pjozsef
248,344,539
false
null
package com.github.pjozsef.wordgenerator import com.github.pjozsef.wordgenerator.rule.* import java.util.Random fun generateWord( expression: String, mappings: Map<String, List<String>>, random: Random, rules: List<Rule> = listOf(SubstitutionRule(), InlineSubstitutionRule(), MarkovRule(), ReferenceRule()), maxDepth: Int = 100 ) = generateWord(expression, mappings, random, rules, maxDepth, 0) private tailrec fun generateWord( expression: String, mappings: Map<String, List<String>>, random: Random, rules: List<Rule> = listOf(SubstitutionRule(), InlineSubstitutionRule(), MarkovRule(), ReferenceRule()), maxDepth: Int, currentDepth: Int ): String { check(currentDepth <= maxDepth) { "Reached maximum depth of recursion: $maxDepth" } val (first, second) = doTwoIterations(rules, expression, mappings, random) return if (first == second) { first } else { generateWord(first, mappings, random, rules, maxDepth, currentDepth + 1) } } private fun doTwoIterations(rules: List<Rule>, expression: String, mappings: Map<String, List<String>>, random: Random): Pair<String, String> { val first = rules.fold(expression) { acc, rule -> applyRule(rule, acc, mappings, random) } val second = rules.fold(first) { acc, rule -> applyRule(rule, acc, mappings, random) } return Pair(first, second) } private fun applyRule( rule: Rule, expression: String, mappings: Map<String, List<String>>, random: Random ): String { return rule.regex.findAll(expression).map { val range = it.range val value = rule.evaluate(it.rule(), mappings, random) range to value }.toList().asReversed().fold(expression) { current, (range, value) -> current.replaceRange(range, value) } } private fun MatchResult.rule() = this.groups[1]?.value ?: error("Could not find rule key for matched sequence: $value")
23
Kotlin
0
0
10a40fd61b18b5baf1723fc3b28c6205b7af30cb
1,963
word-generator
MIT License
2022/src/main/kotlin/Day03.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day03 { fun part1(input: String): Int { return input .splitNewlines() .map { line -> line.chunked(line.length / 2) } .map { sacks -> sacks.findCommonItem() } .sumOf { it.priority } } fun part2(input: String): Int { return input .splitNewlines() .chunked(3) .map { sacks -> sacks.findCommonItem() } .sumOf { it.priority } } private fun List<String>.findCommonItem(): Char { return map { it.toCharArray().toSet() } .reduce { acc, chars -> acc.intersect(chars) } .toCharArray()[0] } private val Char.priority: Int get() = if (code >= 97) code - 96 else code - 38 }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
664
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestVariance.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import kotlin.math.max /** * 2272. Substring With Largest Variance * @see <a href="https://leetcode.com/problems/substring-with-largest-variance/">Source</a> */ fun interface LargestVariance { operator fun invoke(s: String): Int } /** * Approach: Kadane's Algorithm */ class LargestVarianceKadane : LargestVariance { override operator fun invoke(s: String): Int { val counter = IntArray(ALPHABET_LETTERS_COUNT) for (ch in s.toCharArray()) { counter[ch.code.minus('a'.code)]++ } var globalMax = 0 for (i in 0 until ALPHABET_LETTERS_COUNT) { for (j in 0 until ALPHABET_LETTERS_COUNT) { // major and minor cannot be the same, and both must appear in s. if (i == j || counter[i] == 0 || counter[j] == 0) { continue } // Find the maximum variance of major - minor. val major = ('a'.code + i).toChar() val minor = ('a'.code + j).toChar() var majorCount = 0 var minorCount = 0 // The remaining minor in the rest of s. var restMinor = counter[j] for (ch in s.toCharArray()) { if (ch == major) { majorCount++ } if (ch == minor) { minorCount++ restMinor-- } // Only update the variance if there is at least one minor. if (minorCount > 0) globalMax = max(globalMax, majorCount - minorCount) // We can discard the previous string if there is at least one remaining minor. if (majorCount < minorCount && restMinor > 0) { majorCount = 0 minorCount = 0 } } } } return globalMax } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,692
kotlab
Apache License 2.0
src/Day06.kt
cgeesink
573,018,348
false
{"Kotlin": 10745}
fun main() { fun CharSequence.isUnique() = toSet().count() == length fun solve(input: String, windowSize: Int): Int { return input .windowedSequence(windowSize) { it.isUnique() }.indexOf(true) + windowSize } val testInput = readInput("Day06_test") check(solve(testInput[0], 4) == 7) check(solve(testInput[1], 4) == 5) check(solve(testInput[2], 4) == 6) check(solve(testInput[3], 4) == 10) check(solve(testInput[4], 4) == 11) check(solve(testInput[0], 14) == 19) check(solve(testInput[1], 14) == 23) check(solve(testInput[2], 14) == 23) check(solve(testInput[3], 14) == 29) check(solve(testInput[4], 14) == 26) val input = readInput("Day06") println(solve(input[0], 4)) println(solve(input[0], 14)) }
0
Kotlin
0
0
137fb9a9561f5cbc358b7cfbdaf5562c20d6b10d
821
aoc-2022-in-kotlin
Apache License 2.0
scout/measures/jvm-benchmarks/src/main/kotlin/scout/benchmark/platform/ResultComparer.kt
yandex
698,181,481
false
{"Kotlin": 369096, "Shell": 1596}
/* * Copyright 2023 Yandex LLC * * 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 scout.benchmark.platform import org.openjdk.jmh.results.RunResult import java.io.File internal fun compareResults(results: Collection<RunResult>) { val current = transformRunResults(results) val control = fetchControlResults() val labels = control.keys + current.keys val longest = labels.maxOfOrNull { label -> label.length } ?: 0 val format = "%-${longest + 2}s %10s %10s %10s %14s" val content = mutableListOf<String>() content += String.format(format, "Benchmark", "Control", "Test", "Diff", "Conclusion") for (label in control.keys + current.keys) { val controlScore = control[label] val currentScore = current[label] val (difference, conclusion) = when { controlScore == null && currentScore == null -> "-" to "" controlScore == null -> "-" to "new" currentScore == null -> "-" to "missing" else -> { val diff = (currentScore - controlScore) / controlScore * 100 if (diff > 0) { val suffix = if (diff > 5.0) " (BAD)" else "" "+${String.format("%.1f", diff)}%" to suffix } else { val suffix = if (diff < -5.0) " (GOOD)" else "" "${String.format("%.1f", diff)}%" to suffix } } } content += String.format( format, label, String.format("%.3f", controlScore), String.format("%.3f", currentScore), difference, conclusion ) } printCompareResult(content) dumpCompareResult(content) } private fun printCompareResult(content: List<String>) { println() for (line in content) { println(line) } } private fun dumpCompareResult(content: List<String>) { File(Environment.RESULT_DIR_PATH).mkdirs() File(Environment.COMPARE_FILE_PATH).apply { createNewFile() writeText(content.joinToString(separator = "\n")) } } private fun transformRunResults(results: Collection<RunResult>): Map<String, Double> { return results.associate { result -> formatBenchmarkId(result) to getBenchmarkScore(result) } }
2
Kotlin
4
87
4a49d143be5d92184bf4bfc540f1e192344914d6
2,822
scout
Apache License 2.0
src/day08/Rope.kt
Frank112
572,910,492
false
null
package day08 import kotlin.math.abs data class Rope(val length: Int) { private var knots: MutableList<Position> = (0 until length).map { Position(0, 0) }.toMutableList() var tailPositionHistory: Set<Position> = setOf(knots.last()) fun handle(command: MoveCommand) { (1..command.count).forEach { _ -> knots[0] = knots[0].move(command.direction) //println("Moved head to ${knots[0]}") for (i in knots.indices.drop(1)) { val previousKnot = knots[i - 1] if (!previousKnot.isConnected(knots[i])) { knots[i] = moveKnotToStayConnected(previousKnot, knots[i]) //println("Moved knot $i to ${knots[i]}") } } tailPositionHistory += knots.last() } } private fun moveKnotToStayConnected(previousKnot: Position, knot: Position): Position { val diffX = knot.x - previousKnot.x val diffY = knot.y - previousKnot.y val diffRowAndCollumn = knot.x != previousKnot.x && knot.y != previousKnot.y var newKnot: Position = knot if (abs(diffX) > 1 || diffRowAndCollumn) { newKnot = if (diffX > 0) newKnot.moveLeft() else newKnot.moveRight() } if (abs(diffY) > 1 || diffRowAndCollumn) { newKnot = if (diffY > 0) newKnot.moveDown() else newKnot.moveUp() } return newKnot } } enum class Direction { UP, DOWN, RIGHT, LEFT } data class MoveCommand(val direction: Direction, val count: Int) data class Position(val x: Int, val y: Int) { fun move(direction: Direction): Position { return when (direction) { Direction.UP -> moveUp() Direction.DOWN -> moveDown() Direction.RIGHT -> moveRight() Direction.LEFT -> moveLeft() } } fun moveUp(): Position { return Position(x, y + 1) } fun moveDown(): Position { return Position(x, y - 1) } fun moveRight(): Position { return Position(x + 1, y) } fun moveLeft(): Position { return Position(x - 1, y) } fun isConnected(other: Position): Boolean { return abs(other.x - x) <= 1 && abs(other.y - y) <= 1 } }
0
Kotlin
0
0
1e927c95191a154efc0fe91a7b89d8ff526125eb
2,282
advent-of-code-2022
Apache License 2.0
src/y2016/Day12.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.readInput data class MachineState( val instructions: MutableList<Instruction>, var instructionIdx: Int = 0, val registers: MutableMap<Char, Int> = mutableMapOf('a' to 0, 'b' to 0, 'c' to 0, 'd' to 0) ) { fun step() { instructions[instructionIdx].executeOn(this) } } sealed class Instruction { companion object { fun parse(string: String): Instruction { val els = string.split(" ") return when (els[0]) { "cpy" -> Copy( fromRegister = if (els[1][0] in "abcd") els[1][0] else null, value = els[1].toIntOrNull(), targetRegister = els[2][0] ) "inc" -> Inc(els[1][0]) "dec" -> Dec(els[1][0]) "jnz" -> Jnz(els[1][0], els[2].toInt()) else -> error("invalid instruction") } } } open fun executeOn(state: MachineState) { state.instructionIdx += 1 } } data class Copy( val fromRegister: Char?, val value: Int?, val targetRegister: Char ) : Instruction() { override fun executeOn(state: MachineState) { super.executeOn(state) state.registers[targetRegister] = fromRegister?.let { state.registers[it] } ?: value!! } } data class Inc( val register: Char ) : Instruction() { override fun executeOn(state: MachineState) { super.executeOn(state) state.registers[register] = (state.registers[register] ?: 0) + 1 } } data class Dec( val register: Char ) : Instruction() { override fun executeOn(state: MachineState) { super.executeOn(state) state.registers[register] = (state.registers[register] ?: 0) - 1 } } data class Jnz( val register: Char, val offset: Int ): Instruction() { override fun executeOn(state: MachineState) { if (state.registers[register] != 0) { state.instructionIdx += offset } else { super.executeOn(state) } } } object Day12 { private fun parse(input: List<String>): MachineState { val instructions = input.map { Instruction.parse(it) }.toMutableList() return MachineState(instructions) } fun part1(input: List<String>): Int? { val state = parse(input) while (state.instructionIdx < state.instructions.size) { state.step() } println(state.registers) return state.registers['a'] } fun part2(input: List<String>): Int? { val state = parse(input) state.registers['c'] = 1 while (state.instructionIdx < state.instructions.size) { state.step() } println(state.registers) return state.registers['a'] } } fun main() { val testInput = """ cpy 41 a inc a inc a dec a jnz a 2 dec a """.trimIndent().split("\n") println("------Tests------") println(Day12.part1(testInput)) println(Day12.part2(testInput)) println("------Real------") val input = readInput("resources/2016/day12") println(Day12.part1(input)) println(Day12.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,240
advent-of-code
Apache License 2.0
src/main/kotlin/Algo.kt
YaroslavGamayunov
321,353,612
false
null
import kotlinx.serialization.Serializable @Serializable data class EarleyRule(val leftPart: Char, val rightPart: String, val dotPosition: Int) { fun getNextSymbol() = rightPart.getOrNull(dotPosition) fun isComplete() = dotPosition == rightPart.length } @Serializable data class Situation(val rule: EarleyRule, val position: Int) class Algo(private val grammar: Grammar) { companion object { fun fit(grammar: Grammar) = Algo(grammar) } fun predict(word: String): Boolean { if (word.any { !grammar.terminals.contains(it) }) { return false } val situations = initialize(word) for (j in 0..word.length) { scan(situations, j, word) var prevSize = -1 while (situations[j].size != prevSize) { prevSize = situations[j].size complete(situations, j) predict(situations, j) } } return situations[word.length].contains( Situation( EarleyRule( SpecialSymbols.SPECIAL_NON_TERMINAL.value, grammar.startNonterminal.toString(), 1 ), 0 ) ) } private fun initialize(word: String): ArrayList<HashSet<Situation>> { val situations = ArrayList<HashSet<Situation>>(word.length) for (i in word.indices + 1) { situations.add(HashSet()) } val initialRule = EarleyRule(SpecialSymbols.SPECIAL_NON_TERMINAL.value, grammar.startNonterminal.toString(), 0) situations[0].add(Situation(initialRule, 0)) return situations } private fun scan(situations: ArrayList<HashSet<Situation>>, j: Int, word: String) { if (j == 0) { return } for (situation in situations[j - 1]) { val rule = situation.rule rule.getNextSymbol()?.let { a -> if (a == word[j - 1]) { situations[j].add(Situation(rule.copy(dotPosition = rule.dotPosition + 1), situation.position)) } } } } private fun predict(situations: ArrayList<HashSet<Situation>>, j: Int) { val updatedData = arrayListOf<Situation>() for (situation in situations[j]) { val rule = situation.rule rule.getNextSymbol()?.let { b -> if (grammar.rules.containsKey(b.toString())) { for (grammarRule in grammar.rules[b.toString()]!!) { updatedData.add(Situation(EarleyRule(b, grammarRule, 0), j)) } } } } situations[j].addAll(updatedData) } private fun complete(situations: ArrayList<HashSet<Situation>>, j: Int) { val updatedData = arrayListOf<Situation>() for ((rule1, i) in situations[j]) { if (!rule1.isComplete()) continue for ((rule2, k) in situations[i]) { rule2.getNextSymbol()?.let { if (it == rule1.leftPart) { updatedData.add(Situation(rule2.copy(dotPosition = rule2.dotPosition + 1), k)) } } } } situations[j].addAll(updatedData) } }
0
Kotlin
0
0
15ca19370d0de9a060fc8881988900b25e126782
3,335
GrammarAnalyzer
MIT License
src/main/kotlin/dp/RingDing.kt
yx-z
106,589,674
false
null
package dp import util.* import kotlin.math.abs // given an array A[1..n], containing either < 0, 0, or > 0 ints, // you traverse A from 1 to n (left to right) // at each index i, you may decide to say either Ring or Ding // if you say Ring, you will earn A[i] points, and if A[i] is negative, you // actually lose -A[i] points // if you say Ding, you will lose A[i] points, and if A[i] is negative, you // actually gain -A[i] points // in other words, Ring for +A[i], Ding for -A[i] // but you cannot say the same word Ring/Ding more than three times in a row // ex. if you decide to say Ring at i = 1, 2, 3, you MUST say Ding at i = 4 // find the max points you can get fun OneArray<Int>.ringDing(): Int { val A = this // assume n > 3, o/w solve by brute force val n = size // 1 2 3 4 5 6 // xdr drr rrr xrd rdd ddd // dp[i, j]: max points i can get given A[1..i] and the last three words // i have said (after the turn @ i) falls to the j-th category described above // r for Ring, d for Ding, x for either Ring or Ding val dp = OneArray(n) { OneArray(6) { 0 } } // space: O(n) dp[3, 1] = abs(A[1]) - A[2] + A[3] dp[3, 2] = -A[1] + A[2] + A[3] dp[3, 3] = A[1] + A[2] + A[3] dp[3, 4] = abs(A[1]) + A[2] - A[3] dp[3, 5] = A[1] - A[2] - A[3] dp[3, 6] = -A[1] - A[2] - A[3] // eval order: increasing i from 4 to n for (i in 4..n) { // no specific order for j dp[i, 1] = A[i] + max(dp[i - 1, 4], dp[i - 1, 5], dp[i - 1, 6]) dp[i, 2] = A[i] + dp[i - 1, 1] dp[i, 3] = A[i] + dp[i - 1, 2] dp[i, 4] = -A[i] + max(dp[i - 1, 1], dp[i - 1, 2], dp[i - 1, 3]) dp[i, 5] = -A[i] + dp[i - 1, 4] dp[i, 6] = -A[i] + dp[i - 1, 5] } // time: O(n) // dp.prettyPrintTable() // we want max_j { dp[n, j] } return dp[n].max()!! } // another solution with simpler recursive functions fun OneArray<Int>.ringDingRedo(): Int { val A = this val n = size // dp(i, w, c): max points i can get given A[1..i] with word w (being either // Ring/1 or Ding/2) said exactly c times (n is 1, 2, 3) val dp = OneArray(n) { OneArray(2) { OneArray(3) { 0 } } } // space: O(n) // dp(1, 1, _) = A[1] // dp(1, 2, _) = -A[1] for (c in 1..3) { dp[1, 1, c] = A[1] dp[1, 2, c] = -A[1] } // dp(i, w, c) = if w = Ring/1: A[i] + // c = 1 -> max{ dp(i - 1, 2, k) } k in 1..3 // c = 2 -> dp(i - 1, 1, 1) // c = 3 -> dp(i - 1, 1, 2) // else w = Ding/2: -A[i] + // c = 1 -> max{ dp(i - 1, 1, k) } k in 1..3 // c = 2 -> dp(i - 1, 2, 1) // c = 3 -> dp(i - 1, 2, 2) // dp(i, _, _) depends on dp(i - 1, _, _) so we will evaluate i increasingly for (i in 2..n) { for (w in 1..2) { for (c in 1..3) { dp[i, w, c] = if (w == 1) { A[i] + when (c) { 1 -> dp[i - 1, 2].max()!! 2 -> dp[i - 1, 1, 1] else -> dp[i - 1, 1, 2] // c == 3 } } else { // w = 2 -A[i] + when (c) { 1 -> dp[i - 1, 1].max()!! 2 -> dp[i - 1, 2, 1] else -> dp[i - 1, 2, 2] // c == 3 } } } } } // we want max_{w, c} { dp(n, w, c) } return dp[n].map { it.max()!! }.max()!! } fun main(args: Array<String>) { val A = oneArrayOf(-1, -2, -3, -100, 6) println(A.ringDing()) println(A.ringDingRedo()) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
3,302
AlgoKt
MIT License
src/main/java/aoc_2019/Day03.kt
frenchfrie
161,678,638
false
{"Java": 64581, "Kotlin": 12191}
package aoc_2019 import org.slf4j.LoggerFactory import java.lang.IllegalStateException import kotlin.math.max import kotlin.math.min class Day03 { private val log = LoggerFactory.getLogger(javaClass) fun distanceFromClosestIntersection(coordinates: String): Int { val lineRaw = coordinates.split("\n") .stream() .map { lr -> lr.split(",") } .map { l -> l.map{ elem -> Vector(elem)} } .map { l -> { val line = ArrayList<Segment>(l.size - 1) val previous = Point(0, 0) for (e in l) { val newPosition = e.move(previous) line.add(Segment(previous, newPosition)) } line } } return 0 } private class Vector(raw: String) { val length: Int = raw.substring(1).toInt() val direction: Char = raw[0] fun move(from : Point) : Point { return when (direction) { 'R' -> Point(from.x + length, from.y) 'L' -> Point(from.x - length, from.y) 'U' -> Point(from.x, from.y + length) 'D' -> Point(from.x, from.y - length) else -> throw RuntimeException("shit") } } } private class Line { val elements = ArrayList<Point>() fun add(point : Point) = elements.add(point) fun intersection(line: Line): List<Point> { val intersections = ArrayList<Point>() var previous = elements[0] for (current in elements) { val currentSegment = Segment(previous, current) var otherPrevious = line.elements[0] for (other in line.elements) { val intersection = currentSegment.intersection(Segment(otherPrevious, other)) if (intersection != null) { intersections.add(intersection) } } } return intersections } } private data class Segment(val a: Point, val b: Point) { fun intersection(segment: Segment): Point? { val intersectX : Int val intersectY : Int if (this.isHoriz()) { intersectY = this.a.y if (segment.isVert()) { intersectX = segment.a.x if ((min(this.a.x, this.b.x) < intersectX && intersectX < max(this.a.x, this.b.x)) && (min(segment.a.y, segment.b.y) < intersectY && intersectY < max(segment.a.y, segment.b.y))) { return Point(intersectX, intersectY) } } } else { intersectX = this.a.y if (segment.isHoriz()) { intersectY = segment.a.x if ((min(this.a.x, this.b.x) < intersectX && intersectX < max(this.a.x, this.b.x)) && (min(segment.a.y, segment.b.y) < intersectY && intersectY < max(segment.a.y, segment.b.y))) { return Point(intersectX, intersectY) } } } return null } private fun isHoriz() = a.x == b.x private fun isVert() = a.y == b.y fun lowerLeftPoint(): Point { return if (a.isLeftOf(b)) { if (a.isUnderOf(b)) { a } else { throw IllegalStateException("should not happen") } } else { if (a.isUnderOf(b)) { throw IllegalStateException("should not happen") } else { b } } } fun upperRightPoint(): Point { return if (this.a == lowerLeftPoint()) this.b else this.a } } private data class Point(val x: Int, val y: Int) { fun isLeftOf(other: Point): Boolean = this.x <= other.x fun isRightOf(other: Point): Boolean = this.x >= other.x fun isUnderOf(other: Point): Boolean = this.y <= other.y fun isAboveOf(other: Point): Boolean = this.y >= other.y } }
2
Java
0
0
b21c991277ce8ae76338620c7002699fb8279f75
4,320
advent-of-code
Apache License 2.0
src/test/kotlin/com/winterbe/kotlin/sequences/AdvancedExamples.kt
winterbe
141,977,205
false
null
package com.winterbe.kotlin.sequences import org.junit.Test class AdvancedExamples { data class Person(val name: String, val age: Int) private val persons = listOf( Person("Peter", 16), Person("Anna", 28), Person("Anna", 23), Person("Sonya", 39) ) @Test fun `reduce sequence of numbers into digit sum`() { val result = sequenceOf(1, 2, 3, 4, 5) .asSequence() .reduce { acc, num -> acc + num } print(result) // 15 } @Test fun flatMap() { val result = sequenceOf(listOf(1, 2, 3), listOf(4, 5, 6)) .flatMap { it.asSequence().filter { it % 2 == 1 } } .toList() print(result) // [1, 3, 5] } @Test fun `flatten elements`() { val result = sequenceOf(listOf(1, 2, 3), listOf(4, 5, 6)) .flatten() .toList() print(result) // [1, 2, 3, 4, 5, 6] } @Test fun `associate by a given property`() { val result = persons .asSequence() .associateBy { it.name } print(result) // {Peter=Person(name=Peter, age=16), Anna=Person(name=Anna, age=23), Sonya=Person(name=Sonya, age=39)} } @Test fun `group by a given property`() { val result = persons .asSequence() .groupBy { it.name } print(result) // {Peter=[Person(name=Peter, age=16)], Anna=[Person(name=Anna, age=28), Person(name=Anna, age=23)], Sonya=[Person(name=Sonya, age=39)]} } @Test fun `any matches predicate`() { val result = sequenceOf(1, 2, 3, 4, 5) .filter { it % 2 == 1 } .any { it % 2 == 0 } print(result) // false } @Test fun `map sequences`() { val map = mapOf( "a" to 10, "b" to 20, "c" to 30 ) val result = map .asSequence() .filter { it.value < 20 } .map { it.key } .single() print(result) // a } @Test fun `sort by property`() { val result = persons .asSequence() .sortedBy { it.age } .toList() print(result) // [Person(name=Peter, age=16), Person(name=Anna, age=23), Person(name=Anna, age=28), Person(name=Sonya, age=39)] } @Test fun `distinct by property`() { val result = persons .asSequence() .distinctBy { it.name } .toList() print(result) // [Person(name=Peter, age=16), Person(name=Anna, age=28), Person(name=Sonya, age=39)] } @Test fun `max by property`() { val result = persons .asSequence() .maxBy { it.age } print(result) // Person(name=Sonya, age=39) } @Test fun `operate on element indices`() { val result = sequenceOf("a", "b", "c", "d") .withIndex() .filter { it.index % 2 == 0 } .map { it.value } .toList() print(result) // [a, c] } @Test fun `add and remove elements from sequence`() { val result = sequenceOf("a", "b", "c") .plus("d") .minus("c") .map { it.toUpperCase() } .toList() print(result) // [A, B, D] } }
0
Kotlin
6
15
69a232febc1bddca0454e21cae5303f896b3a41d
3,406
kotlin-examples
MIT License
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day05.kt
triozer
573,964,813
false
{"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716}
package fr.triozer.aoc.y2022 import fr.triozer.aoc.utils.readInput // #region other-container private class Container { var stacks: MutableMap<Int, ArrayDeque<Char>> = mutableMapOf() fun add(index: Int, char: Char) { if (!stacks.containsKey(index)) stacks[index] = ArrayDeque() stacks[index]!!.add(char) } // #region added-for-part-1 fun moveCrate9000(from: Int, count: Int, to: Int) { val toBeCopied = stacks[from]!!.subList(0, count) toBeCopied.forEach(stacks[to]!!::addFirst) toBeCopied.clear() } // #endregion added-for-part-1 // #region added-for-part-2 fun moveCrate9001(from: Int, count: Int, to: Int) { val toBeCopied = stacks[from]!!.subList(0, count) toBeCopied.reversed().forEach(stacks[to]!!::addFirst) toBeCopied.clear() } // #endregion added-for-part-2 fun firsts() = stacks.toSortedMap() .map { it.value.first() } .joinToString("") } // #endregion other-container // #region other-parse-container private fun List<String>.toContainer(): Pair<Container, Int> { val container = Container() var lineIndex = 0 // it is used to keep a track of the current line index for (i in this.indices) { val line = this[i] lineIndex++ if (line.isBlank()) break for (charIndex in 1 until line.length step 4) { var char = line[charIndex] if (!char.isLetter()) continue container.add(charIndex / 4, char) } } return Pair(container, lineIndex) } // #endregion other-parse-container // #region other-parse-instructions private fun List<String>.toInstructions(): List<List<Int>> = this .map { val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex() val matchResult = regex.find(it) matchResult!!.destructured.toList().map { n -> n.toInt() } } // #endregion other-parse-instructions // #region part1 private fun part1(input: List<String>): String { val (container, lineIndex) = input.toContainer() input.subList(lineIndex, input.size) .toInstructions() .forEach { (count, from, to) -> container.moveCrate9000(from - 1, count, to - 1) } return container.firsts() } // #endregion part1 // #region part2 private fun part2(input: List<String>): String { val (container, lineIndex) = input.toContainer() input.subList(lineIndex, input.size) .toInstructions() .forEach { (count, from, to) -> container.moveCrate9001(from - 1, count, to - 1) } return container.firsts() } // #endregion part2 private fun main() { val testInput = readInput(2022, 5, "test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") println("Checks passed ✅") val input = readInput(2022, 5, "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a9f47fa0f749a40e9667295ea8a4023045793ac1
2,929
advent-of-code
Apache License 2.0
src/main/aoc2015/Day16.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 class Day16(input: List<String>) { private val realSue = """ children: 3 cats: 7 samoyeds: 2 pomeranians: 3 akitas: 0 vizslas: 0 goldfish: 5 trees: 3 cars: 2 perfumes: 1 """.trimIndent().split("\n").associate { line -> line.split(": ").let { it.first() to it.last().toInt() } } private val memories = parseInput(input) private fun parseInput(input: List<String>): List<Pair<Int, Map<String, Int>>> { return input.map {line -> val sue = line.substringBefore(":").substringAfter(" ").toInt() val list = line.substringAfter(": ") val parts = list.split(", ") val parsed = parts.associate { part -> part.split(": ").let { it.first() to it.last().toInt() } } sue to parsed } } fun solvePart1(): Int { memories.forEach {memory -> val found = memory.second.all { (key, value) -> realSue[key] == value } if (found) { return memory.first } } return -1 } fun solvePart2(): Int { memories.forEach {memory -> var found = true memory.second.forEach { (key, value) -> found = when (key) { "cat", "trees" -> found && value > realSue.getValue(key) "pomeranians", "goldfish" -> found && value < realSue.getValue(key) else -> found && realSue[key] == value } } if (found) { return memory.first } } return -1 } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,703
aoc
MIT License
src/Day19.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
private enum class Mineral { ORE, CLAY, OBSIDIAN, GEODE } private enum class MiningRobot { ORE_ROBOT, CLAY_ROBOT, OBSIDIAN_ROBOT, GEODE_ROBOT } fun main() { data class Cost( val oreCount: Int = 0, val clayCount: Int = 0, val obsidianCount: Int = 0, val geodeCount: Int = 0, ) { fun forMineral(mineral: Mineral) = when (mineral) { Mineral.ORE -> oreCount Mineral.CLAY -> clayCount Mineral.OBSIDIAN -> obsidianCount Mineral.GEODE -> geodeCount } } class Blueprint( val id: Int, oreRobotCost: Cost, clayRobotCost: Cost, obsidianRobotCost: Cost, geodeRobotCost: Cost ) { val costs: Map<MiningRobot, Cost> init { costs = mapOf( MiningRobot.ORE_ROBOT to oreRobotCost, MiningRobot.CLAY_ROBOT to clayRobotCost, MiningRobot.OBSIDIAN_ROBOT to obsidianRobotCost, MiningRobot.GEODE_ROBOT to geodeRobotCost, ) } fun costOf(robot: MiningRobot): Cost = costs[robot] ?: error("No price for robot $robot") } fun parseBlueprint(str: String): Blueprint { val pattern = Regex( "Blueprint (\\d+): Each ore robot costs (\\d+) ore. " + "Each clay robot costs (\\d+) ore. " + "Each obsidian robot costs (\\d+) ore and (\\d+) clay. " + "Each geode robot costs (\\d+) ore and (\\d+) obsidian\\." ) val ( id, oreRobotOre, clayRobotOre, obsidianRobotOre, obsidianRobotClay, geodeRobotOre, geodeRobotObsidian, ) = pattern.matchEntire(str)?.destructured ?: error("Cannot match string: '$str'") return Blueprint( id.toInt(), Cost(oreCount = oreRobotOre.toInt()), Cost(oreCount = clayRobotOre.toInt()), Cost(oreCount = obsidianRobotOre.toInt(), clayCount = obsidianRobotClay.toInt()), Cost(oreCount = geodeRobotOre.toInt(), obsidianCount = geodeRobotObsidian.toInt()), ) } data class State( val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int, val oreCount: Int, val clayCount: Int, val obsidianCount: Int, val geodeCount: Int, ) { fun crystalsPerTick(): Cost { return Cost( oreCount = oreRobots, clayCount = clayRobots, obsidianCount = obsidianRobots, geodeCount = geodeRobots, ) } fun canBuy(cost: Cost): Boolean { return oreCount >= cost.forMineral(Mineral.ORE) && clayCount >= cost.forMineral(Mineral.CLAY) && obsidianCount >= cost.forMineral(Mineral.OBSIDIAN) && geodeCount >= cost.forMineral(Mineral.GEODE) } fun addCost(cost: Cost): State = copy( oreCount = (oreCount + cost.forMineral(Mineral.ORE)), clayCount = (clayCount + cost.forMineral(Mineral.CLAY)), obsidianCount = (obsidianCount + cost.forMineral(Mineral.OBSIDIAN)), geodeCount = (geodeCount + cost.forMineral(Mineral.GEODE)), ) fun removeCost(cost: Cost): State = copy( oreCount = (oreCount - cost.forMineral(Mineral.ORE)), clayCount = (clayCount - cost.forMineral(Mineral.CLAY)), obsidianCount = (obsidianCount - cost.forMineral(Mineral.OBSIDIAN)), geodeCount = (geodeCount - cost.forMineral(Mineral.GEODE)), ) fun addRobot(robot: MiningRobot): State = when (robot) { MiningRobot.ORE_ROBOT -> copy(oreRobots = (oreRobots + 1)) MiningRobot.CLAY_ROBOT -> copy(clayRobots = (clayRobots + 1)) MiningRobot.OBSIDIAN_ROBOT -> copy(obsidianRobots = (obsidianRobots + 1)) MiningRobot.GEODE_ROBOT -> copy(geodeRobots = (geodeRobots + 1)) } } fun nextStates(originalState: State, blueprint: Blueprint): List<State> = buildList { val crystals = originalState.crystalsPerTick() val baseNextState = originalState.addCost(crystals) fun yield(s: State) = add(s) var canBuyRobots = 0 for (robot in MiningRobot.values()) { val robotCost = blueprint.costOf(robot) if (originalState.canBuy(robotCost)) { yield(baseNextState.removeCost(robotCost).addRobot(robot)) canBuyRobots++ } } if (canBuyRobots != MiningRobot.values().size) { yield(baseNextState) } } fun evaluate2(blueprint: Blueprint, time: Int): Int { var states = listOf( State( oreRobots = 1, clayRobots = 0, obsidianRobots = 0, geodeRobots = 0, oreCount = 0, clayCount = 0, obsidianCount = 0, geodeCount = 0, ) ) repeat(time) { currentTime -> println("time: $currentTime, states number: ${states.size}") val newStates = mutableListOf<State>() for (state in states) { newStates += nextStates(state, blueprint) } // This is very dirty hack states = if (currentTime < 25) { newStates.distinct() } else { newStates.distinct().sortedByDescending { it.geodeCount }.take(newStates.size / 2) } } return states.maxOf { it.geodeCount }.also { println("blueprint ${blueprint.id}, max is $it") } } fun part1(input: List<String>): Int { val blueprints = input.map { parseBlueprint(it) } return blueprints.map { evaluate2(it, time = 24) * it.id }.sum() } fun part2(input: List<String>): Int { val blueprints = input.map { parseBlueprint(it) }.take(3) return blueprints.map { evaluate2(it, time = 32) }.reduce(Int::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day19_test") check(part1(testInput) == 33) check(part2(testInput) == 3472) val input = readInput("Day19") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
6,490
aoc2022
Apache License 2.0
aoc16/day_08/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File fun print_display(display: Array<Array<Boolean>>) = display.forEach { it.forEach { print(if (it) '#' else '.') }; println() } fun main() { val instructions = File("input").readLines() val display = Array(6) { Array(50) { false } } for (inst in instructions) { if (inst.startsWith("rect")) { val A = inst.split(" ")[1].split("x")[0].toInt() val B = inst.split(" ")[1].split("x")[1].toInt() display .take(B) .forEach { row -> row.take(A).forEachIndexed { i, _ -> row[i] = true } } } else if (inst.startsWith("rotate row")) { val A = inst.split("y=")[1].split("by")[0].trim().toInt() val B = inst.split("y=")[1].split("by")[1].trim().toInt() display[A] = display[A].sliceArray(50 - B until 50) + display[A].sliceArray(0 until 50 - B) } else if (inst.startsWith("rotate column")) { val A = inst.split("x=")[1].split("by")[0].trim().toInt() val B = inst.split("x=")[1].split("by")[1].trim().toInt() val column = display.map { it[A] }.slice(6 - B until 6) + display.map { it[A] }.slice(0 until 6 - B) for (i in 0 until column.size) { display[i][A] = column[i] } } } val first = display.map { it.filter { it }.count() }.sum() println("First: $first") println("Second:") print_display(display) }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
1,496
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/dp/LCS.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.dp /** * The longest common subsequence. */ fun interface LCS { fun perform(x: String, y: String, m: Int, n: Int): Int } class LCSRecursive : LCS { override fun perform(x: String, y: String, m: Int, n: Int): Int { if (m == 0 || n == 0) return 0 val xArr = x.toCharArray() val yArr = y.toCharArray() return if (xArr[m - 1] == yArr[n - 1]) { 1 + perform(x, y, m - 1, n - 1) } else { maxOf(perform(x, y, m, n - 1), perform(x, y, m - 1, n)) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,163
kotlab
Apache License 2.0
advent-of-code-2022/src/test/kotlin/Day 24 Blizzard Basin.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class `Day 24 B<NAME>` { private fun Point.neighbors(): List<Point> = listOf(up(), down(), left(), right()) data class State( val steps: Int, val blizzards: List<Pair<Point, Char>>, val pos: Set<Point>, ) @Test fun silverTest() { findWayOutOnce(testInput2) shouldBe 18 } @Test fun silver() { findWayOutOnce(loadResource("day24")) shouldBe 277 } @Test fun goldTest() { findWayOutReturnAndGoBack(testInput2) shouldBe 54 } @Test fun gold() { findWayOutReturnAndGoBack(loadResource("day24")) shouldBe 877 } private fun findWayOutOnce(input: String): Int { val map = parseMap(input) val (start, end) = map.keys.filter { point -> map[point] == '.' && point.neighbors().count { map[it] == '#' } == 2 } val blizzards = map.filterValues { it == '^' || it == '>' || it == 'v' || it == '<' } .map { (k, v) -> k to v } return findWay(map.filterValues { it == '#' }.keys, blizzards, start, end).steps + 1 } private fun findWayOutReturnAndGoBack(input: String): Int { val map = parseMap(input) val (start, end) = map.keys.filter { point -> map[point] == '.' && point.neighbors().count { map[it] == '#' } == 2 } val blizzards = map.filterValues { it == '^' || it == '>' || it == 'v' || it == '<' } .map { (k, v) -> k to v } val bounds = map.filterValues { it == '#' }.keys val firstRun = findWay(bounds, blizzards, start, end) val secondRun = findWay(bounds, firstRun.blizzards, end, start) val thirdRun = findWay(bounds, secondRun.blizzards, start, end) return firstRun.steps + secondRun.steps + thirdRun.steps + 1 } private fun findWay( bounds: Set<Point>, blizzards: List<Pair<Point, Char>>, start: Point, end: Point ): State { val maxX = bounds.maxOf { it.x } val minX = bounds.minOf { it.x } val maxY = bounds.maxOf { it.y } val minY = bounds.minOf { it.y } return generateSequence(State(0, blizzards, setOf(start))) { state -> val nextBlizzards = state.blizzards.map { (point, direction) -> when (direction) { '^' -> point.up().takeIf { it.y > minY } ?: point.copy(y = maxY - 1) '>' -> point.right().takeIf { it.x < maxX } ?: point.copy(x = minX + 1) 'v' -> point.down().takeIf { it.y < maxY } ?: point.copy(y = minY + 1) '<' -> point.left().takeIf { it.x > minX } ?: point.copy(x = maxX - 1) else -> error("") } to direction } val blizzardMap = nextBlizzards.associate { it } val possibleMoves = state.pos .flatMap { it.neighbors() + it } .filter { it !in blizzardMap && it !in bounds && it.y in minY..maxY } .toSet() State(state.steps + 1, nextBlizzards, possibleMoves) } .takeWhile { state -> end !in state.pos } .last() } private val testInput1 = """ #.##### #.....# #>....# #.....# #...v.# #.....# #####.# """.trimIndent() private val testInput2 = """ #.###### #>>.<^<# #.<..<<# #>v.><># #<^v^^># ######.# """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
3,378
advent-of-code
MIT License
src/main/kotlin/github/walkmansit/aoc2020/Day13.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 import kotlin.math.ceil class Day13(val input: List<String>) : DayAoc<Int, Long> { private class BusSchedule(val earliestTime: Int, val busTs: Collection<Int>) { fun findEarliest(): Int { var minDt = Int.MAX_VALUE var id = 0 for (ts in busTs) { if (ts != -1) { val closest = ceil(earliestTime / ts.toDouble()).toInt() * ts val t = closest - earliestTime if (t < minDt) { minDt = t id = ts } } } return id * minDt } private fun findMaxWithId(): Pair<Int, Int> { var pair = 0 to 0 for ((i, v) in busTs.withIndex()) { if (v > pair.second) pair = i to v } return pair } fun findEarliestOffsetMatch(): Long { val maxPair = findMaxWithId() // Index, Value var candidate: Long = maxPair.second.toLong() while (!fullMatch(candidate, maxPair)) { candidate += maxPair.second } return candidate - maxPair.first } private fun fullMatch(candidateMax: Long, maxPair: Pair<Int, Int>): Boolean { for ((i, v) in busTs.withIndex()) { if (v != -1 && i != maxPair.first) { val candidate = candidateMax - (maxPair.first - i) if (candidate % v != 0L) return false } } return true } fun findWithChineeseTheoreme(): Long { fun mod(a: Int, b: Int): Int { var ar = a while (ar < b) ar += a return ar % b } fun mod(a: Long, b: Long): Long { var ar = a while (ar < b) ar += a return ar % b } fun getPositiveAi(i: Int, mi: Int): Int { var result = -i while (result < 0) result += mi return result } fun findMi(mi: Array<Int>): Array<Long> { val result = Array(mi.size) { 0L } for (i in mi.indices) { var mult = 1L for ((j, k) in mi.withIndex()) { if (i != j) mult *= k } result[i] = mult } return result } fun findYi(idx: Int, Mi: Array<Long>, ai: Array<Int>, mi: Array<Int>): Int { var y = 1 val mis = (Mi[idx] % mi[idx]).toInt() while (true) { if ((((mis * y) - ai[idx]) % mi[idx]) == 0) return y y++ } return y } val aiB = mutableListOf<Int>() val miB = mutableListOf<Int>() for ((i, v) in busTs.withIndex()) { if (v != -1) { miB.add(v) aiB.add(getPositiveAi(i, v)) } } val ai = aiB.toTypedArray() val mi = miB.toTypedArray() val mBi = findMi(mi) val yi = Array(ai.size) { 0 } var sum = 0L for (i in yi.indices) { yi[i] = findYi(i, mBi, ai, mi) sum += mBi[i] * yi[i] } val m0: Long = mi[0] * mBi[0] return mod(sum, m0) } companion object { fun fromInput(lines: List<String>): BusSchedule { return BusSchedule( lines[0].toInt(), lines[1].split(",").map { i -> if (i == "x") -1 else i.toInt() } ) } } } override fun getResultPartOne(): Int { return BusSchedule.fromInput(input).findEarliest() } override fun getResultPartTwo(): Long { return BusSchedule.fromInput(input).findWithChineeseTheoreme() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
4,270
AdventOfCode2020
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day23.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution import at.mpichler.aoc.lib.Vector2i import at.mpichler.aoc.lib.moves open class Part23A : PartSolution() { private lateinit var elves: MutableMap<Vector2i, Elf> var numRounds = 0 override fun parseInput(text: String) { elves = mutableMapOf() var i = 0 for ((y, line) in text.split("\n").withIndex()) { for ((x, char) in line.withIndex()) { if (char == '#') { val pos = Vector2i(x, y) elves[pos] = Elf(i, pos) i += 1 } } } } override fun config() { numRounds = 10 } override fun compute(): Int { doRounds() return getBounds() } fun doRounds(): Int { var i = 0 while (true) { val anyMoved = doRound() i += 1 if (!anyMoved || i >= numRounds) { break } } return i } private fun doRound(): Boolean { val elves = this.elves.values.toList() elves.forEach { it.prepareMove(this.elves) } return elves.map { it.move(this.elves) }.any { it } } private fun getBounds(): Int { val min = elves.values.map { it.pos }.reduce { acc, elf -> at.mpichler.aoc.lib.min(acc, elf) } val max = elves.values.map { it.pos }.reduce { acc, elf -> at.mpichler.aoc.lib.max(acc, elf) } val diff = (max - min + 1) return diff.x * diff.y - elves.size } override fun getExampleAnswer(): Int { return 110 } data class Elf(val id: Int, var pos: Vector2i) { private val moves = mutableListOf(Vector2i(0, -1), Vector2i(0, 1), Vector2i(-1, 0), Vector2i(1, 0)) private var consideredMove: Vector2i? = null private var lastPos = pos fun prepareMove(elves: Map<Vector2i, Elf>) { lastPos = pos val availableMoves = moves.toMutableList() val move = moves.removeFirst() moves.add(move) for (p in moves(diagonals = true)) { if (availableMoves.isEmpty()) { break } if (pos + p in elves) { if (p.y < 0 && Vector2i(0, -1) in availableMoves) { availableMoves.remove(Vector2i(0, -1)) } if (p.y > 0 && Vector2i(0, 1) in availableMoves) { availableMoves.remove(Vector2i(0, 1)) } if (p.x < 0 && Vector2i(-1, 0) in availableMoves) { availableMoves.remove(Vector2i(-1, 0)) } if (p.x > 0 && Vector2i(1, 0) in availableMoves) { availableMoves.remove(Vector2i(1, 0)) } } } consideredMove = if (availableMoves.size in 1..<moves.size) { availableMoves.removeFirst() } else { null } } fun move(elves: MutableMap<Vector2i, Elf>): Boolean { if (consideredMove == null) { return false } val newPos = pos + consideredMove!! if (newPos in elves) { elves[newPos]!!.goBack(elves) return false } elves.remove(pos) pos = newPos elves[newPos] = this return true } private fun goBack(elves: MutableMap<Vector2i, Elf>) { elves.remove(pos) pos = lastPos elves[pos] = this } } } class Part23B : Part23A() { override fun config() { numRounds = 1_000_000 } override fun compute(): Int { return doRounds() } override fun getExampleAnswer(): Int { return 20 } } fun main() { Day(2022, 23, Part23A(), Part23B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
4,069
advent-of-code-kotlin
MIT License
src/main/kotlin/dev/claudio/adventofcode2022/Day2Part2.kt
ClaudioConsolmagno
572,915,041
false
{"Kotlin": 41573}
package dev.claudio.adventofcode2022 fun main() { Day2Part2().main() } private class Day2Part2 { fun main() { val inputList: List<String> = Support.readFileAsListString("2022/day2-input.txt") val sumOf = inputList.map { Round(it.split(" ")[0], it.split(" ")[1]) } .map { println(it.calcResult()); it } .sumOf { it.calcResult() } println(sumOf) } private data class Round(val left: String, val right: String) { val shapeScores = mapOf( "A" to 1, // rock "B" to 2, // paper "C" to 3, // scissors "X" to 1, // rock "Y" to 2, // peper "Z" to 3, // scissors ) val permutationScores = mapOf( Pair("A", "Z") to 3, Pair("B", "X") to 1, Pair("C", "Y") to 2, Pair("C", "X") to 7, Pair("A", "Y") to 8, Pair("B", "Z") to 9, ) val replacements = mapOf( Pair("A", "X") to "Z", Pair("A", "Y") to "X", Pair("A", "Z") to "Y", Pair("B", "X") to "X", Pair("B", "Y") to "Y", Pair("B", "Z") to "Z", Pair("C", "X") to "Y", Pair("C", "Y") to "Z", Pair("C", "Z") to "X", ) fun calcResult() : Int { return permutationScores[Pair(left,replacements[Pair(left, right)])] ?: ((shapeScores[replacements[Pair(left, right)]] ?: 0) + 3) } } }
0
Kotlin
0
0
43e3f1395073f579137441f41cd5a63316aa0df8
1,509
adventofcode-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-12.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.CharGrid import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.filterIn import com.github.ferinagy.adventOfCode.get import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.set import com.github.ferinagy.adventOfCode.searchGraph import com.github.ferinagy.adventOfCode.singleStep import com.github.ferinagy.adventOfCode.toCharGrid fun main() { val input = readInputLines(2022, "12-input") val testInput1 = readInputLines(2022, "12-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: List<String>): Int { val grid = input.toCharGrid() val start = grid.getCoords('S') grid[start] = 'a' val end = grid.getCoords('E') grid[end] = 'z' return searchGraph( start = start, isDone = { it == end }, nextSteps = { current -> val height = grid[current].code val neighbors = current.adjacent(false) .filterIn(grid.xRange, grid.yRange) .filter { grid[it].code - height <= 1 } neighbors.toSet().singleStep() }, ) } private fun part2(input: List<String>): Int { val grid = input.toCharGrid() val start = grid.getCoords('S') grid[start] = 'a' val end = grid.getCoords('E') grid[end] = 'z' return searchGraph( start = end, isDone = { grid[it] == 'a' }, nextSteps = { current -> val height = grid[current].code val neighbors = current.adjacent(false) .filterIn(grid.xRange, grid.yRange) .filter { height - grid[it].code <= 1 } neighbors.toSet().singleStep() }, ) } private fun CharGrid.getCoords(c: Char): Coord2D { for (x in xRange) { for (y in yRange) { if (get(x, y) == c) return Coord2D(x, y) } } error("'$c' not found") }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,194
advent-of-code
MIT License
functional-kotlin-basics-solution/src/main/kotlin/ch/sbb/functionalkotlin/basics/Recursion.kt
burriad
299,246,489
false
null
package ch.sbb.functionalkotlin.basics // 2.1 Given the function prepend, write a recursive function concat that concatenates a list of chars to a string fun prepend(c: Char, s: String): String = "$c$s" fun concat(chars: List<Char>): String = if (chars.isEmpty()) "" else prepend(chars.first(), concat(chars.takeLast(chars.size - 1))) // 2.2 Create a recursive version of a function that computes the n-th number in the Fibonacci sequence // Hint: the Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13, 21; hence the n-th number in the sequence is the sum of the (n-2)th and (n-1)th numbers fun fibRec(n: Int): Int = when (n) { 0 -> 0 1 -> 1 else -> fibRec(n - 1) + fibRec(n - 2) } // 2.3 (HARD) Create a tail-recursive version of the function in 2.2 fun fibCorec(n: Int): Int { tailrec fun _fib(n: Int, prev2: Int, prev1: Int): Int = when (n) { 0 -> prev2 1 -> prev1 else -> _fib(n - 1, prev1, prev2 + prev1) } return _fib(n, 0, 1) } // 2.4 (Extra) Write a binary search function which takes a sorted list of ints and checks whether an element is present fun binarySearch(value: Int, list: List<Int>): Boolean = when { list.isEmpty() -> false list[middle(list)] < value -> binarySearch(value, list.subList(0, middle(list))) list[middle(list)] > value -> binarySearch(value, list.subList(middle(list) + 1, list.size)) else -> true // list[middle(list)] == value } fun middle(list: List<Int>) = list.size / 2
0
Kotlin
0
0
d27e471737c66bde80c15da29083654cf6c49a69
1,612
functional-kotlin
Apache License 2.0
src/Day03.kt
zhtk
579,137,192
false
{"Kotlin": 9893}
fun main() { val input = readInput("Day03") input.sumOf { val firstCompartment = it.substring(0, it.length / 2).toSet() val secondCompartment = it.substring(it.length / 2, it.length).toSet() val itemInBothCompartments = firstCompartment.find { secondCompartment.contains(it) }!! getPriority(itemInBothCompartments) }.println() input.chunked(3).sumOf { chunk -> chunk[0].filter { chunk[1].contains(it) }.first { chunk[2].contains(it) }.let { getPriority(it) } }.println() } fun getPriority(item: Char): Int = if (item in 'A'..'Z') item - 'A' + 27 else item - 'a' + 1
0
Kotlin
0
0
bb498e93f9c1dd2cdd5699faa2736c2b359cc9f1
627
aoc2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestMerge.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 /** * 1754. Largest Merge Of Two Strings * @see <a href="https://leetcode.com/problems/largest-merge-of-two-strings/">Source</a> */ fun interface LargestMerge { operator fun invoke(word1: String, word2: String): String } class LargestMergeGreedy : LargestMerge { override operator fun invoke(word1: String, word2: String): String { return largestMerge(word1, word2) } private fun largestMerge(s1: String, s2: String): String { if (s1.isEmpty() || s2.isEmpty()) return s1 + s2 return if (s1 > s2) { s1[0].toString() + largestMerge(s1.substring(1), s2) } else { s2[0].toString() + largestMerge(s1, s2.substring(1)) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,350
kotlab
Apache License 2.0
src/main/kotlin/sschr15/aocsolutions/Day16.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import sschr15.aocsolutions.util.* /** * AOC 2023 [Day 16](https://adventofcode.com/2023/day/16) * Challenge: We got lasers! (and a sixth grid this year what the heck) but how much energy is it really? */ object Day16 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 16) { // test() fun calculate(inputLines: List<String>, start: Point, startDirection: Direction = Direction.East): Int { val grid = inputLines.map { s -> s.map { it to 0 } }.toGrid() val toTrack = mutableListOf(start to startDirection) while (toTrack.isNotEmpty()) { val (point, direction) = toTrack.removeFirst() if (point !in grid) continue val (char, flags) = grid[point] val flag = when (direction) { Direction.North -> 1 Direction.East -> 2 Direction.South -> 4 Direction.West -> 8 } if (flags and flag != 0) continue // already visited in this direction (probably loop) when (char) { '/' -> { val newDirection = when (direction) { Direction.North -> Direction.East Direction.East -> Direction.North Direction.South -> Direction.West Direction.West -> Direction.South } toTrack.add(newDirection.mod(point) to newDirection) } '\\' -> { val newDirection = when (direction) { Direction.North -> Direction.West Direction.East -> Direction.South Direction.South -> Direction.East Direction.West -> Direction.North } toTrack.add(newDirection.mod(point) to newDirection) } '|' -> { if (direction == Direction.East || direction == Direction.West) { toTrack.add(point.up() to Direction.North) toTrack.add(point.down() to Direction.South) } else { toTrack.add(direction.mod(point) to direction) } } '-' -> { if (direction == Direction.North || direction == Direction.South) { toTrack.add(point.left() to Direction.West) toTrack.add(point.right() to Direction.East) } else { toTrack.add(direction.mod(point) to direction) } } else -> toTrack.add(direction.mod(point) to direction) } grid[point] = char to (flags or flag) } return grid.flatten().count { (_, i) -> i != 0 } } part1 { calculate(inputLines, Point(0, 0)) } part2 { val results = mutableListOf<Int>() for (y in inputLines.indices) { results.add(calculate(inputLines, Point(0, y), Direction.East)) results.add(calculate(inputLines, Point(inputLines[0].length - 1, y), Direction.West)) } for (x in inputLines[0].indices) { results.add(calculate(inputLines, Point(x, 0), Direction.South)) results.add(calculate(inputLines, Point(x, inputLines.size - 1), Direction.North)) } results.maxOrNull() ?: error("no max") } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
3,952
advent-of-code
MIT License
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day10/Day10.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pietromaggi.aoc2021.day10 import com.pietromaggi.aoc2021.readInput val opening = setOf('(', '[', '{', '<') val closing = setOf(')', ']', '}', '>') val mapping = mapOf(')' to '(', ']' to '[', '}' to '{', '>' to '<') fun part1(input: List<String>): Int { val points = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) val parens = mutableListOf<Char>() var result = 0 checkLine@ for (line in input) { parens.clear() for (paren in line) { if (opening.contains(paren)) parens.add(paren) if (closing.contains(paren)) { if (mapping[paren] != parens.last()) { result += points[paren] as Int continue@checkLine } parens.removeLast() } } } return result } fun part2(input: List<String>): Long { val points = mapOf( '(' to 1, '[' to 2, '{' to 3, '<' to 4 ) val parens = mutableListOf<Char>() val resultList = mutableListOf<Long>() checkLine@ for (line in input) { parens.clear() for (paren in line) { if (opening.contains(paren)) parens.add(paren) if (closing.contains(paren)) { if (mapping[paren] != parens.last()) { continue@checkLine } parens.removeLast() } } resultList.add(parens.reversed().fold(0) {sum, paren -> sum * 5 + points[paren] as Int}) } resultList.sort() return resultList[resultList.size / 2] } fun main() { val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
2,345
AdventOfCode
Apache License 2.0
module-tool/src/main/kotlin/de/twomartens/adventofcode/day10/graph/GraphWalker.kt
2martens
729,312,999
false
{"Kotlin": 89431}
package de.twomartens.adventofcode.day10.graph import de.twomartens.adventofcode.day10.node.* import mu.KotlinLogging class GraphWalker { fun findFurthestDistance(graph: Graph): Int { val startNode = findStartNode(graph) val (_, _, distance) = findLoop(startNode, graph) return distance } fun findNumberOfContainedNodes(graph: Graph): Int { val startNode = findStartNode(graph) val (visitedNodes, newStartNode, _) = findLoop(startNode, graph) visitedNodes.filterIsInstance<AdjustableColourNode>() .forEach { it.colour = NodeColour.LOOP } graph.replaceNode(startNode.index, newStartNode) colourNodes(graph) log.debug { graph.printGraphString() } val innerNodes = graph.nodes.filter { it.colour == NodeColour.INSIDE } return innerNodes.size } private fun findStartNode(graph: Graph): Node { val startPosition = graph.startPosition val startNode = graph.rows[startPosition.first][startPosition.second] return startNode } private fun findLoop(startNode: Node, graph: Graph): Triple<Collection<Node>, Node, Int> { val visitedNodes = mutableSetOf<Node>() var furthestDistance = 0 val queue = initializeQueue(startNode) while (queue.isNotEmpty()) { val (currentNode, distance) = queue.removeFirst() visitedNodes.add(currentNode) if (distance > furthestDistance) { furthestDistance = distance } val neighbours = findNeighbours(currentNode, graph) for (neighbour in neighbours) { if (isReachable(visitedNodes, currentNode, neighbour)) { queue.add(neighbour to distance + 1) } } } val neighboursOfStart = visitedNodes.filter { it.isConnectedTo(startNode) && startNode.isConnectedTo(it) } val realStartNodeType = findStartNodeType(startNode.index, neighboursOfStart) val realStartNode = Node.of(realStartNodeType, startNode.index) visitedNodes.remove(startNode) visitedNodes.add(realStartNode) return Triple(visitedNodes, realStartNode, furthestDistance) } private fun colourNodes(graph: Graph) { val uncolouredNodes = graph.nodes.filter { it.colour == NodeColour.UNKNOWN } val intersectionFinder = IntersectionFinder() for (node in uncolouredNodes) { if (node !is AdjustableColourNode) { continue } val nodesToBorder = mutableListOf<Node>(node) var neighbour = node do { neighbour = findNode(graph, neighbour.westIndex()) nodesToBorder.add(neighbour) } while (neighbour !is BorderNode) val intersections = intersectionFinder.findNumberOfIntersections(nodesToBorder) if (isOdd(intersections)) { node.colour = NodeColour.INSIDE } else { node.colour = NodeColour.OUTSIDE } } } private fun isOdd(intersections: Int) = intersections % 2 == 1 private fun initializeQueue(startNode: Node): ArrayDeque<Pair<Node, Int>> { val queue = ArrayDeque<Pair<Node, Int>>() queue.add(startNode to 0) return queue } private fun findNeighbours( currentNode: Node, graph: Graph ): List<Node> { val neighbours = listOf( currentNode.northIndex(), currentNode.eastIndex(), currentNode.southIndex(), currentNode.westIndex() ).map { (row, col) -> findNode(graph, row, col) } return neighbours } private fun findStartNodeType(startNodeIndex: Pair<Int, Int>, neighbours: Collection<Node>): NodeType { if (neighbours.size != 2) { throw IllegalArgumentException("Neighbours must have size 2") } val firstNode = neighbours.first() val firstNodeType = firstNode.nodeType val secondNode = neighbours.last() val secondNodeType = secondNode.nodeType if (firstNodeType == secondNodeType) { return firstNodeType } if (firstNode.northIndex() == startNodeIndex && secondNode.southIndex() == startNodeIndex || firstNode.southIndex() == startNodeIndex && secondNode.northIndex() == startNodeIndex) { return NodeType.VERTICAL } if (firstNode.eastIndex() == startNodeIndex && secondNode.westIndex() == startNodeIndex || firstNode.westIndex() == startNodeIndex && secondNode.eastIndex() == startNodeIndex) { return NodeType.HORIZONTAL } if (firstNode.northIndex() == startNodeIndex && secondNode.westIndex() == startNodeIndex || firstNode.westIndex() == startNodeIndex && secondNode.northIndex() == startNodeIndex) { return NodeType.SOUTH_EAST } if (firstNode.southIndex() == startNodeIndex && secondNode.westIndex() == startNodeIndex || firstNode.westIndex() == startNodeIndex && secondNode.southIndex() == startNodeIndex) { return NodeType.NORTH_EAST } if (firstNode.northIndex() == startNodeIndex && secondNode.eastIndex() == startNodeIndex || firstNode.eastIndex() == startNodeIndex && secondNode.northIndex() == startNodeIndex) { return NodeType.SOUTH_WEST } if (firstNode.southIndex() == startNodeIndex && secondNode.eastIndex() == startNodeIndex || firstNode.eastIndex() == startNodeIndex && secondNode.southIndex() == startNodeIndex) { return NodeType.NORTH_WEST } throw IllegalArgumentException("Invalid combination of neighbours") } private fun findNode( graph: Graph, index: Pair<Int, Int> ) = findNode(graph, index.first, index.second) private fun findNode( graph: Graph, row: Int, col: Int ) = if (row in graph.rows.indices && col in graph.rows[row].indices) { graph.rows[row][col] } else { BorderNode(Pair(row, col)) } private fun isReachable( visitedNodes: MutableSet<Node>, currentNode: Node, neighbour: Node ) = (neighbour !in visitedNodes && currentNode.isConnectedTo(neighbour) && neighbour.isConnectedTo(currentNode)) companion object { private val log = KotlinLogging.logger {} } }
0
Kotlin
0
0
03a9f7a6c4e0bdf73f0c663ff54e01daf12a9762
6,651
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/Combinations.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 /** * 77. Combinations * @see <a href="https://leetcode.com/problems/combinations/">Source</a> */ fun interface Combinations { fun combine(n: Int, k: Int): List<List<Int>> } class CombinationsBacktracking : Combinations { override fun combine(n: Int, k: Int): List<List<Int>> { val combs: MutableList<List<Int>> = ArrayList() combine(combs, ArrayList(), 1, n, k) return combs } private fun combine(combs: MutableList<List<Int>>, comb: MutableList<Int>, start: Int, n: Int, k: Int) { if (k == 0) { combs.add(ArrayList(comb)) return } for (i in start..n) { comb.add(i) combine(combs, comb, i + 1, n, k - 1) comb.removeAt(comb.size - 1) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,423
kotlab
Apache License 2.0
src/Day06.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
fun main() { fun _process(input: List<String>, distinctCount: Int): Int { val l = input.first().toList() l.forEachIndexed { i, c -> val mem = l.subList(i, i + distinctCount) if (mem.distinct().size == distinctCount) { return(i + distinctCount) } } return -1 } fun part1(input: List<String>): Int { return _process(input, 4) } fun part2(input: List<String>): Int { return _process(input, 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") part1(input).println() part2(input).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
797
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/github/marcospereira/Day2.kt
marcospereira
50,556,652
false
null
package com.github.marcospereira /** * ## Day 2: I Was Told There Would Be No Math * * The elves are running low on wrapping paper, and so they need to submit an * order for more. They have a list of the dimensions (length `l`, width `w`, * and height `h`) of each present, and only want to order exactly as much as * they need. */ class Day2() : Day() { val boxes = file.readLines().map { line -> val (l, w, h) = line.split("x") Box(l.toInt(), w.toInt(), h.toInt()) } /** * ### Part One * * Fortunately, every present is a box (a perfect * [right rectangular prism](https://en.wikipedia.org/wiki/Cuboid#Rectangular_cuboid)), * which makes calculating the required wrapping paper for each gift a little * easier: find the surface area of the box, which is `2*l*w + 2*w*h + 2*h*l`. * The elves also need a little extra paper for each present: the area of the * smallest side. * * For example: * - A present with dimensions `2x3x4` requires `2*6 + 2*12 + 2*8 = 52` * square feet of wrapping paper plus `6` square feet of slack, for a * total of `58` square feet. * - A present with dimensions `1x1x10` requires `2*1 + 2*10 + 2*10 = 42` * square feet of wrapping paper plus `1` square foot of slack, for a * total of `43` square feet. * * All numbers in the elves' list are in feet. How many **total square feet** of * wrapping paper should they order? */ override fun part1() = boxes.sumBy { it.requiredWrappingPaper() } /** * ### Part Two * * The elves are also running low on ribbon. Ribbon is all the same width, * so they only have to worry about the length they need to order, which they * would again like to be exact. * * The ribbon required to wrap a present is the shortest distance around its * sides, or the smallest perimeter of any one face. Each present also * requires a bow made out of ribbon as well; the feet of ribbon required for * the perfect bow is equal to the cubic feet of volume of the present. Don't * ask how they tie the bow, though; they'll never tell. * * For example: * * - A present with dimensions `2x3x4` requires `2+2+3+3 = 10` feet of ribbon * to wrap the present plus `2*3*4 = 24` feet of ribbon for the bow, for a * total of `34` feet. * - A present with dimensions `1x1x10` requires `1+1+1+1 = 4` feet of ribbon * to wrap the present plus 1*1*10 = 10 feet of ribbon for the bow, for a * total of `14` feet. * * How many total **feet of ribbon** should they order? */ override fun part2() = boxes.sumBy { it.requiredFeetOfRibbon() } companion object { @JvmStatic fun main(args: Array<String>) { Day2().run() } } } class Box(val l: Int, val w: Int, val h: Int) { fun surface() = 2*l*w + 2*w*h + 2*h*l; fun areaOfSmallestSide() = smallestSides().reduce { a, b -> a * b } fun requiredWrappingPaper() = surface() + areaOfSmallestSide() fun ribbonToWrap() = smallestSides().sum() * 2 fun ribbonForTheBow() = l * w * h fun requiredFeetOfRibbon() = ribbonToWrap() + ribbonForTheBow() private fun smallestSides() = listOf(l, w, h).sorted().slice(0..1) }
0
Kotlin
3
2
4fed029837d87d81c833f2ad0273656b366d42ae
3,393
AdventOfCodeKotlin
MIT License
src/main/kotlin/com/ginsberg/advent2022/Day17.kt
tginsberg
568,158,721
false
{"Kotlin": 113322}
/* * Copyright (c) 2022 by <NAME> */ /** * Advent of Code 2022, Day 17 - Pyroclastic Flow * Problem Description: http://adventofcode.com/2022/day/17 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day17/ */ package com.ginsberg.advent2022 import kotlin.math.absoluteValue class Day17(input: String) { private val jets: List<Point2D> = parseJets(input) private val shapes: List<Set<Point2D>> = generateShapes() private val cave: MutableSet<Point2D> = (0..6).map { Point2D(it, 0) }.toMutableSet() private val down: Point2D = Point2D(0, 1) private val up: Point2D = Point2D(0, -1) private var jetCounter: Int = 0 private var blockCounter: Int = 0 fun solvePart1(): Int { repeat(2022) { simulate() } return cave.height() } fun solvePart2(): Long = calculateHeight(1000000000000L - 1) private fun simulate() { var thisShape = shapes.nth(blockCounter++).moveToStart(cave.minY()) do { val jettedShape = thisShape * jets.nth(jetCounter++) if (jettedShape in (0..6) && jettedShape.intersect(cave).isEmpty()) { thisShape = jettedShape } thisShape = thisShape * down } while (thisShape.intersect(cave).isEmpty()) cave += (thisShape * up) } private fun calculateHeight(targetBlockCount: Long): Long { data class State(val ceiling: List<Int>, val blockMod: Int, val jetMod: Int) val seen: MutableMap<State, Pair<Int, Int>> = mutableMapOf() while (true) { simulate() val state = State(cave.normalizedCaveCeiling(), blockCounter % shapes.size, jetCounter % jets.size) if (state in seen) { // Fast forward val (blockCountAtLoopStart, heightAtLoopStart) = seen.getValue(state) val blocksPerLoop: Long = blockCounter - 1L - blockCountAtLoopStart val totalLoops: Long = (targetBlockCount - blockCountAtLoopStart) / blocksPerLoop val remainingBlocksFromClosestLoopToGoal: Long = (targetBlockCount - blockCountAtLoopStart) - (totalLoops * blocksPerLoop) val heightGainedSinceLoop = cave.height() - heightAtLoopStart repeat(remainingBlocksFromClosestLoopToGoal.toInt()) { simulate() } return cave.height() + (heightGainedSinceLoop * (totalLoops - 1)) } seen[state] = blockCounter - 1 to cave.height() } } private operator fun IntRange.contains(set: Set<Point2D>): Boolean = set.all { it.x in this } private operator fun Set<Point2D>.times(point: Point2D): Set<Point2D> = map { it + point }.toSet() private fun Set<Point2D>.minY(): Int = minOf { it.y } private fun Set<Point2D>.height(): Int = minY().absoluteValue private fun Set<Point2D>.normalizedCaveCeiling(): List<Int> = groupBy { it.x } .entries .sortedBy { it.key } .map { pointList -> pointList.value.minBy { point -> point.y } } .let { val normalTo = this.minY() it.map { point -> normalTo - point.y } } private fun Set<Point2D>.moveToStart(ceilingHeight: Int): Set<Point2D> = map { it + Point2D(2, ceilingHeight - 4) }.toSet() private fun generateShapes(): List<Set<Point2D>> = listOf( setOf(Point2D(0, 0), Point2D(1, 0), Point2D(2, 0), Point2D(3, 0)), setOf(Point2D(1, 0), Point2D(0, -1), Point2D(1, -1), Point2D(2, -1), Point2D(1, -2)), setOf(Point2D(0, 0), Point2D(1, 0), Point2D(2, 0), Point2D(2, -1), Point2D(2, -2)), setOf(Point2D(0, 0), Point2D(0, -1), Point2D(0, -2), Point2D(0, -3)), setOf(Point2D(0, 0), Point2D(1, 0), Point2D(0, -1), Point2D(1, -1)) ) private fun parseJets(input: String): List<Point2D> = input.map { when (it) { '>' -> Point2D(1, 0) '<' -> Point2D(-1, 0) else -> throw IllegalStateException("No such jet direction $it") } } }
0
Kotlin
2
26
2cd87bdb95b431e2c358ffaac65b472ab756515e
4,225
advent-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RegularExpressionMatching.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode fun interface RegularExpressionMatch { operator fun invoke(text: String, pattern: String): Boolean } class RegularExpressionMatchRecursion : RegularExpressionMatch { override operator fun invoke(text: String, pattern: String): Boolean { if (pattern.isEmpty()) return text.isEmpty() val isFirstMatch = text.isNotEmpty() && (pattern[0] == text[0] || pattern[0] == '.') return if (pattern.length >= 2 && pattern[1] == '*') { invoke(text, pattern.substring(2)) || isFirstMatch && invoke(text.substring(1), pattern) } else { isFirstMatch && invoke(text.substring(1), pattern.substring(1)) } } } class RegularExpressionMatchDPTopDown : RegularExpressionMatch { enum class Result { TRUE, FALSE } private lateinit var memo: Array<Array<Result?>> override operator fun invoke(text: String, pattern: String): Boolean { memo = Array(text.length + 1) { arrayOfNulls<Result>(pattern.length + 1) } return dp(0, 0, text, pattern) } private fun dp(i: Int, j: Int, text: String, pattern: String): Boolean { if (memo[i][j] != null) { return memo[i][j] == Result.TRUE } val ans = if (j == pattern.length) { i == text.length } else { val isFirstMatch = i < text.length && pattern[j] == text[i] || pattern[j] == '.' if (j + 1 < pattern.length && pattern[j + 1] == '*') { dp(i, j + 2, text, pattern) || isFirstMatch && dp(i + 1, j, text, pattern) } else { isFirstMatch && dp(i + 1, j + 1, text, pattern) } } memo[i][j] = if (ans) Result.TRUE else Result.FALSE return ans } } class RegularExpressionMatchDPBottomUp : RegularExpressionMatch { override operator fun invoke(text: String, pattern: String): Boolean { val dp = Array(text.length + 1) { BooleanArray(pattern.length + 1) } dp[text.length][pattern.length] = true for (i in text.length downTo 0) { for (j in pattern.length - 1 downTo 0) { val isFirstMatch = i < text.length && (pattern[j] == text[i] || pattern[j] == '.') if (j + 1 < pattern.length && pattern[j + 1] == '*') { dp[i][j] = dp[i][j + 2] || isFirstMatch && dp[i + 1][j] } else { dp[i][j] = isFirstMatch && dp[i + 1][j + 1] } } } return dp[0][0] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,187
kotlab
Apache License 2.0
src/2022/Day13.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.lang.Math.min import java.util.* import kotlin.math.max fun main() { Day13().solve() } class Day13 { val input1 = """ [1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9] """.trimIndent() data class Term(val list: MutableList<Term> = mutableListOf(), var int: Int? = null) { constructor(s: String): this() { add(s, 0) } fun add(s: String, startIx: Int): Int { var ix = startIx while (s[ix] == ',') { ++ix } if (s[ix] == '[') { if (s[ix+1] == ']') { return ix+2 } while (s[ix] != ']') { list.add(Term()) ix = list.last().add(s, ix + 1) } return ix+1 } else { int = s.substring(ix).takeWhile { it.isDigit() }.toInt() while (s[ix].isDigit()) { ++ix } return ix } } fun isInt(): Boolean = int != null fun isList(): Boolean = !list.isEmpty() fun toList() { if (int == null) { return } list.add(Term(int = int)) int = null } } fun compare(t1: Term, t2: Term): Int { if (t1.isInt() && t2.isInt()) { if (t1.int!! < t2.int!!) { return 1 } if (t1.int!! > t2.int!!) { return -1 } return 0 } t1.toList() t2.toList() for (i in 0 until min(t1.list.size, t2.list.size)) { val c = compare(t1.list[i], t2.list[i]) if (c == 0) { continue } return c } if (t1.list.size < t2.list.size) { return 1 } if (t1.list.size > t2.list.size) { return -1 } return 0 } fun solve() { val f = File("src/2022/inputs/day13.in") val s = Scanner(f) // val s = Scanner(input1) var ix = 0 var sumIx = 0 val t01 = Term("[[2]]") val t02 = Term("[[6]]") val packets = mutableListOf(t01, t02) while (s.hasNextLine()) { val line = s.nextLine().trim() if (line.isEmpty()) { continue } ++ix val t1 = Term(line) val t2 = Term(s.nextLine().trim()) if (compare(t1, t2) > 0) { sumIx += ix } packets.add(t1) packets.add(t2) } val p1 = packets.sortedWith{ a, b -> compare(a, b) }.reversed() val ix1 = p1.indexOf(t01) val ix2 = p1.indexOf(t02) println("${sumIx} $ix1 $ix2 ${(ix1+1) * (ix2+1)}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
3,200
advent-of-code
Apache License 2.0
src/Day05.kt
ChristianNavolskyi
573,154,881
false
{"Kotlin": 29804}
class Day05 : Challenge<String> { override val name: String get() = "Day 05" override fun inputName(): String = "Day05" override fun testInputName(): String = "Day05_test" override fun testResult1(): String = "CMZ" override fun testResult2(): String = "MCD" override fun part1(input: String): String { val challengeSetup = input.split("\n\n") val stacks = challengeSetup.first().split("\n").parseStacks() challengeSetup[1] .split("\n") .filter { it.isNotBlank() } .map { it.moves() } .forEach { move -> stacks.applyMove9000(move) } return stacks.evaluateChallenge() } override fun part2(input: String): String { val challengeSetup = input.split("\n\n") val stacks = challengeSetup.first().split("\n").parseStacks() challengeSetup[1] .split("\n") .filter { it.isNotBlank() } .map { it.moves() } .forEach { move -> stacks.applyMove9001(move) } return stacks.evaluateChallenge() } private fun Map<Int, MutableList<Char>>.applyMove9001(move: Triple<Int, Int, Int>) { val (amount, from, to) = move this[to]?.addAll( this[from]?.takeLast(amount) ?: throw IndexOutOfBoundsException("Cannot move $amount crates from $from to $to of $this") ) repeat((1..amount).count()) { this[from]?.removeLastOrNull() } } private fun Map<Int, MutableList<Char>>.applyMove9000(move: Triple<Int, Int, Int>) { val (amount, from, to) = move this[to]?.addAll( this[from]?.takeLast(amount)?.reversed() ?: throw IndexOutOfBoundsException("Cannot move $amount crates from $from to $to of $this") ) repeat((1..amount).count()) { this[from]?.removeLastOrNull() } } private fun Map<Int, List<Char>>.evaluateChallenge(): String = toSortedMap().mapNotNull { it.value.lastOrNull { c -> c.isLetter() } }.joinToString("") private fun String.moves(): Triple<Int, Int, Int> { val parts = split(" ") return Triple(parts[1].toInt(), parts[3].toInt(), parts[5].toInt()) } private fun List<String>.parseStacks(): Map<Int, MutableList<Char>> { val numberOfStacks = last().split(regex = Regex("\\s")).last { it.isNotBlank() }.toInt() val result = (1..numberOfStacks).associateWith { mutableListOf<Char>() } reversed().drop(1).forEach { it.crates(numberOfStacks).forEachIndexed { index, c -> if (c.isLetter()) { result[index + 1]?.add(c) ?: throw IndexOutOfBoundsException("Failed to insert $c at index $index into $result") } } } return result } private fun String.crates(numberOfStacks: Int): List<Char> { return substring(1).mapIndexedNotNull { index, c -> if (index % 4 == 0) { c } else { null } } } }
0
Kotlin
0
0
222e25771039bdc5b447bf90583214bf26ced417
3,099
advent-of-code-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/BullsAndCows.kt
faniabdullah
382,893,751
false
null
//You are playing the Bulls and Cows game with your friend. // // You write down a secret number and ask your friend to guess what the number //is. When your friend makes a guess, you provide a hint with the following info: // // // The number of "bulls", which are digits in the guess that are in the correct //position. // The number of "cows", which are digits in the guess that are in your secret //number but are located in the wrong position. Specifically, the non-bull digits //in the guess that could be rearranged such that they become bulls. // // // Given the secret number secret and your friend's guess guess, return the //hint for your friend's guess. // // The hint should be formatted as "xAyB", where x is the number of bulls and y //is the number of cows. Note that both secret and guess may contain duplicate //digits. // // // Example 1: // // //Input: secret = "1807", guess = "7810" //Output: "1A3B" //Explanation: Bulls are connected with a '|' and cows are underlined: //"1807" // | //"7810" // // Example 2: // // //Input: secret = "1123", guess = "0111" //Output: "1A1B" //Explanation: Bulls are connected with a '|' and cows are underlined: //"1123" "1123" // | or | //"0111" "0111" //Note that only one of the two unmatched 1s is counted as a cow since the non- //bull digits can only be rearranged to allow one 1 to be a bull. // // // Example 3: // // //Input: secret = "1", guess = "0" //Output: "0A0B" // // // Example 4: // // //Input: secret = "1", guess = "1" //Output: "1A0B" // // // // Constraints: // // // 1 <= secret.length, guess.length <= 1000 // secret.length == guess.length // secret and guess consist of digits only. // // Related Topics Hash Table String Counting 👍 1136 👎 1178 package leetcodeProblem.leetcode.editor.en class BullsAndCows { 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 getHint(secret: String, guess: String): String { val map = IntArray(10) var bulls = 0 var cows = 0 for (i in secret.indices) { if (guess[i] == secret[i]) bulls++ else map[secret[i] - '0']++ } for (i in guess.indices) { if (guess[i] != secret[i] && map[guess[i] - '0'] > 0) { cows++ map[guess[i] - '0']-- } } return "${bulls}A${cows}B" } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,713
dsa-kotlin
MIT License
src/main/kotlin/pl/jpodeszwik/aoc2023/Day18.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 import java.lang.Integer.parseInt import java.util.* import kotlin.math.max import kotlin.math.min private fun part1(input: List<String>) { val digCoords = mutableSetOf<MapCoord>() var position = MapCoord(0, 0) var minRow = 0 var maxRow = 0 var minCol = 0 var maxCol = 0 digCoords.add(position) input.forEach { val parts = it.split(" ") val direction = when (parts[0]) { "L" -> Direction.LEFT "R" -> Direction.RIGHT "U" -> Direction.UP "D" -> Direction.DOWN else -> throw IllegalStateException() } val distance = parseInt(parts[1]) for (i in 0..<distance) { position = position.inDirection(direction, 1) digCoords.add(position) maxRow = max(maxRow, position.row) minRow = min(minRow, position.row) maxCol = max(maxCol, position.col) minCol = min(minCol, position.col) } } minRow-- maxRow++ minCol-- maxCol++ val outside = mutableSetOf<MapCoord>() val queue = LinkedList<MapCoord>() val startCoord = MapCoord(minRow, minCol) queue.add(startCoord) outside.add(startCoord) while (queue.isNotEmpty()) { val current = queue.pop() current.neighbours().filter { it.second.let { coord -> coord.row >= minRow && coord.row <= maxRow && coord.col >= minCol && coord.col <= maxCol } }.filter { !outside.contains(it.second) && !digCoords.contains(it.second) }.forEach { outside.add(it.second) queue.add(it.second) } } var count = 0 for (row in minRow..maxRow) { for (col in minCol..maxCol) { val coord = MapCoord(row, col) if(!outside.contains(coord) && !digCoords.contains(coord)) { count++ } } } println(digCoords.size + count) } fun main() { val input = loadFile("/aoc2023/input18") part1(input) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
2,099
advent-of-code
MIT License
src/Day01.kt
SekthDroid
573,039,827
false
{"Kotlin": 1566}
fun main() { fun parseCarriers(input: List<String>): List<List<Int>> { var current = mutableListOf<Int>() var carriers = emptyList<List<Int>>() for (each in input) { if (each.isBlank()) { carriers = carriers.plusElement(current) current = mutableListOf() } else { current.add(each.toInt()) } } return carriers } fun part1(input: List<String>): Int { return parseCarriers(input).maxOf { it.sum() } } fun part2(input: List<String>): Int { return parseCarriers(input).map { it.sum() }.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
830dd6b7c783759b4a7172e6f71b66e0554019b3
929
aoc-2022
Apache License 2.0
app/src/main/kotlin/play.kt
Henrique-Castro
376,186,163
false
null
package mastermind import models.Code import models.ColorsEnum import models.Pin val ALPHABET_PAIRS = ColorsEnum.values().map { it.initial to it.name } val ALPHABET = ColorsEnum.values().map { it.initial } const val CODE_LENGTH = 4 fun main() { playMastermind() } fun playMastermind( secret: Code = generateSecret() ) { var evaluation: Evaluation do { print("Your guess: ") val guess = readAndValidateInput(readLine()!!) val interpretedGuess = identifyInput(guess) evaluation = evaluateGuess(secret, interpretedGuess) if (evaluation.isComplete()) { println("The guess is correct!") } else { println("Right positions: ${evaluation.rightPosition}; " + "wrong positions: ${evaluation.wrongPosition}.") } } while (!evaluation.isComplete()) } fun Evaluation.isComplete(): Boolean = rightPosition == CODE_LENGTH fun hasErrorsInInput(guess: List<String>): Boolean { return guess.size != CODE_LENGTH || guess.any { it !in ALPHABET } } fun generateSecret(): Code { return Code(Pin.makeARandomList(CODE_LENGTH)) } fun readAndValidateInput(input: String) : List<String> { var guess = input.split("").verify() while (hasErrorsInInput(guess)) { println("Incorrect input: $guess. " + "It should consist of $CODE_LENGTH characters from $ALPHABET_PAIRS. ") println("Please try again.") guess = readLine()!!.split("").verify() } return guess } fun identifyInput(guess: List<String>) : Code { val pins = mutableListOf<Pin>() for (t in guess.verify()) { val colorName = ALPHABET_PAIRS.find { color -> t == color.first }!!.second val color = ColorsEnum.valueOf(colorName) pins.add(Pin(color, guess.indexOf(t))) } return Code(pins) } fun List<String>.verify (): List<String> { return this.filter { it != "" && it != " " } }
0
Kotlin
0
0
2bed4671a91e1beed5dddee3638d29799bfa7313
1,950
mastermind
MIT License
src/Day02.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
fun main() { val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return input.sumOf(String::toScore) } private fun part2(input: List<String>): Int { return input .map(String::correctMove) .sumOf(String::toScore) } private val SCORES = mapOf( "AX" to 4, "AY" to 8, "AZ" to 3, "BX" to 1, "BY" to 5, "BZ" to 9, "CX" to 7, "CY" to 2, "CZ" to 6, ) private fun String.toScore(): Int { return SCORES.getValue("${this[0]}${this[2]}") } private val CORRECTIONS = mapOf( "AX" to "A Z", "AY" to "A X", "AZ" to "A Y", "BX" to "B X", "BY" to "B Y", "BZ" to "B Z", "CX" to "C Y", "CY" to "C Z", "CZ" to "C X", ) private fun String.correctMove(): String { return CORRECTIONS.getValue("${this[0]}${this[2]}") }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
1,000
AOC2022
Apache License 2.0
src/Day02.kt
riegersan
572,637,157
false
{"Kotlin": 4377}
import kotlin.Exception fun main() { fun getPoints(e: Int, i: Int): Int { if(e == i){ //draw return i + 3 } if(e == 3){ if(i == 1){ return 7 } } if(e == 1){ if(i == 3){ return 3 } } if(e > i){ return i } if(e < i) { return i + 6 } throw Exception("Nope") } fun part1(input: List<String>): Int { return input.map { it.split(" ").map { when(it){ "A" -> 1 // rock "B" -> 2 // paper "C" -> 3 // scissors "X" -> 1 // rock "Y" -> 2 // paper "Z" -> 3 // scissors else -> 0// will not happen } } }.map { getPoints(it[0], it[1]) }.sum() } fun roundTwo(e: Int, i: Int): Int{ if(i == 1){ //lose val test = e - 1 if(test > 0){ return test }else return 3 } if(i == 2){ //draw return e + 3 } if(i == 3){ //win val test = e + 1 if(test < 4){ return test + 6 }else return 1 + 6 } throw Exception() } fun part2(input: List<String>): Int { return input.map { it.split(" ").map { when(it){ "A" -> 1 // rock "B" -> 2 // paper "C" -> 3 // scissors "X" -> 1 // rock "Y" -> 2 // paper "Z" -> 3 // scissors else -> 0// will not happen } } }.map { roundTwo(it[0], it[1]) }.sum() } // test if implementation meets criteria from the description, like: 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
d89439eb4d4d736d783c77cec873ac6e697e6ee9
2,215
advent-of-code-22-kotlin
Apache License 2.0
AOC-2017/src/main/kotlin/Day08.kt
sagar-viradiya
117,343,471
false
{"Kotlin": 72737}
import utils.dec import utils.inc import utils.splitAtNewLines import utils.splitAtWhiteSpace object Day08 { fun part1(input: String, trackHighestValue: Boolean = false) : Int { val valueMap = mutableMapOf<String, Int>() var highestValue: Int? = null input.splitAtNewLines().forEach { val splitInput = it.split(" if ") val operation = splitInput[0] val condition = splitInput[1] if (evaluateCondition(condition, valueMap)) { val operationSplit = operation.splitAtWhiteSpace() if (operationSplit[1] == "inc") { valueMap[operationSplit[0]] = (valueMap[operationSplit[0]] ?: 0) inc operationSplit[2].toInt() } else { valueMap[operationSplit[0]] = (valueMap[operationSplit[0]] ?: 0) dec operationSplit[2].toInt() } if (trackHighestValue && (highestValue == null || highestValue!! < valueMap[operationSplit[0]]!!)) { highestValue = valueMap[operationSplit[0]] } } } return if (trackHighestValue) { highestValue ?: throw IllegalStateException("Freak out!!!") } else { valueMap.values.max() ?: throw IllegalStateException("Freak out!!!") } } fun part2(input: String) = part1(input, true) private fun evaluateCondition(condition: String, valueMap: Map<String, Int>) : Boolean { val splitInput = condition.splitAtWhiteSpace() val variable = splitInput[0] val value = splitInput[2].toInt() return when(splitInput[1]) { ">" -> (valueMap[variable] ?: 0) > value "<" -> (valueMap[variable] ?: 0) < value "<=" -> (valueMap[variable] ?: 0) <= value ">=" -> (valueMap[variable] ?: 0) >= value "==" -> (valueMap[variable] ?: 0) == value else -> (valueMap[variable] ?: 0) != value } } }
0
Kotlin
0
0
7f88418f4eb5bb59a69333595dffa19bee270064
2,080
advent-of-code
MIT License
src/main/kotlin/leetcode/problem0123/BestTimeToBuyAndSellStock3.kt
ayukatawago
456,312,186
false
{"Kotlin": 266300, "Python": 1842}
package leetcode.problem0123 import java.lang.IllegalArgumentException import kotlin.math.max class BestTimeToBuyAndSellStock3 { fun maxProfit(prices: IntArray): Int { val dp: Map<Boolean, Array<IntArray>> = mapOf( true to Array(prices.size) { IntArray(MAX_PURCHASE_COUNT) { -1 } }, false to Array(prices.size) { IntArray(MAX_PURCHASE_COUNT) { -1 } } ) return solve(prices, 0, false, 0, dp) } private fun solve( prices: IntArray, index: Int, hasStock: Boolean, count: Int, dp: Map<Boolean, Array<IntArray>> ): Int { val map = dp[hasStock] ?: throw IllegalArgumentException() return when { index == prices.size || count == MAX_PURCHASE_COUNT -> 0 map[index][count] != -1 -> map[index][count] else -> { if (hasStock) { max( prices[index] + solve(prices, index + 1, false, count + 1, dp), solve(prices, index + 1, true, count, dp) ) } else { max( -prices[index] + solve(prices, index + 1, true, count, dp), solve(prices, index + 1, false, count, dp) ) } .also { map[index][count] = it } } } } companion object { private const val MAX_PURCHASE_COUNT = 2 } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
1,566
leetcode-kotlin
MIT License
yandex/y2023/qual/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2023.qual private fun solve(): String { val (n, m) = readInts() data class Edge(val from: Int, val to: Int, val weight: Int) val edges = List(m) { val tokens = readStrings() val a = tokens[0].toInt() - 1 val b = tokens[1].toInt() val greater = (tokens[2][0] == '>') val value = tokens[3].toInt() if (greater) Edge(a, b, -value) else Edge(b, a, value) } val p = LongArray(n + 1) for (iter in 0..n) { for (edge in edges) { if (p[edge.to] > p[edge.from] + edge.weight) { if (iter == n) return "NO" p[edge.to] = p[edge.from] + edge.weight } } } return "YES" } private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() } fun main() = repeat(1) { println(solve()) }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
763
competitions
The Unlicense
aoc_2023/src/main/kotlin/problems/day21/Garden.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day21 import problems.utils.Utils.Companion.transpose class Garden(lines: List<String>) { lateinit var startPos: Pair<Int, Int> var originalSize = Pair(lines.size, lines[0].length) var cells: List<List<GardenCell>> = lines.mapIndexed { i, line -> line.mapIndexed { j, char -> when (char) { '#' -> { GardenWallCell(i, j) } '.' -> { GardenPlotCell(i, j) } 'S' -> { startPos = Pair(i, j) GardenPlotCell(i, j) } else -> { throw Exception("Impossible") } } } } fun countPlotsAtStep(step: Long): Int { return countPlotsAtStep(cells, step) } companion object { fun countPlotsAtStep(cells: List<List<GardenCell>>, step: Long): Int { val reachableCells = cells.flatten().filter { cell -> if (cell !is GardenPlotCell) { return@filter false } cell.isInStep(step) } return reachableCells.size } fun firstStep(cells: List<List<GardenCell>>): Int { return cells.minOf { it.mapNotNull { cell -> if (cell !is GardenPlotCell) { null } else { cell.firstStep } }.min() } } } fun countBySections(times: Long): List<List<Int>> { val divididedInput = this.cells.map { line -> line.chunked(originalSize.second) }.transpose() .map { it.chunked(originalSize.first) } return divididedInput.map { rowComb -> rowComb.map { gridComb -> countPlotsAtStep(gridComb, times) } } } fun inputInSections(): List<List<List<List<GardenCell>>>> { return this.cells.map { line -> line.chunked(originalSize.second) }.transpose() .map { it.chunked(originalSize.first) } } fun extractAllSquares(originalMatrix: List<List<Any>>, size: Int): List<List<List<Any>>> { val submatrices = mutableListOf<List<List<Any>>>() for (rowStart in 0..originalMatrix.size - size) { for (colStart in 0..originalMatrix[0].size - size) { val submatrix = (0 until size).map { i -> originalMatrix[rowStart + i].subList(colStart, colStart + size) } submatrices.add(submatrix) } } return submatrices } fun search() { val startNode = GardenNode(0, this.cells[startPos.first][startPos.second]) val openedCells = mutableListOf(startNode) while (openedCells.isNotEmpty()) { val nextNode = openedCells.removeAt(0) val nextCell = nextNode.cell if (!nextCell.canWalk()) continue val plotCell = nextCell as GardenPlotCell if (plotCell.firstStep != null) continue plotCell.firstStep = nextNode.step val neighbours = findNeighbours(nextNode) for (neighbour in neighbours) { openedCells.add(neighbour) } } } fun findNeighbours(node: GardenNode): List<GardenNode> { val cell = node.cell val neighbours = GardenDirection.allCartesianDirs().map { dir -> val nextPos = dir.nextPos(cell.i, cell.j, this.cells) if (nextPos != null) { val nextCell = this.cells[nextPos.first][nextPos.second] return@map GardenNode(node.step + 1, nextCell) } else { return@map null } } return neighbours.filterNotNull() } fun repeat(times: Int) { val actualTimes = (times * 2 + 1) val width = this.cells.size val height = this.cells[0].size val repeatedWidth = this.cells.map { lineCell -> List(actualTimes) { lineCell.map { it.copy() } }.flatten() } val repeatedHeight = List(actualTimes) { repeatedWidth.map { line -> line.map { it.copy() } } }.flatten() startPos = Pair(startPos.first + width * times, startPos.second + height * times) for (i in repeatedHeight.indices) { for (j in repeatedHeight[0].indices) { repeatedHeight[i][j].i = i repeatedHeight[i][j].j = j } } this.cells = repeatedHeight } fun getPrintLines(step: Long): String { return this.cells.joinToString("\n") { lineCell -> lineCell.map { it.characterMap(step) }.joinToString("") } } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
4,778
advent-of-code-2023
MIT License