path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/Day6.kt
clechasseur
264,758,910
false
null
object Day6 { private val input = """ 2 8 8 5 4 2 3 1 5 5 1 2 15 13 5 14 """.trimIndent().split('\t').map { it.toInt() } fun part1() = detectLoop().size - 1 fun part2(): Int { val loop = detectLoop() val start = loop.indexOf(loop.last()) return loop.indices.last - start } private fun detectLoop(): List<List<Int>> { val bankStates = mutableListOf<List<Int>>() var banks = input var rounds = 0 while (!bankStates.contains(banks)) { bankStates.add(banks) banks = redistribute(banks) rounds++ } bankStates.add(banks) return bankStates } private fun redistribute(banks: List<Int>): List<Int> { val newBanks = banks.toMutableList() val chosen = newBanks.indexOf(newBanks.max()!!) val blocks = newBanks[chosen] newBanks[chosen] = 0 (1..blocks).forEach { bankIdx -> newBanks[(chosen + bankIdx) % newBanks.size]++ } return newBanks } }
0
Kotlin
0
0
f3e8840700e4c71e59d34fb22850f152f4e6e739
1,061
adventofcode2017
MIT License
src/Day04.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
fun main() { fun parseRange(str: String) = str.split("-").let { it[0].toLong()..it[1].toLong() } fun parse(input: List<String>) = input.map { it.split(',').map(::parseRange) } fun LongRange.contains(range: LongRange) = this.first <= range.first && this.last >= range.last fun LongRange.intersects(range: LongRange) = range.contains(this.first) || this.contains(range.first) fun part1(input: List<String>) = parse(input) .filter { it[0].contains(it[1]) || it[1].contains(it[0]) } .size fun part2(input: List<String>) = parse(input).filter { it[0].intersects(it[1]) }.size val input = readInput("day4") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
703
advent-of-code-2022
Apache License 2.0
2019/src/test/kotlin/Day03.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.IllegalArgumentException import kotlin.math.absoluteValue import kotlin.test.Test import kotlin.test.assertEquals class Day03 { enum class Direction { R, L, U, D } data class Location(val x: Int, val y: Int) { fun toManhattenDistance() = x.absoluteValue + y.absoluteValue } data class Path(val direction: Direction, val length: Int) @Test fun runPart01() { val wires = Util.getInputAsListOfString("day03-input.txt") val locations = trace(wires) val distance = (locations.first() intersect locations.last().toSet()) .filter { it != Location(0, 0) } .minOf { it.toManhattenDistance() } assertEquals(245, distance) } @Test fun runPart02() { val wires = Util.getInputAsListOfString("day03-input.txt") val locations = trace(wires) val distance = (locations.first() intersect locations.last().toSet()) .filter { it != Location(0, 0) } .minOf { locations.first().indexOf(it) + locations.last().indexOf(it) } assertEquals(48262, distance) } private fun trace(wires: List<String>) = wires .map { wire -> wire .split(",") .map { it.toPath() } .fold(listOf(Location(0, 0))) { locations, path -> locations + traverse(locations.last(), path) } } private fun traverse(start: Location, path: Path) = when (path.direction) { Direction.R -> (1..path.length).map { Location(start.x + it, start.y) } Direction.L -> (1..path.length).map { Location(start.x - it, start.y) } Direction.U -> (1..path.length).map { Location(start.x, start.y + it) } Direction.D -> (1..path.length).map { Location(start.x, start.y - it) } } private fun String.toPath() = Path( when (get(0)) { 'R' -> Direction.R 'L' -> Direction.L 'U' -> Direction.U 'D' -> Direction.D else -> throw IllegalArgumentException() }, substring(1).toInt() ) }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,119
adventofcode
MIT License
src/main/kotlin/com/mantono/tsa/Trends.kt
mantono
105,402,624
false
null
package com.mantono.tsa import java.time.Duration import java.time.Instant data class Trend(val first: Collection<Number>, val second: Collection<Number>) { fun bySum(): Double = second.sum() / first.sum() fun byAverage(): Double = second.average() / first.average() fun byMedian(): Double = second.median() / first.median() } fun <T: Number> trend(data: Collection<DataPoint<T>>, length: Duration, stop: Instant = Instant.now()): Trend { return trend(data, stop.minus(length), stop) } fun <T: Number> trend(data: Collection<DataPoint<T>>, start: Instant, stop: Instant = Instant.now()): Trend { return trendByTime(data, start, stop) } fun <T: Number> trend(data: Collection<DataPoint<T>>, limit: Int = data.size): Trend { return trendBySize(data, limit) } fun <T: Number> trendByTime(data: Collection<DataPoint<T>>, start: Instant, stop: Instant = Instant.now()): Trend { if(start.isAfter(stop)) throw IllegalArgumentException("Start time cannot be after end time") if(data.size < 2) throw IllegalArgumentException("Collection of data points does not contain enough values. 2 is required, got ${data.size}") val length = Duration.between(start, stop) val divider: Instant = start.plus(length.dividedBy(2L)) val divided: Pair<List<DataPoint<T>>, List<DataPoint<T>>> = data.asSequence() .filter { it.timestamp.isAfter(start) } .filter { it.timestamp.isBefore(stop) } .partition { it.timestamp.isBefore(divider) } val before: List<T> = divided.first.map { it.value } val after: List<T> = divided.second.map { it.value } if(before.isEmpty() || after.isEmpty()) { val timeOfFirstValue: Instant = data.asSequence() .map { it.timestamp } .sorted() .first() .minusMillis(1) val timeOfLastValue: Instant = data.asSequence() .map { it.timestamp } .sorted() .last() .plusMillis(1) return trendByTime(data, timeOfFirstValue, timeOfLastValue) } return Trend(before, after) } fun <T: Number> trendBySize(data: Collection<DataPoint<T>>, limit: Int = data.size): Trend { val breakpoint: Int = computeTakeFromLimit(data.size, limit) val first: List<T> = data.sortedSubList(0 until breakpoint).map { it.value } val second: List<T> = data.sortedSubList(breakpoint..breakpoint*2).map { it.value } return Trend(first, second) } /** * This function computes how many elements that should be included in each sub list from * originating [Collection]. This makes sure that * - No values less than two are used as limit (since at least two values are needed for a trend) * - Limits of odd size is corrected to an even size (so each sub list has an equal amount of elements) * - The given amount is not larger than the entire collection */ fun computeTakeFromLimit(size: Int, limit: Int): Int { if(limit <= 1) throw IllegalArgumentException("Argument limit must be a greater than one but was $limit") val lowerBound: Int = minOf(size, limit) val include: Int = lowerBound - (lowerBound % 2) return include/2 }
0
Kotlin
0
0
978a8a82dd02b20028f5012060caa7ca2fe22b8e
3,060
time-series-analysis
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day03.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.PuzzleSet import kotlin.math.pow fun PuzzleSet.day3() = puzzle(day = 3) { // Part one val lines = inputLines val width = lines.first().length val numbers = lines.map { it.toInt(2) } val gamma = (0 until width) .reduceIndexed { idx, acc, v -> acc or (getMostCommon(width, v, numbers) shl width - idx - 1) } val epsilon = gamma.inv() and 2.0.pow(width).toInt() - 1 partOne = (gamma * epsilon).s() // Part two val findRating = { doNegate: Boolean -> var result = numbers for (i in 0 until width) { val toCheck = getMostCommon(width, i, result) result = result.filter { it.getBit(width - i - 1) == if (doNegate) toCheck.inv() and 1 else toCheck } if (result.size == 1) break } result.first() } val oxygenRating = findRating(false) val co2ScrubRating = findRating(true) partTwo = (oxygenRating * co2ScrubRating).s() } fun Int.getBit(index: Int) = this shr index and 1 fun getMostCommon(width: Int, idx: Int, values: List<Int>): Int { val sum = values.sumOf { b -> (if (b.getBit(width - idx - 1) == 1) 1 else -1).toInt() } return if (sum >= 0) 1 else 0 }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,261
advent-of-code
The Unlicense
src/day10/day10.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day10 import inputTextOfDay import testTextOfDay fun part1(input: String): Int { val instructions = input.lines() var cycle = 1 var x = 1 var strength = 0 instructions.forEach { when { it.startsWith("addx") -> { strength += measureStrength(cycle, x) // during cycle++ strength += measureStrength(cycle, x) // during cycle++ x += it.substringAfter("addx ").toInt() // after } else -> { strength += measureStrength(cycle, x) // during cycle++ } } } return strength } private fun measureStrength(cycle: Int, x: Int): Int = when { cycle == 20 -> cycle * x (cycle - 20) % 40 == 0 -> cycle * x else -> 0 } fun part2(input: String) { val instructions = input.lines() var cycle = 1 var x = 1 val screen = MutableList(40 * 6) { "." } var crt = 0 instructions.forEach { when { it.startsWith("addx") -> { draw(crt, x, screen, cycle) // during cycle++ crt = move(crt) draw(crt, x, screen, cycle) // during cycle++ x += it.substringAfter("addx ").toInt() // after crt = move(crt) // after } else -> { draw(crt, x, screen, cycle) // during cycle++ crt = move(crt) // after } } } printScreen(screen) } private fun move(crt: Int) = (crt + 1) % 40 private fun draw(crt: Int, x: Int, screen: MutableList<String>, cycle: Int ) { if (crt in x - 1..x + 1) screen[cycle-1] = "#" } fun printScreen(screen: List<String>, size: Int = 40) { for (line in screen.chunked(size)) { println(line.joinToString("")) } } fun main() { val test = testTextOfDay(day) val input = inputTextOfDay(day) check(part1(test) == 13140) println("Test ${part1(test)}") part2(test) check(part1(input) == 15120) println("Input ${part1(input)}") part2(input) } const val day = 10
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
2,185
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day25/WiringDiagram.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day25 import org.jgrapht.Graph import org.jgrapht.alg.StoerWagnerMinimumCut import org.jgrapht.graph.DefaultWeightedEdge import org.jgrapht.graph.SimpleWeightedGraph fun Sequence<String>.toWiringDiagram(): WiringDiagram { return WiringDiagram(map(String::toConnection).toList()) } data class WiringDiagram( val connections: List<Connection>, ) { private val vertices = connections.map(Connection::name) + connections.flatMap(Connection::connections) private val edges = connections.flatMap { (from, connections) -> connections.map { to -> Pair(from, to) } } fun disconnectedGroups(): Pair<Set<String>, Set<String>> { val graph = toGraph() val minCut = StoerWagnerMinimumCut(graph).minCut() val vertices = graph.vertexSet() graph.removeAllVertices(minCut) return vertices to minCut } private fun toGraph() = graph { vertices.forEach(::addVertex) edges.forEach(::addEdge) } } private fun <V, E> Graph<V, E>.addEdge(vertices: Pair<V, V>): E { return addEdge(vertices.first, vertices.second) } private inline fun <V> graph(builder: Graph<V, DefaultWeightedEdge>.() -> Unit): Graph<V, DefaultWeightedEdge> { return SimpleWeightedGraph<V, DefaultWeightedEdge>(null, ::DefaultWeightedEdge).apply(builder) }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
1,361
advent-2023
ISC License
src/main/kotlin/Day14.kt
clechasseur
267,632,210
false
null
import org.clechasseur.adventofcode2016.md5 object Day14 { private const val input = "ahsbgdzn" private val tripleRegex = """(.)\1\1""".toRegex() fun part1(): Int = keySequence(false).drop(63).first().second fun part2(): Int = keySequence(true).drop(63).first().second private fun hashSequence(stretch: Boolean): Sequence<String> = generateSequence(0) { it + 1 }.map { i -> generateSequence("$input$i") { md5(it) }.drop(if (stretch) 2017 else 1).first() } private fun keySequence(stretch: Boolean): Sequence<Pair<String, Int>> = KeyDetector(stretch).keySequence() private class KeyDetector(stretch: Boolean) { private val hashIt = hashSequence(stretch).iterator() private val hashes = mutableListOf<String>() private var i = 0 fun keySequence(): Sequence<Pair<String, Int>> = sequence { while (true) { while (i + 1000 >= hashes.size) { fill() } val candidateKey = hashes[i] val tripleMatch = tripleRegex.find(candidateKey) if (tripleMatch != null) { val quintupleRegex = tripleMatch.groupValues[1].repeat(5).toRegex() if (next1000().any { quintupleRegex.containsMatchIn(it) }) { yield(candidateKey to i) } } i++ } } private fun fill() { (0 until 2000).forEach { _ -> hashes.add(hashIt.next()) } } private fun next1000(): Sequence<String> = generateSequence(i + 1) { it + 1 }.take(1000).map { hashes[it] } } }
0
Kotlin
0
0
120795d90c47e80bfa2346bd6ab19ab6b7054167
1,699
adventofcode2016
MIT License
src/Day01.kt
vladislav-og
573,326,483
false
{"Kotlin": 27072}
fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var caloriesCounter = 0 for (row in input) { if (row == "") { if (maxCalories < caloriesCounter) { maxCalories = caloriesCounter } caloriesCounter = 0 continue } caloriesCounter += row.toInt() } return maxCalories } fun part2(input: List<String>): Int { val topThreeValues = arrayListOf(0, 0, 0) var caloriesCounter = 0 for (row in input) { if (row == "") { if (caloriesCounter > topThreeValues[0]) { topThreeValues[0] = caloriesCounter topThreeValues.sort() } caloriesCounter = 0 continue } caloriesCounter += row.toInt() } return topThreeValues.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) println(part1(testInput)) println(part2(testInput)) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b230ebcb5705786af4c7867ef5f09ab2262297b6
1,325
advent-of-code-2022
Apache License 2.0
src/main/kotlin/d8/d8.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d8 import readInput fun part1(input: List<String>): Int { val trees = mutableListOf<List<Int>>() for (line in input) { if (line.isNotBlank()) trees.add(line.toList().map { v-> v-'0' }) } var nbVis = 0 val lines = trees.size for ((idxL, line) in trees.withIndex()) { if (idxL in 1 until lines-1) { val cols = line.size for ((idxC, col) in line.withIndex()) { if (idxC !in 1 until cols-1) nbVis++ else { var visible = true val height = trees[idxL][idxC] var c = idxC - 1 while (visible && c >= 0) { visible = trees[idxL][c] < height --c } if (! visible) { visible = true c = idxC + 1 while (visible && c < cols) { visible = trees[idxL][c] < height ++c } } if (! visible) { visible = true var l = idxL - 1 while (visible && l >= 0) { visible = trees[l][idxC] < height --l } } if (! visible) { visible = true var l = idxL + 1 while (visible && l < lines) { visible = trees[l][idxC] < height ++l } } if (visible) nbVis++ } } } else { // whole line visible nbVis += line.size } } return nbVis } fun part2(input: List<String>): Int { val trees = mutableListOf<List<Int>>() for (line in input) { if (line.isNotBlank()) trees.add(line.toList().map { v-> v-'0' }) } var maxScore = 0 val lines = trees.size for ((idxL, line) in trees.withIndex()) { if (idxL in 1 until lines-1) { val cols = line.size for ((idxC, col) in line.withIndex()) { if (idxC in 1 until cols-1) { var score = 1 var visible = 0 val height = trees[idxL][idxC] var c = idxC - 1 while (c >= 0 && trees[idxL][c] < height) { --c ++visible } if (c>0) ++visible if (visible>0) score *= visible visible = 0 c = idxC + 1 while (c < cols && trees[idxL][c] < height) { ++c ++visible } if (c<cols) ++visible if (visible>0) score *= visible visible = 0 var l = idxL - 1 while (l >= 0 && trees[l][idxC] < height) { --l ++visible } if (l>0) ++visible if (visible>0) score *= visible visible = 0 l = idxL + 1 while (l < lines && trees[l][idxC] < height) { ++l ++visible } if (l<lines) ++visible if (visible>0) score *= visible if (score > maxScore) maxScore = score } } } } return maxScore } fun main() { //val input = readInput("d8/test") val input = readInput("d8/input1") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
4,254
aoc2022
Creative Commons Zero v1.0 Universal
src/main/aoc2022/Day15.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 import Pos import intersect import size import unionALl import kotlin.math.abs class Day15(input: List<String>) { data class Sensor(val pos: Pos, val beacon: Pos) { /** * Gives the range of x coordinates that is visible on the given y coordinate for this sensor. Returns * null if there are no x coordinates in range. */ fun xRangeAt(y: Int): IntRange? { val xRange = pos.distanceTo(beacon) - abs(pos.y - y) if (xRange <= 0) { return null } return pos.x - xRange..pos.x + xRange } } private val sensors: Set<Sensor> private val beacons: Set<Pos> init { val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() val s = mutableSetOf<Sensor>() val b = mutableSetOf<Pos>() input.forEach { line -> val (sx, sy, bx, by) = regex.find(line)!!.destructured val beacon = Pos(bx.toInt(), by.toInt()) s.add(Sensor(Pos(sx.toInt(), sy.toInt()), beacon)) b.add(beacon) } sensors = s beacons = b } fun solvePart1(row: Int): Int { val sensorCoverage = sensors .mapNotNull { it.xRangeAt(row) } // the ranges for all beacons .unionALl() // reduce to the minimal set of ranges // The distress beacon can not be where a detected beacon, or sensor is located, so subtract those return sensorCoverage.sumOf { it.size() } - beacons.count { it.y == row } - sensors.count { it.pos.y == row } } fun solvePart2(searchSpace: Int): Long { var beacon = Pos(-1, -1) val targetRange = 0..searchSpace for (y in searchSpace downTo 0) { // the correct location is close to the end, so search backwards val coverage = sensors .mapNotNull { it.xRangeAt(y) } // the ranges for all beacons .unionALl() // reduce to the minimal set of ranges .mapNotNull { it.intersect(targetRange) } // clamp the ranges to the area of interest if (coverage.size > 1) { // More than one range on the same row means that there is a hole and that's where the distress // beacon is located at beacon = Pos(coverage.first().last + 1, y) break } } return beacon.x * 4000000L + beacon.y } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,492
aoc
MIT License
src/main/kotlin/day24.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day24 : Solvable("24") { override fun solveA(input: List<String>): String { return solve(getInstructions(input), true) } override fun solveB(input: List<String>): String { return solve(getInstructions(input), false) } private fun getInstructions(input: List<String>): List<Pair<List<Instruction>, Int>> { return input .map { Instruction.get(it.split(" ")) } .chunked(18) .map { it to (it.filter { it is Div && it.from.get() == 26L }.size == 1) } .map { if (it.second) { it.first to (it.first[5] as Add).from.get().toInt() } else { it.first to Int.MAX_VALUE } } } private fun solve(instrs: List<Pair<List<Instruction>, Int>>, max: Boolean): String { var count = if (max) 9999999 else 1111111 var countStr: String = "" var nums: MutableList<Int> = mutableListOf() outer@ while (count >= 1111111 && count <= 9999999) { resetRegisters() countStr = count.toString() if (countStr.contains("0")) { count += if (max) -1 else 1 continue } var i = 0 nums = mutableListOf<Int>() for (instr in instrs) { if (instr.second != Int.MAX_VALUE) { val n = registers.get("z")!!.get().toInt() % 26 + instr.second if (n <= 0 || n > 9) break run(instr.first, mutableListOf(n)) nums.add(n) } else { run(instr.first, mutableListOf(countStr[i++].toInt() - 48)) } } if (nums.size == 7 && registers.get("z")!!.get() == 0L) break count += if (max) -1 else 1 } var cCount = 0 var nCount = 0 return instrs .map { if (it.second == Int.MAX_VALUE) { countStr[cCount++].toInt() - 48 } else { nums[nCount++] } } .map(Int::toString) .joinToString("") } } fun run(instructions: List<Instruction>, input: MutableList<Int>) { instructions.forEach { it.execute(input) } } val registers = listOf("w", "x", "y", "z").associateWith { Register() }.toMutableMap() fun resetRegisters() { registers.values.forEach { it.set(0) } } open class Register(v: Long = 0) { var value = v fun get(): Long { return value } fun set(reg: Register) { value = reg.get() } fun set(i: Long) { value = i } companion object { fun get(str: String): Register { registers[str]?.let { return it } return Register(str.toLong()) } } } abstract class Instruction() { abstract fun execute(input: MutableList<Int>) companion object { fun get(inp: List<String>): Instruction { return when (inp.first()) { "inp" -> Inp(Register.get(inp[1])) "add" -> Add(Register.get(inp[1]), Register.get(inp[2])) "mul" -> Mul(Register.get(inp[1]), Register.get(inp[2])) "div" -> Div(Register.get(inp[1]), Register.get(inp[2])) "mod" -> Mod(Register.get(inp[1]), Register.get(inp[2])) "eql" -> Eql(Register.get(inp[1]), Register.get(inp[2])) else -> throw Exception("invalid instruction ${inp.first()}") } } } } class Inp(val to: Register) : Instruction() { override fun execute(input: MutableList<Int>) { to.set(input.removeAt(input.size - 1).toLong()) } } class Add(val to: Register, val from: Register) : Instruction() { override fun execute(input: MutableList<Int>) { to.set(to.get() + from.get()) } } class Mul(val to: Register, val from: Register) : Instruction() { override fun execute(input: MutableList<Int>) { to.set(to.get() * from.get()) } } class Div(val to: Register, val from: Register) : Instruction() { override fun execute(input: MutableList<Int>) { to.set(to.get() / from.get()) } } class Mod(val to: Register, val from: Register) : Instruction() { override fun execute(input: MutableList<Int>) { to.set(to.get() % from.get()) } } class Eql(val to: Register, val from: Register) : Instruction() { override fun execute(input: MutableList<Int>) { to.set(if (to.get() == from.get()) 1L else 0L) } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
4,726
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/day13.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
val originalReflection = mutableMapOf<Int, Mirror>() fun day13 (lines: List<String>) { val patterns = parsePatterns(lines) var sum = 0L patterns.forEachIndexed { index, it -> var newSum = findHorizontalReflectionSum(it, 100, true, index) if (newSum == 0) { newSum = findVerticalReflectionSum(it, true, index) } sum += newSum } println("Day 13 part 1: $sum") var smudgeSum = 0L var hits = 0 patterns.forEachIndexed { index, pattern -> var horizontalSum: Int var verticalSum: Int for (row in pattern.pattern.indices) { for (col in pattern.pattern[row].indices) { horizontalSum = findHorizontalReflectionSum(replaceSmudge(pattern, row, col), 100, false, index) verticalSum = findVerticalReflectionSum(replaceSmudge(pattern, row, col), false, index) if (horizontalSum != 0) { smudgeSum += horizontalSum hits++ return@forEachIndexed } if (verticalSum != 0) { smudgeSum += verticalSum hits++ return@forEachIndexed } } } } println("Day 13 part 2: $smudgeSum") println() } fun replaceSmudge(pattern: Pattern, row: Int, col: Int): Pattern { val replaced = Pattern(mutableListOf()) for (y in pattern.pattern.indices) { var line = "" for (x in pattern.pattern[y].indices) { line += if (y == row && x == col) { if (pattern.pattern[y][x] == '.') { '#' } else { '.' } } else { pattern.pattern[y][x] } } replaced.pattern.add(line) } return replaced } fun findHorizontalReflectionSum(pattern: Pattern, multiplier: Int, part1: Boolean, index: Int): Int { for (i in pattern.pattern.indices) { if (i == pattern.pattern.size - 1) { continue } if (!part1 && multiplier == 1 && originalReflection[index]!!.originalVerticalLine != null && originalReflection[index]!!.originalVerticalLine == i) { continue } if (!part1 && multiplier == 100 && originalReflection[index]!!.originalHorizontalLine != null && originalReflection[index]!!.originalHorizontalLine == i) { continue } if (pattern.pattern[i] == pattern.pattern[i + 1]) { var matching = true var indexOffset = 1 try { while (matching) { matching = pattern.pattern[i - indexOffset + 1] == pattern.pattern[i + indexOffset] indexOffset++ } } catch (e: IndexOutOfBoundsException) { if (part1) { if (multiplier == 1) { originalReflection[index] = Mirror(null, i) } else { originalReflection[index] = Mirror(i, null) } } return (i + 1) * multiplier } } } return 0 } fun rotatePattern(pattern: Pattern): Pattern { val rotated = Pattern(mutableListOf()) pattern.pattern[0].forEach { _ -> rotated.pattern.add("") } pattern.pattern.reversed().forEach { row -> row.forEachIndexed { index, c -> rotated.pattern[index] = rotated.pattern[index] + c } } return rotated } fun findVerticalReflectionSum(pattern: Pattern, part1: Boolean, index: Int): Int { return findHorizontalReflectionSum(rotatePattern(pattern), 1, part1, index) } fun parsePatterns(lines: List<String>): List<Pattern> { val patterns = mutableListOf<Pattern>() var pattern = Pattern(mutableListOf()) lines.forEach { if (it.isEmpty()) { patterns.add(pattern) pattern = Pattern(mutableListOf()) } else { pattern.pattern.add(it) } } patterns.add(pattern) return patterns } data class Pattern(val pattern: MutableList<String>) data class Mirror(val originalHorizontalLine: Int?, val originalVerticalLine: Int?)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
4,363
advent_of_code_2023
MIT License
jvm_sandbox/projects/advent_of_code/src/main/kotlin/year2018/Day2.kt
jduan
166,515,850
false
{"Rust": 876461, "Kotlin": 257167, "Java": 139101, "Python": 114308, "Vim Script": 100117, "Shell": 96665, "C": 67784, "Starlark": 23497, "JavaScript": 20939, "HTML": 12920, "Ruby": 5087, "Thrift": 4518, "Nix": 2919, "HCL": 1069, "Lua": 926, "CSS": 826, "Assembly": 761, "Makefile": 591, "Haskell": 585, "Dockerfile": 501, "Scala": 322, "Smalltalk": 270, "CMake": 252, "Smarty": 97, "Clojure": 91}
package year2018.day2 import java.io.File import java.lang.Exception import java.util.* fun checksum(path: String): Int { var totalTwos = 0 var totalThrees = 0 File(path).forEachLine { val (twos, threes) = countID2(it) totalTwos += twos totalThrees += threes } return (totalTwos * totalThrees) } // Another way of counting twos and threes. fun countID2(id: String): Pair<Int, Int> { val counts = mutableMapOf<Char, Int>() id.forEach { if (counts.contains(it)) { counts[it] = counts[it]!! + 1 } else { counts[it] = 1 } } val twos = if (counts.containsValue(2)) 1 else 0 val threes = if (counts.containsValue(3)) 1 else 0 return Pair(twos, threes) } /** * Given a string ID, check if it contains exactly 2 of any letter and * separately check if it contains exactly 3 of any letter. * Return a pair of both. Note that if there are multiple letters that * appear exactly twice, it only counts once. */ fun countID(id: String): Pair<Int, Int> { val sortedId = sortString(id) var twos = 0 var threes = 0 var previous: Char? = null var i = 0 var repeats = 0 while (i < sortedId.length) { val current = sortedId[i] i++ if (previous == null) { previous = current repeats = 1 continue } if (previous == current) { repeats++ } else { if (repeats >= 3) { threes = 1 } else if (repeats == 2) { twos = 1 } previous = current repeats = 1 } } // Don't forget about the last batch! if (repeats >= 3) { threes = 1 } else if (repeats == 2) { twos = 1 } return Pair(twos, threes) } fun findCommonLetters(path: String): String { val lines = File(path).readLines() for (i in 0 until lines.size) { for (j in i until lines.size) { if (distance(lines[i], lines[j]) == 1) { return common(lines[i], lines[j]) } } } throw Exception("Not found!") } internal fun sortString(s: String): String { val chars = s.toCharArray() Arrays.sort(chars) return String(chars) } // Return the distance of 2 strings of the same length. fun distance(s1: String, s2: String): Int { var diff = 0 for (i in 0 until s1.length) { diff += if (s1[i] == s2[i]) 0 else 1 } return diff } // Return the common letters between 2 strings of the same length. fun common(s1: String, s2: String): String { val letters = mutableListOf<Char>() for (i in 0 until s1.length) { if (s1[i] == s2[i]) { letters.add(s1[i]) } } return letters.joinToString(separator = "") }
58
Rust
1
0
d5143e89ce25d761eac67e9c357620231cab303e
2,584
cosmos
MIT License
kotlin/src/main/kotlin/dev/akkinoc/atcoder/workspace/kotlin/algo/ListAlgo.kt
akkinoc
520,873,415
false
{"Kotlin": 24773}
package dev.akkinoc.atcoder.workspace.kotlin.algo /** * The algorithms for [List]. */ object ListAlgo { /** * Generate a sequence of permutations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of permutations. */ fun <T> List<T>.perm(r: Int): Sequence<List<T>> { val i = IntArray(size) { it } val c = IntArray(r) { size - it } return generateSequence(List(r) { get(i[it]) }) s@{ _ -> val p = (r - 1 downTo 0).find f@{ p -> if (--c[p] > 0) return@f true i[size - 1] = i[p].also { i.copyInto(i, p, p + 1) } c[p] = size - p false } ?: return@s null i[size - c[p]] = i[p].also { i[p] = i[size - c[p]] } List(r) { get(i[it]) } } } /** * Generate a sequence of repeated permutations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of repeated permutations. */ fun <T> List<T>.rperm(r: Int): Sequence<List<T>> { val i = IntArray(r) return generateSequence(i.map(::get)) s@{ _ -> val p = (r - 1 downTo 0).find { i[it] < size - 1 } ?: return@s null ++i[p] i.fill(0, p + 1) i.map(::get) } } /** * Generate a sequence of combinations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of combinations. */ fun <T> List<T>.comb(r: Int): Sequence<List<T>> { val i = IntArray(r) { it } return generateSequence(i.map(::get)) s@{ _ -> var p = (r - 1 downTo 0).find { i[it] < size - r + it } ?: return@s null var n = i[p] while (p < r) i[p++] = ++n i.map(::get) } } /** * Generate a sequence of repeated combinations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of repeated combinations. */ fun <T> List<T>.rcomb(r: Int): Sequence<List<T>> { val i = IntArray(r) return generateSequence(i.map(::get)) s@{ _ -> val p = (r - 1 downTo 0).find { i[it] < size - 1 } ?: return@s null i.fill(i[p] + 1, p) i.map(::get) } } }
1
Kotlin
0
1
e650a9c2e73d26a8f037b4f9f0dfe960171a604a
2,575
atcoder-workspace
MIT License
LeetCode2020April/week3/src/main/kotlin/net/twisterrob/challenges/leetcode2020april/week3/number_islands/Solution.kt
TWiStErRob
136,539,340
false
{"Kotlin": 104880, "Java": 11319}
package net.twisterrob.challenges.leetcode2020april.week3.number_islands class Solution { fun numIslands(grid: Array<CharArray>): Int { val islands = Array(grid.size) { r -> IntArray(grid[0].size) { c -> when (grid[r][c]) { '1' -> Marker.UNPROCESSED_LAND '0' -> Marker.WATER else -> error("Invalid character at position $r, $c: '${grid[r][c]}'") } } } val marker = Marker(islands) marker.markIslands() return marker.islandCount } } private class Marker( private val islands: Array<IntArray> ) { companion object { const val UNPROCESSED_LAND = -1 const val WATER = 0 // anything above 0 is a marked island private const val FIRST_ISLAND = 1 } private var nextIsland = FIRST_ISLAND val islandCount: Int get() = nextIsland - 1 @Suppress("LoopToCallChain") fun markIslands() { // Walk the map and traverse the full island when unprocessed land found. for (r in islands.indices) { for (c in islands[r].indices) { if (islands[r][c] == UNPROCESSED_LAND) { markIsland(r, c, island = nextIsland++) } } } } private fun markIsland(r: Int, c: Int, island: Int) { if (r < 0 || islands.size <= r) return // outside the map -> water -> nothing to do if (c < 0 || islands[r].size <= c) return // outside the map -> water -> nothing to do when (islands[r][c]) { UNPROCESSED_LAND -> { islands[r][c] = island markIsland(r - 1, c, islands[r][c]) markIsland(r + 1, c, islands[r][c]) markIsland(r, c - 1, islands[r][c]) markIsland(r, c + 1, islands[r][c]) } WATER -> return // nothing to do else -> return // already processed } } }
1
Kotlin
1
2
5cf062322ddecd72d29f7682c3a104d687bd5cfc
1,645
TWiStErRob
The Unlicense
src/main/kotlin/com/groundsfam/advent/y2020/d14/Day14.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d14 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.pow import kotlin.io.path.div import kotlin.io.path.useLines private sealed class Instruction private data class SetMask(val mask: String) : Instruction() private data class WriteValue(val location: Int, val value: Long) : Instruction() private val memRegex = Regex("""mem\[(.+)] = (.+)""") private fun parseInstruction(line: String): Instruction = when { line.startsWith("mask = ") -> { SetMask(line.substringAfter("mask = ")) } else -> { val (location, origValue) = memRegex.matchEntire(line)!!.destructured WriteValue(location.toInt(), origValue.toLong()) } } private fun runProgram1(program: List<Instruction>): Long { var zeroesMask: Long = 0 var onesMask: Long = 0 val memory = mutableMapOf<Int, Long>() program.forEach { ins -> when (ins) { is SetMask -> { ins.mask.let { zeroesMask = it.replace('X', '1').toLong(2) onesMask = it.replace('X', '0').toLong(2) } } is WriteValue -> { memory[ins.location] = (ins.value and zeroesMask) or onesMask } } } return memory.values.sum() } private fun runProgram2(program: List<Instruction>): Long { var onesMask: Long = 0 // zeroesMask + floatingBits together implement the wildcard nature of Xs // zeroesMask is the 36 bit number of zeroes for Xs in the mask, and 1s elsewhere // floatingBits is a list of all the inverse indices of Xs, // i.e. 00000000000000000000000000000000000X would have floatingBits = [0], not [35] var zeroesMask: Long = 0 var floatingBits: List<Int> = emptyList() val memory = mutableMapOf<Long, Long>() fun setAll(location: Long, value: Long, fbIdx: Int) { if (fbIdx == floatingBits.size) { memory[location] = value } else { setAll(location, value, fbIdx + 1) setAll(location + 2.pow(floatingBits[fbIdx]), value, fbIdx + 1) } } program.forEach { ins -> when (ins) { is SetMask -> { ins.mask.let { onesMask = it.replace('X', '0').toLong(2) zeroesMask = it.replace('0', '1').replace('X', '0').toLong(2) floatingBits = it.mapIndexed { i, c -> (it.length - i - 1).takeIf { c == 'X' } }.filterNotNull() } } is WriteValue -> { ((ins.location.toLong() and zeroesMask) or onesMask).let { loc -> setAll(loc, ins.value, 0) } } } } return memory.values.sum() } fun main() { val program = (DATAPATH / "2020/day14.txt") .useLines { it.map(::parseInstruction).toList() } runProgram1(program) .also { println("Part one: $it") } runProgram2(program) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
3,082
advent-of-code
MIT License
src/questions/FindDuplicateNumber.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import kotlin.math.ceil import kotlin.test.assertEquals /** * Given an array of integers nums containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. * There is only one repeated number in `nums`, return this repeated number. * You must solve the problem without modifying the array nums and uses only constant extra space. * * [Source](https://leetcode.com/problems/find-the-duplicate-number/) */ @UseCommentAsDocumentation private fun findDuplicate(nums: IntArray): Int { val maxValue = nums.maxOrNull()!! // we need to accommodate [maxValue]. One array can hold 8 1/0s val countsOfByteArraysRequiredToHoldMaxValue = ceil((maxValue.toDouble() + 1) / 8).toInt() // only dealing with positive number, sign doesn't matter so using 8 // [ 00000000, 00000000, 00000000, 00000000 ] // [ 00000000, 00000000, 00000000, 00000001 ] => 1 has been seen // [ 00000000, 00000000, 00000000, 00000010 ] => 2 has been seen // [ 00000000, 00000000, 00000001, 00000000 ] => 9 has been seen // each bit in an element represents whether the value has occurred yet or not val byteArray = ByteArray(countsOfByteArraysRequiredToHoldMaxValue) { 0.toByte() } nums.forEach { val indexOfStoringArray = it / 8 // find the index where the [it] should be stored // after finding the index in the [array], find how much to shift // if it is product of 8, then it should be shifted to full length of a byte // else it should be shifted by compensating the [indexOfStoringArray] val howMuchToShift = if (it > 0 && it % 8 == 0) 8 else it - 8 * indexOfStoringArray // shift left // -1 because [nums] is in range [1,n] so element = 1 should be in 0th array at 0th bit val setter = 1.shl(howMuchToShift - 1) // when and-ed with setter, if it doesn't return 0 means it had already been set so this must be the duplicate val mask = byteArray[indexOfStoringArray].toInt().and(setter) if (mask != 0) { return it } val newMask = setter.or(byteArray[indexOfStoringArray].toInt()) // set the bit byteArray[indexOfStoringArray] = newMask.toByte() // write it to [array] } return -1 // unknown } fun main() { assertEquals(16, findDuplicate(intArrayOf(14, 16, 12, 1, 16, 17, 6, 8, 5, 19, 16, 13, 16, 3, 11, 16, 4, 16, 9, 7))) assertEquals(8, findDuplicate(intArrayOf(8, 9, 8, 4, 2, 8, 1, 5))) assertEquals(7, findDuplicate(intArrayOf(7, 9, 7, 4, 2, 8, 7, 7, 1, 5))) assertEquals(1, findDuplicate(intArrayOf(1, 3, 1, 2))) assertEquals(2, findDuplicate(intArrayOf(1, 3, 2, 2))) assertEquals(3, findDuplicate(intArrayOf(3, 1, 3, 4, 2))) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,799
algorithms
MIT License
kotlin/src/main/kotlin/AoC_Day23.kt
sviams
115,921,582
false
null
object AoC_Day23 { fun registers(aVal: Long) = mapOf<Char, Long>('a' to aVal, 'b' to 0, 'c' to 0, 'd' to 0, 'e' to 0, 'f' to 0, 'g' to 0, 'h' to 0, 'x' to 0) data class State(val registers: Map<Char, Long>, val pc: Long, val isTerminated: Boolean) fun parseOps(instructions: List<String>) : List<(State) -> State> = instructions.fold(listOf()) { acc, instr -> acc + parseInstruction(instr) } fun parseInstruction(input: String) : (State) -> State { val split = input.split(" ") return when (split[0]) { "set" -> setFunc(split[1].first(), split[2]) "sub" -> subFunc(split[1].first(), split[2]) "mul" -> mulFunc(split[1].first(), split[2]) else -> jnzFunc(split[1], split[2]) } } fun parseValue(str: String, state: State) : Long = if (str.first().isDigit() || str.first() == '-') str.toLong() else state.registers[str.first()]!! fun shouldStop(state: State, maxOps: Int) : Boolean = !(state.pc in 0..(maxOps - 1)) fun setFunc(register: Char, value: String) : (State) -> State = { State(it.registers.plus(Pair(register, parseValue(value, it))), it.pc + 1, false) } fun subFunc(register: Char, value: String) : (State) -> State = { State(it.registers.plus(Pair(register, it.registers[register]!! - parseValue(value, it))), it.pc + 1, false) } fun mulFunc(register: Char, value: String) : (State) -> State = { State(it.registers.plus(Pair(register, it.registers[register]!! * parseValue(value, it))).plus(Pair('x', (it.registers['x']!! + 1L))), it.pc + 1, false) } fun jnzFunc(register: String, value: String) : (State) -> State = { if (parseValue(register, it) != 0L) State(it.registers,it.pc + parseValue(value, it), false) else State(it.registers,it.pc + 1, false) } fun doOneOp(it: State, ops: List<(State) -> State>) : State = ops[it.pc.toInt()](it) fun solvePt1(input: List<String>) : Long { val ops = parseOps(input) val startState = State(registers(0), 0,false) return generateSequence(startState) { doOneOp(it, ops) }.takeWhile { !shouldStop(it, ops.size) }.last().registers['x']!! } fun solvePt2(input: List<String>) : Int { val seed = input.first().split(" ").last().toInt() val low = seed * 100 + 100000 val high = low + 17000 return (low..high step 17).fold(0) { acc, value -> if (notPrime(value)) acc + 1 else acc } } fun notPrime(num: Int) : Boolean { (2..num/2).forEach { if (num % it == 0) return true } return false } /* fun rewritten() : Int { val low = 81 * 100 + 100000 val high = low + 17000 var h = 0 (low..high step 17).forEach { b -> var f = 1 (2..b).forEach { d -> (2..b).forEach { e -> if (d * e == b) f = 0 } } if (f == 0) h++ } return h } fun reconstructed() : Long { var a: Long = 1 var b: Long = 81 * 100 + 100000 var c: Long = b + 17000 var d: Long = 0 var e: Long = 0 var f: Long = 0 var g: Long = 0 var h: Long = 0 while (true) { f = 1 d = 2 while (g != 0L) { e = 2 while (g != 0L) { g = d * e - b if (g == 0L) f = 0 e++ g = e g -= b } d++ g = d - b } if (f == 0L) h++ g = b - c if (g == 0L) return h b += 17 } } */ }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
3,809
aoc17
MIT License
src/Day05.kt
euphonie
571,665,044
false
{"Kotlin": 23344}
class MultiStack(private val stackCount: Int, private val stackSize: Int) { private val array: Array<String> = Array(stackCount * stackSize) {""} private val tops: Array<Int> = Array(stackCount) {-1} fun push(stackIndex: Int, value: String) { if (tops[stackIndex] == stackSize -1) { throw Exception("full") } tops[stackIndex] += 1 array[getTopIndex(stackIndex)] = value } fun pop(stackIndex : Int) : String { if (tops[stackIndex] == -1) { throw Exception("empty stack") } val topIndex = getTopIndex(stackIndex) val value = array[topIndex] array[topIndex] = "" tops[stackIndex] -= 1 return value } fun multiPush(stackIndex: Int, values: List<String>) { values.forEach{ v -> push(stackIndex, v) } } fun multiPop(stackIndex: Int, count: Int) : List<String> { if (tops[stackIndex] == -1) { throw Exception("empty stack") } return IntRange(1, count).map { pop(stackIndex) } } fun peek( stackIndex: Int) : String { if (tops[stackIndex] == -1) { throw Exception("empty stack") } return array[getTopIndex(stackIndex)] } fun isEmpty(stackIndex: Int) : Boolean { return tops[stackIndex] == -1 } private fun getTopIndex(stackIndex: Int) : Int { return stackIndex * stackSize + tops[stackIndex] } } class Command(val count: Int, val origin: Int, val dest: Int ) fun main() { fun parseAssignments(input: List<String>) : List<List<String>> { return input .takeWhile { !it.trimStart().startsWith("1") } .map { current -> (1 until current.length step 4).map { current[it].toString() } } } fun createCommand(input: String) : Command { val regex = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)") return regex.matchEntire(input)?.destructured ?.let { (count, origin, dest) -> try { Command(count = count.toInt(), origin = origin.toInt(), dest = dest.toInt()) } catch(e: Exception) { Command (count = 0, origin = 0, dest = 0) } } ?: Command (count = 0, origin = 0, dest = 0) } fun parseCommands(input: List<String>) : List<Command> { val firstCommandIndex = input.withIndex().first { it.value.trimStart().startsWith("move") }.index return input.subList(firstCommandIndex, input.size) .map { createCommand(it) } } fun processInput(input: List<String>) : Pair<List<List<String>>, List<Command>> { val assignments = parseAssignments(input) if (assignments.isEmpty()) { throw Exception("no assignments") } val commands = parseCommands(input) return Pair(assignments, commands) } fun part1(input: List<String>) : String { val (assignments, commands) = processInput(input) val stackCount = assignments.first().size val stacks : MultiStack = MultiStack(stackCount, assignments.size * stackCount) assignments.reversed() .forEach { assignment -> assignment.indices.forEach { i -> if (assignment[i] != " ") stacks.push(i, assignment[i]) } } commands.forEach { command -> IntRange(1, command.count).forEach { _ -> run { val el = stacks.pop(command.origin - 1) stacks.push(command.dest - 1, el) } } } return IntRange(0, stackCount -1).joinToString("") { stacks.peek(it) } } fun part2(input: List<String>) : String { val (assignments, commands) = processInput(input) val stackCount = assignments.first().size val stacks : MultiStack = MultiStack(stackCount, assignments.size * stackCount) assignments.reversed() .forEach { assignment -> assignment.indices.forEach { i -> if (assignment[i] != " ") stacks.push(i, assignment[i]) } } commands.forEach { command -> val elements = stacks.multiPop(command.origin -1, command.count) stacks.multiPush(command.dest -1, elements.reversed()) } return IntRange(0, stackCount -1).joinToString("") { stacks.peek(it) } } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") check(part1(input) == "PSNRGBTFT") check(part2(input) == "BNTZFPMMW") }
0
Kotlin
0
0
82e167e5a7e9f4b17f0fbdfd01854c071d3fd105
4,845
advent-of-code-kotlin
Apache License 2.0
src/Day08.kt
a-glapinski
572,880,091
false
{"Kotlin": 26602}
import utils.readInputAsLines fun main() { val input = readInputAsLines("day08_input_test") val grid = input.map { it.map(Char::digitToInt) } val result1 = flyOver(grid, lookAround = { current, direction -> direction.all { it < current } }, calculate = { directions -> if (directions.any { it }) 1 else 0 } ).sum() println(result1) val result2 = flyOver(grid, lookAround = { current, direction -> (direction.indexOfFirst { it >= current } + 1).takeIf { it != 0 } ?: direction.size }, calculate = { it.reduce(Int::times) } ).max() println(result2) } fun <T> flyOver(grid: List<List<Int>>, lookAround: (Int, List<Int>) -> T, calculate: (List<T>) -> Int): List<Int> = with(grid.indices) { flatMap { i -> map { j -> val current = grid[i][j] val left = lookAround(current, grid[i].slice(j - 1 downTo 0)) val right = lookAround(current, grid[i].slice(j + 1 until grid.size)) val up = lookAround(current, grid.slice(i - 1 downTo 0).map { it[j] }) val down = lookAround(current, grid.slice(i + 1 until grid.size).map { it[j] }) calculate(listOf(left, right, up, down)) } } }
0
Kotlin
0
0
c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8
1,298
advent-of-code-2022
Apache License 2.0
src/Day05.kt
erikthered
572,804,470
false
{"Kotlin": 36722}
fun main() { fun part1(input: List<String>): String { var stacks = arrayListOf<ArrayDeque<Char>>() var layout = true for(line in input) { if(layout) { if(line.isBlank()) { layout = false } val cols = line.windowed(3, 4) cols.forEachIndexed { idx, c -> val index = idx + 1 if(index > stacks.size) { stacks.add(ArrayDeque()) } if (!c[1].isWhitespace() && !c[1].isDigit()) { stacks[idx].addFirst(c[1]) } } } else { val segments = line.split(" ") val quantity = segments[1].toInt() val source = segments[3].toInt() val dest = segments[5].toInt() repeat(quantity) { stacks[dest-1].addLast(stacks[source-1].removeLast()) } } } return stacks.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { var stacks = arrayListOf<ArrayDeque<Char>>() var layout = true for(line in input) { if(layout) { if(line.isBlank()) { layout = false } val cols = line.windowed(3, 4) cols.forEachIndexed { idx, c -> val index = idx + 1 if(index > stacks.size) { stacks.add(ArrayDeque()) } if (!c[1].isWhitespace() && !c[1].isDigit()) { stacks[idx].addFirst(c[1]) } } } else { val segments = line.split(" ") val quantity = segments[1].toInt() val source = segments[3].toInt() val dest = segments[5].toInt() val payload = arrayListOf<Char>() repeat(quantity) { payload.add(stacks[source-1].removeLast()) } payload.reversed().forEach { stacks[dest-1].addLast(it) } } } return stacks.map { it.last() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3946827754a449cbe2a9e3e249a0db06fdc3995d
2,664
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/mirecxp/aoc23/day01/Day01.kt
MirecXP
726,044,224
false
{"Kotlin": 42343}
package mirecxp.aoc23.day01 import java.io.File import java.util.* //https://adventofcode.com/2023/day/1 class Day01(inputPath: String) { private val calibrations: List<String> = File(inputPath).readLines().map { it.lowercase(Locale.getDefault()) } fun solveA() { println("Solving day 1A for ${calibrations.size} lines") var sum = 0L calibrations.forEach { line -> val first = line.first { it.isDigit() }.digitToInt() val last = line.last { it.isDigit() }.digitToInt() val cal = 10 * first + last println("calibration value is $cal") sum += cal } println("Sum is $sum") } //eightwo = 82 fun solveB() { println("Solving day 1B for ${calibrations.size} lines") var sum = 0L calibrations.forEach { line -> val first = firstTextOrNumericDigit(line) val last = lastTextOrNumericDigit(line) val cal = 10 * first + last println("calibration value is $cal") sum += cal } println("sum is $sum") } private fun firstTextOrNumericDigit(line: String): Int { var digit: Int = 0 var index: Int = Int.MAX_VALUE val first = line.first { it.isDigit() }.digitToInt() digit = first index = line.indexOfFirst { it.isDigit() } stringDigits.forEach { (sDigit: String, nDigit: Int) -> val i = line.indexOf(sDigit) if (i in 0 until index) { index = i digit = nDigit } } return digit } private fun lastTextOrNumericDigit(line: String): Int { var digit: Int = 0 var index: Int = -1 val last = line.last { it.isDigit() }.digitToInt() digit = last index = line.indexOfLast { it.isDigit() } stringDigits.forEach { (sDigit: String, nDigit: Int) -> val i = line.lastIndexOf(sDigit) if (i > index) { index = i digit = nDigit } } return digit } private val stringDigits: List<Pair<String, Int>> = listOf( "zero" to 0, "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) } fun main(args: Array<String>) { val problem = Day01("/Users/miro/projects/AoC23/input/day01a.txt") problem.solveA() problem.solveB() }
0
Kotlin
0
0
6518fad9de6fb07f28375e46b50e971d99fce912
2,559
AoC-2023
MIT License
lib/src/main/kotlin/de/linkel/aoc/utils/iterables/CombinationMixIn.kt
norganos
726,350,504
false
{"Kotlin": 162220}
package de.linkel.aoc.utils.iterables fun <T> List<T>.combinationPairs( withSelf: Boolean = false, withMirrors: Boolean = false ): Sequence<Pair<T,T>> { val size = this.size val list = this return sequence { (0 until size) .forEach { i -> ((if (withMirrors) 0 else i) until size) .forEach { j -> if (withSelf || i != j) { yield(Pair(list[i], list[j])) } } } } } fun <A, B> List<A>.combineWith(other: List<B>): Sequence<Pair<A, B>> { val list = this return sequence { list .forEach { a -> other.forEach { b -> yield(Pair(a, b)) } } } } fun <T> List<List<T>>.combinations(): Sequence<List<T>> { val outer = this return sequence { val sizes = outer.map { it.size } val indices = outer.map { 0 }.toMutableList() while (indices.mapIndexed { i, o -> o < sizes[i] }.all { it }) { yield( indices.mapIndexed { i,o -> outer[i][o] } ) if (outer.indices .firstOrNull { i -> indices[i] = indices[i] + 1 if (indices[i] >= sizes[i]) { indices[i] = 0 false } else true } == null) { break } } } } fun <T> List<T>.permutations(maxSize: Int = -1): Sequence<List<T>> { val list = this return sequence { if (list.isEmpty() || maxSize == 0) { yield(emptyList()) } else { list.indices.forEach { i -> val item = list[i] list.withoutIndex(i).permutations(maxSize - 1) .forEach { yield(it + item) } } } } }
0
Kotlin
0
0
3a1ea4b967d2d0774944c2ed4d96111259c26d01
2,005
aoc-utils
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch6/Problem63.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch6 import kotlin.math.log10 import kotlin.math.pow /** * Problem 63: Powerful Digit Counts * * https://projecteuler.net/problem=63 * * Goal: Given N, find all N-digit positive integers that are also a Nth power. * * Constraints: 1 <= N <= 19 * * e.g.: N = 2 * output = [16, 25, 36, 49, 64, 81] */ class PowerfulDigitCounts { /** * Solution optimised by searching backwards from 9^N, as 10^N produces a number with (N + 1) * digits, and breaking the loop as soon as the power's digits drop below N. * * @return list of all N-digit integers that are a Nth power, in ascending order. */ fun nDigitNthPowers(n: Int): List<Long> { val results = mutableListOf<Long>() for (x in 9 downTo 1) { var power = 1L // using pow would create scientific notation double at higher constraints // which would lose accuracy when converted to Long repeat(n) { power *= x } val digits = log10(1.0 * power).toInt() + 1 if (digits == n) { results.add(power) } else { break } } return results.reversed() } /** * Project Euler specific implementation that requests a count of all N-digit positive * integers that are also a Nth power. * * N.B. The last 9-digit number to also be a 9th power occurs at N = 21. * * SPEED (WORSE) 9.0e4ns to count all valid numbers */ fun allNDigitNthPowers(): Int { var total = 0 var n = 1 while (true) { var count = 0 for (x in 9 downTo 1) { val power = (x.toDouble()).pow(n) val digits = log10(power).toInt() + 1 if (digits == n) count++ else break } // if 9^N has less than N digits, no future integers exist if (count == 0) break total += count n++ } return total } /** * Project Euler specific implementation that requests a count of all N-digit positive * integers that are also a Nth power. * * Solution is based on the following formula: * * 10^(n-1) <= x^n < 10^n, so find where the lower bounds meets x^n * * 10^(n-1) = x^n, using the quotient rule of exponentiation becomes * * 10^n / 10^1 = x^n * * log(10)n / log(10) = log(x)n, using the quotient rule of logarithms becomes * * log(10)n - log(10) = log(x)n * * n = log(10) / (log(10) - log(x)) -> 1 / (1 - log(x)) * * SPEED (BETTER) 3.0e4ns to count all valid numbers */ fun allNDigitNthPowersFormula(): Int { var total = 0 for (n in 1..9) { total += (1 / (1 - log10(1.0 * n))).toInt() } return total } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,944
project-euler-kotlin
MIT License
src/Day04.kt
MerickBao
572,842,983
false
{"Kotlin": 28200}
fun main() { fun game1(s: String): Boolean { val arr = s.split(",") val L = arr[0].split("-") val R = arr[1].split("-") val ll = L[0].toInt() val lr = L[1].toInt() val rl = R[0].toInt() val rr = R[1].toInt() return ll >= rl && lr <= rr || rl >= ll && rr <= lr } fun game2(s: String): Boolean { val arr = s.split(",") val L = arr[0].split("-") val R = arr[1].split("-") val ll = L[0].toInt() val lr = L[1].toInt() val rl = R[0].toInt() val rr = R[1].toInt() return ll in rl..rr || lr in rl..rr || rl in ll..lr || rr in ll..lr } fun part1(input: List<String>): Int { var ans = 0 for (s in input) { if (game1(s)) ans++ } return ans } fun part2(input: List<String>): Int { var ans = 0 for (s in input) { if (game2(s)) ans++ } return ans } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
70a4a52aa5164f541a8dd544c2e3231436410f4b
1,077
aoc-2022-in-kotlin
Apache License 2.0
app/src/main/java/com/marknkamau/justjava/data/models/AppProduct.kt
MarkNjunge
86,477,705
false
{"Kotlin": 237127}
package com.marknkamau.justjava.data.models import com.marknjunge.core.data.model.Product import com.marknjunge.core.data.model.ProductChoice import com.marknjunge.core.data.model.ProductChoiceOption data class AppProduct( val id: Long, val name: String, val slug: String, val image: String, val createdAt: Long, val price: Double, val description: String, val type: String, var choices: List<AppProductChoice>?, val status: String ) { fun calculateTotal(quantity: Int): Double { val basePrice = price val optionsTotal = choices?.fold(0.0) { i, c -> i + c.options .filter { it.isChecked } .fold(0.0) { acc, o -> acc + o.price } } ?: 0.0 return (basePrice + optionsTotal) * quantity } fun validate(): MutableList<String> { val errors = mutableListOf<String>() choices?.forEach { choice -> if (choice.isRequired && !choice.hasValue) { errors.add(choice.name) } } return errors } } data class AppProductChoice( val id: Int, val name: String, val position: Int, val qtyMax: Int, val qtyMin: Int, var options: List<AppProductChoiceOption> ) { val isRequired: Boolean = qtyMin == 1 val isSingleSelectable = qtyMax == 1 val hasValue: Boolean get() = options.any { it.isChecked } } data class AppProductChoiceOption( val id: Int, val price: Double, val name: String, val description: String?, var isChecked: Boolean = false ) fun Product.toAppModel() = AppProduct( id, name, slug, image, createdAt, price, description, type, choices?.toAppChoice(), status ) private fun List<ProductChoice>.toAppChoice(): List<AppProductChoice> = this.map { AppProductChoice( it.id, it.name, it.position, it.qtyMax, it.qtyMin, it.options.toAppOption() ) }.sortedBy { it.id } private fun List<ProductChoiceOption>.toAppOption(): List<AppProductChoiceOption> = map { AppProductChoiceOption( it.id, it.price, it.name, it.description ) }.sortedBy { it.price }
1
Kotlin
35
74
e3811f064797d50fadef4033bf1532b3c2ceef8d
2,294
JustJava-Android
Apache License 2.0
src/Day25.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
fun main() { val testInput = readInput("Day25_test") val input = readInput("Day25") part1(testInput).also { println("Part 1, test input: $it") check(it == "2=-1=0") } part1(input).also { println("Part 1, real input: $it") //check(it == 1) } part2(testInput).also { println("Part 2, test input: $it") check(it == 1) } part2(input).also { println("Part 2, real input: $it") //check(it == 1) } } private fun part1(input: List<String>): String { val i = input .map(String::fromSnafu) val sum = i.sum() return sum.toSnafu() } private fun Long.toSnafu(): String { var cf = 0L var l = this val res: MutableList<Char> = mutableListOf() while (l != 0L) { val d = (l % 5L) + cf cf = 0 when (d) { in 0..2 -> { res += d.toInt().digitToChar() } in 3..4 -> { cf = 1 val v = when (d) { 3L -> '=' 4L -> '-' else -> error("Unknown value") } res += v } else -> { error("Unexpected d $d") } } l /= 5L } if (cf > 0) { res += cf.toInt().digitToChar() } return res.reversed().joinToString("") } private fun String.fromSnafu(): Long { var r = 0L fun Char.fromSnafu(): Long { return when (this) { '0' -> 0L '1' -> 1L '2' -> 2L '-' -> -1L '=' -> -2L else -> error("Unknown number") } } this.forEach { c -> r = r * 5 + c.fromSnafu() } return r } private fun part2(input: List<String>): Int { return input.size }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
1,853
aoc22-kotlin
Apache License 2.0
src/Day06.kt
esteluk
572,920,449
false
{"Kotlin": 29185}
fun main() { fun findMarker(message: String, size: Int): Int { val windows = message.windowed(size, 1) val index = windows.indexOfFirst { it.toCharArray().distinct().size == size } return index + size } fun part1(input: String): Int { return findMarker(input, 4) } fun part1(input: List<String>): Int { return part1(input.first()) } fun part2(input: String): Int { return findMarker(input, 14) } fun part2(input: List<String>): Int { return part2(input.first()) } // test if implementation meets criteria from the description, like: check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73
1,298
adventofcode-2022
Apache License 2.0
year2023/src/cz/veleto/aoc/year2023/Day09.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2023 import cz.veleto.aoc.core.AocDay class Day09(config: Config) : AocDay(config) { override fun part1(): String = input .mapToEndStates() .map { it.lastNumbers.sum() } // b = a + c .sum() .toString() override fun part2(): String = input .mapToEndStates() .map { state -> // a = b - c state.firstNumbers.asReversed() .reduce { extrapolated, firstNumber -> firstNumber - extrapolated } } .sum() .toString() private fun Sequence<String>.mapToEndStates(): Sequence<State> = this .map { line -> line.split(' ').map { it.toLong() } } .map { history -> history .indices // maximum number of sequences .asSequence() .runningFold(State(history)) { state, _ -> state.extend(state.lastSequence.zipWithNext { a, b -> b - a }) } .onEach { if (config.log) println(it.lastSequence.joinToString(" ")) } .first { state -> state.lastSequence.all { it == 0L } } } private fun State.extend(newSequence: List<Long>): State = State( lastSequence = newSequence, firstNumbers = firstNumbers + newSequence.first(), lastNumbers = lastNumbers + newSequence.last(), ) data class State( val lastSequence: List<Long>, val firstNumbers: List<Long> = listOf(lastSequence.first()), val lastNumbers: List<Long> = listOf(lastSequence.last()), ) }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
1,575
advent-of-pavel
Apache License 2.0
src/Day10.kt
kecolk
572,819,860
false
{"Kotlin": 22071}
data class Instruction(val operation: String, val operand: Int = 0) fun parseInput(input: List<String>): List<Instruction> = input.map { val parts = it.split(" ") Instruction( operation = parts[0], operand = if (parts[0] == "addx") parts[1].toInt() else 0 ) } class Processor() { private var acc: Int = 1 private var pcounter = 1 private val signal: MutableList<Int> = mutableListOf() private val screen: MutableList<String> = mutableListOf() private var currentLine = "" fun execute(program: List<Instruction>) { program.forEach { instruction -> if (instruction.operation == "noop") { tick() } if (instruction.operation == "addx") { tick() tick() acc += instruction.operand } } } fun getSignalStrength() = signal.sum() fun printScreen() { screen.forEach { println(it) } } private fun tick() { if ((pcounter + 20).mod(40) == 0) signal.add(pcounter * acc) drawPixel() pcounter += 1 } private fun drawPixel() { val column = (pcounter - 1).mod(40) currentLine += if (column >= acc - 1 && column <= acc + 1) "#" else "." if (column == 39) { screen.add(currentLine) currentLine = "" } } } fun main() { val testInput = parseInput(readTextInput("Day10_test")) val input = parseInput(readTextInput("Day10")) check(part1(testInput) == 13140) part2(testInput) println(part1(input)) part2(input) } fun part1(program: List<Instruction>): Int { Processor().apply { execute(program) return getSignalStrength() } } fun part2(program: List<Instruction>) { Processor().apply { execute(program) printScreen() } }
0
Kotlin
0
0
72b3680a146d9d05be4ee209d5ba93ae46a5cb13
1,880
kotlin_aoc_22
Apache License 2.0
src/day03/Day03.kt
elenavuceljic
575,436,628
false
{"Kotlin": 5472}
package day03 import java.io.File fun main() { fun prioritiseItem(it: Char) = if (it.isUpperCase()) (it - 'A' + 27) else (it - 'a' + 1) fun part1(input: String): Int { val rucksacks = input.lines() val duplicateItems = rucksacks.flatMap { val (first, second) = it.chunked(it.length / 2) { it.toSet() } val intersect = first intersect second intersect } return duplicateItems.sumOf { prioritiseItem(it) } } fun part2(input: String): Int { val rucksacks = input.lines().map { it.toSet() } val compartments = rucksacks.chunked(3).flatMap { it.reduce(Set<Char>::intersect) } return compartments.sumOf { prioritiseItem(it) } } val testInput = File("src/day03/Day03_test.txt").readText().trim() val part1Solution = part1(testInput) val part2Solution = part2(testInput) println(part1Solution) check(part1Solution == 157) check(part2Solution == 70) val input = File("src/day03/Day03.txt").readText().trim() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c5093b111fd02e28823d31f2edddb7e66c295add
1,140
advent-of-code-2022
Apache License 2.0
src/y2021/Day06.kt
Yg0R2
433,731,745
false
null
package y2021 fun main() { fun part1(input: List<String>): Long { val fishTank = FishTank(input) for (i in 0 until 80) { fishTank.nextDay() } return fishTank.getFishCount() } fun part2(input: List<String>): Long { val fishTank = FishTank(input) for (i in 0 until 256) { fishTank.nextDay() } return fishTank.getFishCount() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 5934L) check(part2(testInput) == 26984457539L) val input = readInput("Day06") println(part1(input)) println(part2(input)) } private class FishTank( input: List<String> ) { companion object { private const val NEW_BORN_INTERNAL_TIMER = 8 private const val NEXT_CHILD_INTERNAL_TIMER = 6 } private val tank: Array<Long> = Array(NEW_BORN_INTERNAL_TIMER + 1) { 0L } init { input.flatMap { it.split(",") } .forEach { tank[it.toInt()] += 1L } } fun getFishCount() = tank.sum() fun nextDay() { val willBread = tank[0] for(index in 1..NEW_BORN_INTERNAL_TIMER) { tank[index - 1] = tank[index] } tank[NEW_BORN_INTERNAL_TIMER] = willBread tank[NEXT_CHILD_INTERNAL_TIMER] += willBread } }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
1,409
advent-of-code
Apache License 2.0
src/Day13_json.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonArray fun main() { operator fun JsonElement.compareTo(other: JsonElement): Int { if (this is JsonPrimitive) { if (other is JsonPrimitive) { return content.toInt() - other.content.toInt() } else return JsonArray(listOf(this)).compareTo(other) } else { if (other is JsonPrimitive) { return this.compareTo(JsonArray(listOf(other))) } else { val children = this.jsonArray val otherChildren = other.jsonArray for (i in 0..maxOf(children.lastIndex, otherChildren.lastIndex)) { if (i > children.lastIndex) return -1 if (i > otherChildren.lastIndex) return 1 val compareTo = children[i].compareTo(otherChildren[i]) if (compareTo != 0) { return compareTo } } return 0 } } } fun String.parse() = Json.parseToJsonElement(this) fun part1(input: List<String>): Int { var max = 0; var index = 0 for (signal in input.indices step 3) { index++ val left = input[signal].parse() val right = input[signal + 1].parse() if (left < right) { max += index } } return max } fun part2(input: List<String>): Int { val first = "[2]".parse() val second = "[6]".parse() var mult = 1 val newInput = input + listOf("[2]", "[6]") val map = newInput.filterNot { it.isBlank() }.map { it.parse() }.sortedWith( comparator = { one, two -> one.compareTo(two) } ) map.forEachIndexed { index, list -> if (list == first || list == second) { mult *= index + 1 } } return mult } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d7ab334f38a9e260c72725d3f583228acb6aa0e
2,463
advent-2022
Apache License 2.0
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day06/Day06.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day06 import eu.janvdb.aocutil.kotlin.readGroupedLines fun main() { val groups = readGroups() println(groups.map(Group::combineOr).map(Answers::count).sum()) println(groups.map(Group::combineAnd).map(Answers::count).sum()) } private fun readGroups(): List<Group> { return readGroupedLines(2020, "input06.txt").map { Group(it.map(::Answers)) } } class Answers { private val values: List<Boolean> constructor(line: String) { values = CharRange('a', 'z').map(line::contains) } constructor(values: List<Boolean>) { this.values = values } fun count(): Int { return values.count { it } } fun or(answers: Answers): Answers { val newValues = values.mapIndexed { index, value -> value || answers.values[index] } return Answers(newValues) } fun and(answers: Answers): Answers { val newValues = values.mapIndexed { index, value -> value && answers.values[index] } return Answers(newValues) } } class Group(private val answers: List<Answers>) { fun combineOr(): Answers { return answers.reduce { a1, a2 -> a1.or(a2) } } fun combineAnd(): Answers { return answers.reduce { a1, a2 -> a1.and(a2) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,163
advent-of-code
Apache License 2.0
AdventOfCodeDay12/src/nativeMain/kotlin/Day12.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
class Day12(lines:List<String>) { private val paths = buildPaths(lines) fun solvePart1() = traverse(::part1VisitRule).size fun solvePart2() = traverse(::part2VisitRule).size private fun buildPaths(input: List<String>): Map<String, List<String>> = input .map { it.split("-") } .flatMap { listOf( it.first() to it.last(), it.last() to it.first() ) } .groupBy({ it.first }, { it.second }) private fun traverse( allowedToVisit: (String, List<String>) -> Boolean, path: List<String> = listOf("start") ): List<List<String>> = if (path.last() == "end") listOf(path) else paths.getValue(path.last()) .filter { allowedToVisit(it, path) } .flatMap { traverse(allowedToVisit, path + it) } private fun part1VisitRule(name: String, path: List<String>): Boolean = name.isUpperCase() || name !in path private fun part2VisitRule(name: String, path: List<String>): Boolean = when { name.isUpperCase() -> true name == "start" -> false name !in path -> true else -> path .filterNot { it.isUpperCase() } .groupBy { it } .none { it.value.size == 2 } } private fun String.isUpperCase(): Boolean = all { it.isUpperCase() } }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
1,458
AdventOfCode2021
The Unlicense
src/main/kotlin/kt/kotlinalgs/app/kickstart/roundG22/curling.ws.kts
sjaindl
384,471,324
false
null
var line = 0 var args: Array<String> = arrayOf() fun readLine(): String? { val result = args[line] line++ return result } fun main(mainArgs: Array<String>) { args = mainArgs line = 0 // https://codingcompetitions.withgoogle.com/kickstart/round/00000000008cb2e1/0000000000c17c82 val testCases = readLine()?.toIntOrNull() ?: 0 for (testCase in 1 until testCases + 1) { val (radiusStone, radiusHouse) = (readLine()?.split(" ")?.map { it.toInt() }) ?: return val numStonesInHouseRed = readLine()?.toIntOrNull() ?: 0 val distancesRed: MutableList<Double> = mutableListOf() calcValidDistances(distancesRed, numStonesInHouseRed, radiusHouse, radiusStone) val numStonesInHouseYellow = readLine()?.toIntOrNull() ?: 0 val distancesYellow: MutableList<Double> = mutableListOf() calcValidDistances(distancesYellow, numStonesInHouseYellow, radiusHouse, radiusStone) distancesRed.sort() distancesYellow.sort() var pointsRed = 0 var pointsYellow = 0 if (distancesRed.isEmpty()) { pointsYellow = distancesYellow.size } else if (distancesYellow.isEmpty()) { pointsRed = distancesRed.size } else if (distancesYellow[0] < distancesRed[0]) { pointsYellow = calcPoints(distancesYellow, distancesRed) } else { pointsRed = calcPoints(distancesRed, distancesYellow) } println("Case #$testCase: $pointsRed $pointsYellow") } } fun calcPoints(winning: MutableList<Double>, loosing: MutableList<Double>): Int { var points = 0 var minOpponent = loosing[0] var index = 0 while (index < winning.size && winning[index] < minOpponent) { points++ index++ } return points } fun calcValidDistances( distances: MutableList<Double>, numStones: Int, radiusHouse: Int, radiusStone: Int ) { //println("radiusHouse: $radiusHouse, radiusStone: $radiusStone") for (num in 0 until numStones) { val (x0, y0) = (readLine()?.split(" ")?.map { it.toInt() }) ?: return var dist = euclideanDistance(x0, y0) - radiusStone.toDouble() //println("x0: $x0, y0: $y0, dist: $dist") if (dist <= radiusHouse) { distances.add(dist) } } } fun euclideanDistance(x0: Int, y0: Int, x1: Int = 0, y1: Int = 0): Double { return Math.sqrt( Math.pow(x0.toDouble() - x1.toDouble(), 2.0) + Math.pow(y0.toDouble() + y1.toDouble(), 2.0) ) } main( arrayOf( "2", "1 5", "4", "1 -1", "6 1", "0 6", "-5 0", "0", "10 100", "2", "-3 -4", "200 200", "0" ) ) main( arrayOf( "2", "1 5", "2", "1 0", "-3 0", "1", "0 2", "10 50", "2", "-40 -31", "-35 70", "3", "59 0", "-10 0", "30 40" ) )
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,008
KotlinAlgs
MIT License
src/main/kotlin/PerfectSquares.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * Given an integer n, return the least number of perfect square numbers that sum to n. * * A perfect square is an integer that is the square of an integer; * in other words, it is the product of some integer with itself. * For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. * * * * Example 1: * * Input: n = 12 * Output: 3 * Explanation: 12 = 4 + 4 + 4. * Example 2: * * Input: n = 13 * Output: 2 * Explanation: 13 = 4 + 9. * * * Constraints: * * 1 <= n <= 10^4 * @see <a href="https://leetcode.com/problems/perfect-squares/">LeetCode</a> */ fun numSquares(n: Int): Int { val resultList = IntArray(n + 1) { Int.MAX_VALUE } resultList[0] = 0 for (index in 1..n) { var squareNum = 1 while (index >= squareNum * squareNum) { resultList[index] = minOf(resultList[index], 1 + resultList[index - squareNum * squareNum]) squareNum++ } } return resultList[n] }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
972
kotlin-codes
Apache License 2.0
src/main/kotlin/us/jwf/aoc2021/Day17TrickShot.kt
jasonwyatt
318,073,137
false
null
package us.jwf.aoc2021 import java.io.Reader import us.jwf.aoc.Day /** * AoC 2021 - Day 17 */ class Day17TrickShot : Day<Int, Int> { override suspend fun executePart1(input: Reader): Int { val targetArea = Rect(96..125, -144..-98) val highestValidYs = mutableSetOf<Int>() (1..125).forEach { candidateDx -> (1..1000).forEach { candidateDy -> var probe = Probe(0, 0, 0, candidateDx, candidateDy) var highestY = 0 do { probe = probe.step() highestY = maxOf(highestY, probe.y) } while (probe.keepGoing(targetArea)) if (probe in targetArea) { highestValidYs += highestY } } } return highestValidYs.maxOf { it } } override suspend fun executePart2(input: Reader): Int { val targetArea = Rect(96..125, -144..-98) val solutions = mutableSetOf<Pair<Int, Int>>() (1..targetArea.xRange.last).forEach { candidateDx -> (targetArea.yRange.first..1000).forEach { candidateDy -> var probe = Probe(0, 0, 0, candidateDx, candidateDy) do { probe = probe.step() } while (probe.keepGoing(targetArea)) if (probe in targetArea) { solutions.add(candidateDx to candidateDy) } } } return solutions.size } data class Rect(val xRange: IntRange, val yRange: IntRange) { operator fun contains(probe: Probe): Boolean = probe.x in xRange && probe.y in yRange operator fun compareTo(probe: Probe): Int { if (probe in this) return 0 if (probe.x > xRange.last || probe.y < yRange.first) return -1 return 1 } } data class Probe(val x: Int, val y: Int, val t: Int, val dx: Int, val dy: Int) { fun step(): Probe = Probe(x + dx, y + dy, t + 1, maxOf(0, dx - 1), dy - 1) fun keepGoing(target: Rect): Boolean { if (this in target) return false if (target < this) return false if (dx == 0 && x !in target.xRange) return false return true } } }
0
Kotlin
0
0
0c92a62ba324aaa1f21d70b0f9f5d1a2c52e6868
2,001
AdventOfCode-Kotlin
Apache License 2.0
kotlin/09.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
class Day9 : Day<TwoDimensionalArray<Int>>("09") { override fun dataStar1(lines: List<String>): TwoDimensionalArray<Int> = TwoDimensionalArray(lines.map { line -> line.map(Char::digitToInt) }) override fun dataStar2(lines: List<String>): TwoDimensionalArray<Int> = dataStar1(lines) override fun star1(data: TwoDimensionalArray<Int>): Number = data.with2DIndex() .filter { (row, col, v) -> data.getHorizontalAndVerticalNeighbors(row, col).all { (_, _, x) -> x > v } } .sumOf { it.value + 1 } fun flood(row: Int, col: Int, data: TwoDimensionalArray<Int>, filled: TwoDimensionalArray<Boolean>): Int { return if (row !in 0 until data.rows || col !in 0 until data.cols || filled[row, col]) 0 else { filled[row, col] = true 1 + flood(row - 1, col, data, filled) + flood(row + 1, col, data, filled) + flood(row, col - 1, data, filled) + flood(row, col + 1, data, filled) } } override fun star2(data: TwoDimensionalArray<Int>): Number { val filled = data.map { it == 9 } return data.indices2D() .map { (row, col) -> flood(row, col, data, filled) } .sortedDescending() .take(3) .toList() .let { (a, b, c) -> a * b * c } } } fun main() { Day9()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
1,399
advent-of-code-2021
MIT License
src/Day06.kt
cnietoc
572,880,374
false
{"Kotlin": 15990}
fun main() { fun process(input: String, markerSize: Int): Int { val chars = input.iterator() var charProcessedCount = 0; val charProcessed = ArrayDeque<Char>(markerSize + 1) while (chars.hasNext()) { charProcessed.add(chars.nextChar()) charProcessedCount++ if (charProcessed.size > markerSize) { charProcessed.removeFirst() if (charProcessed.distinct().size == markerSize) return charProcessedCount } } return charProcessedCount } fun part1(input: String): Int { return process(input, 4) } fun part2(input: String): Int { return process(input, 14) } val testInput = readInput("Day06_test") val input = readInput("Day06") check(part1(testInput[0]) == 7) check(part1(testInput[1]) == 5) check(part1(testInput[2]) == 6) check(part1(testInput[3]) == 10) check(part1(testInput[4]) == 11) println(part1(input.first())) check(part2(testInput[0]) == 19) check(part2(testInput[1]) == 23) check(part2(testInput[2]) == 23) check(part2(testInput[3]) == 29) check(part2(testInput[4]) == 26) println(part2(input.first())) }
0
Kotlin
0
0
bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3
1,262
aoc-2022
Apache License 2.0
leetcode2/src/leetcode/decode-ways.kt
hewking
68,515,222
false
null
package leetcode /** * 91. 解码方法 * https://leetcode-cn.com/problems/decode-ways/ * Created by test * Date 2020/1/31 0:02 * Description * 一条包含字母 A-Z 的消息通过以下方式进行了编码: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。 示例 1: 输入: "12" 输出: 2 解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。 示例 2: 输入: "226" 输出: 3 解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/decode-ways 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object DecodeWays { class Solution { /** * 思路: 动态规划 * https://leetcode-cn.com/problems/decode-ways/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-2-3/ */ fun numDecodings(s: String): Int { val len = s.length val dp = IntArray(len + 1) dp[len] = 1 if (s[len - 1] != '0') { dp[len - 1] = 1 } for (i in len -1 downTo 0) { if (s[i] == '0') { continue } val ans1 = dp[i + 1] var ans2 = 0 val ten = (s[i] - '0') * 10 val one = s[i + 1] - '0' if (ten + one <= 26) { ans2 = dp[i + 2] } dp[i] = ans1 + ans2 } return dp[0] } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,636
leetcode
MIT License
src/main/kotlin/days/Day2.kt
hughjdavey
159,955,618
false
null
package days import util.lazyAllPossiblePairs import util.toInt class Day2 : Day(2) { override fun partOne(): Int { val counts = inputList.map { toMatchSummary(it) }.fold(Pair(0, 0)) { totals, summary -> Pair(totals.first + summary.first.toInt(), totals.second + summary.second.toInt()) } return counts.first * counts.second } override fun partTwo(): String { val boxIdLength = inputList.first().length // validate an assumption that all boxIds are the same length if (!inputList.all { it.length == boxIdLength }) throw IllegalArgumentException("") return lazyAllPossiblePairs(inputList, inputList) .map { commonLetters(it.first, it.second) } .find { it.length == boxIdLength - 1 }!! // if the common letters string is one char shorter than the id length then the ids differ by exactly one letter } companion object { /** * Take a boxId (string of letters) and return a summary of its relevant internal matches * * Pair#first is true if boxId contains exactly 2 of a letter * Pair#second is true if boxId contains exactly 3 of a letter */ fun toMatchSummary(boxId: String): Pair<Boolean, Boolean> { val charCounts = boxId.associate { char -> Pair(char, boxId.count { it == char }) }.values return Pair(charCounts.any { it == 2 }, charCounts.any { it == 3 }) } /** * Take two boxIds and return the letters they have in common (same letter at same index) */ fun commonLetters(id1: String, id2: String): String { return id1.mapIndexed { index, char -> if (char == id2[index]) char else null }.filterNotNull().joinToString("") } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
1,832
aoc-2018
Creative Commons Zero v1.0 Universal
leetcode2/src/leetcode/construct-binary-tree-from-preorder-and-inorder-traversal.kt
hewking
68,515,222
false
null
package leetcode import leetcode.structure.TreeNode /** * 105. 从前序与中序遍历序列构造二叉树 * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ * Created by test * Date 2020/2/1 13:14 * Description * 根据一棵树的前序遍历与中序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / \ 9 20 / \ 15 7 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object ConstructBinaryTreeFromPreorderAndInOrderTraversal { /** * 思路: * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--22/ */ class Solution { fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { return buildTreeHelper(preorder,0,preorder.size,inorder,0,inorder.size) } fun buildTreeHelper(preorder: IntArray,pStart:Int,pEnd:Int,inorder: IntArray,iStart:Int,iEnd:Int):TreeNode? { if (pStart == pEnd) { return null } val rootValue = preorder[pStart] val root = TreeNode(rootValue) var rootIndex = 0 for (i in iStart until iEnd) { if (rootValue == inorder[i]) { rootIndex = i break } } val leftNum = rootIndex - iStart root.left = buildTreeHelper(preorder,pStart + 1,pStart + leftNum + 1,inorder,iStart,rootIndex) root.right = buildTreeHelper(preorder,pStart + leftNum + 1,pEnd,inorder,rootIndex + 1,iEnd) return root } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,006
leetcode
MIT License
Kotlin/src/main/kotlin/org/algorithm/problems/0049_unique_paths_iii.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
//Problem Statement // On a 2-dimensional grid, there are 4 types of squares: // // * 1 represents the starting square. There is exactly one starting square. // * 2 represents the ending square. There is exactly one ending square. // * 0 represents empty squares we can walk over. // * -1 represents obstacles that we cannot walk over. // // Return the number of 4-directional walks from the starting square to the ending // square, that walk over every non-obstacle square exactly once. package org.algorithm.problems class `0049_unique_paths_iii` { private val visited = mutableSetOf<Int>() private var result = 0 private var walkableSquares = 0 private val dir = intArrayOf(0, 1, 0, -1) fun uniquePathsIII(grid: Array<IntArray>): Int { var start_row = 0 var start_col = 0 for (i in 0 until grid.size) { for (j in 0 until grid[0].size) { if (grid[i][j] == 0) { walkableSquares += 1 } if (grid[i][j] == 1) { start_row = i start_col = j walkableSquares += 1 } } } dfs(grid, start_row, start_col) return result } private fun dfs(grid: Array<IntArray>, row: Int, col: Int) { val newKey = row * grid[0].size + col if (row < 0 || col < 0 || row >= grid.size || col >= grid[0].size || grid[row][col] == -1 || visited.contains(newKey)) { return } if (grid[row][col] == 2) { if (walkableSquares == visited.size) { result += 1 } return } visited.add(newKey) for (i in 0 until 4) { dfs(grid, row + dir[i], col + dir[(i + 1) % 4]) } visited.remove(newKey) } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
1,856
algorithms
MIT License
src/Day25.kt
felldo
572,233,925
false
{"Kotlin": 76496}
import kotlin.math.pow fun main() { fun snafuToDecimal(snafu: String): Long { var total = 0L for (i in snafu.indices) { val power = 5.0.pow(snafu.length - i.toDouble() - 1).toLong() total += when (snafu[i]) { '2' -> 2L * power '1' -> 1L * power '0' -> 0L '-' -> -1L * power '=' -> -2L * power else -> 0L } } return total } fun decimalToSnafu(decimal: Long): String { var remainder = decimal var snafu = "" var fives = 1L while (fives < decimal) { fives *= 5 } fives /= 5 while (fives >= 1) { val div = (remainder + fives / 2 * if (remainder > 0) 1 else -1) / fives snafu += when (div.toInt()) { 0 -> "0" 1 -> "1" 2 -> "2" -1 -> "-" -2 -> "=" else -> "" } remainder -= fives * div fives /= 5 } return snafu } fun part1(input: List<String>) = decimalToSnafu(input.sumOf { snafuToDecimal(it) }) val input = readInput("Day25") println(part1(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
1,287
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/aoc2023/Day5.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2023 import days.Day class Day5 : Day(2023, 5) { override fun partOne(): Any { return calculatePartOne(inputList) } fun calculatePartOne(inputList: List<String>): Long { val seeds = inputList.first().split("\\s+".toRegex()).drop(1).map { it.toLong() } val maps = mutableListOf<SourceToDestinationMap>() var currentMap = SourceToDestinationMap() inputList.drop(2).forEach {line -> if (line.isEmpty()) { maps.add(currentMap) currentMap = SourceToDestinationMap() } else if (line.first().isDigit()) { parseRangeAndAddToMap(line, currentMap) } } return seeds.minOf { seed -> maps.fold(seed) { current, map -> map.destinationForSource(current) } } } private fun parseRangeAndAddToMap(line: String, map: SourceToDestinationMap) { Regex("(\\d+) (\\d+) (\\d+)").matchEntire(line)?.destructured?.let { (destinationStart, sourceStart, length) -> map.addRange(LongRange(sourceStart.toLong(), sourceStart.toLong() + length.toLong()), destinationStart.toLong() - sourceStart.toLong()) } } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartTwo(inputList: List<String>): Long { val seedGroups = inputList.first().split("\\s+".toRegex()).drop(1).map { it.toLong() }.chunked(2) val maps = mutableListOf<SourceToDestinationMap>() var currentMap = SourceToDestinationMap() inputList.drop(2).forEach {line -> if (line.isEmpty()) { maps.add(currentMap) currentMap = SourceToDestinationMap() } else if (line.first().isDigit()) { parseRangeAndAddToMap(line, currentMap) } } var seedCount = 0L val result = seedGroups.minOf { seedGroup -> (seedGroup.first()..seedGroup.first() + seedGroup.last()).minOf {seed -> seedCount++ maps.fold(seed) { current, map -> map.destinationForSource(current) } } } println("Looked at $seedCount seeds") return result } private class SourceToDestinationMap { private val ranges = mutableListOf<Pair<LongRange,Long>>() fun addRange(range: LongRange, destinationOffset: Long) { ranges.add(Pair(range, destinationOffset)) } fun destinationForSource(source: Long): Long { ranges.forEach { range -> if (range.first.contains(source)) { return source + range.second } } return source } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,824
Advent-Of-Code
Creative Commons Zero v1.0 Universal
Problems/Algorithms/1473. Paint House III/PaintHouseIII.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun minCost(houses: IntArray, cost: Array<IntArray>, m: Int, n: Int, target: Int): Int { val dp = Array(m) { Array(n) { IntArray(target+1) { 1000001 } } } for (color in 1..n) { if (houses[0] == color) { dp[0][color-1][1] = 0 } else if (houses[0] == 0) { dp[0][color-1][1] = cost[0][color-1] } } for (house in 1..m-1) { for (color in 1..n) { for (neighbors in 1..minOf(target, house+1)) { if (houses[house] != 0 && color != houses[house]) { continue } var prevCost = 1000001 for (prevColor in 1..n) { if (prevColor != color) { prevCost = minOf(prevCost, dp[house-1][prevColor-1][neighbors-1]) } else { prevCost = minOf(prevCost, dp[house-1][prevColor-1][neighbors]) } } var currCost = 0 if (houses[house] == 0) { currCost = cost[house][color-1] } dp[house][color-1][neighbors] = currCost + prevCost } } } var ans = 1000001 for (color in 1..n) { ans = minOf(ans, dp[m-1][color-1][target]) } if (ans == 1000001) return -1 return ans } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,631
leet-code
MIT License
src/main/kotlin/adventofcode/NumberUtils.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
package adventofcode import java.math.BigInteger fun allCombinationsOf(num: List<Int>): Set<List<Int>> { return allCombinationsOf(num, arrayListOf()) } fun allCombinationsOf(num: IntRange): Set<List<Int>> { return allCombinationsOf(num.toList(), arrayListOf()) } private fun allCombinationsOf(num: List<Int>, builtList: ArrayList<Int>): Set<List<Int>> { val result = hashSetOf<List<Int>>() for (i in num.indices) { val value = num[i] if (!builtList.contains(value)) { val newList = ArrayList(builtList) newList.add(value) if (newList.size == num.size) { result.add(newList) } else { result.addAll(allCombinationsOf(num, newList)) } } } return result } fun BigInteger.max(other: BigInteger): BigInteger { return if (this >= other) this else other } data class RotatingNumber(val from: BigInteger, val to: BigInteger, val value: BigInteger = from, val diff: BigInteger = to - from + BigInteger.ONE) { constructor(from: Int, to: Int, value: Int = from) : this(from.toBigInteger(), to.toBigInteger(), value.toBigInteger(), (to - from + 1).toBigInteger()) fun reverse(): RotatingNumber { val diffToTail = to - value return RotatingNumber(from, to, from + diffToTail) } operator fun inc(): RotatingNumber { val newValue = if (value + BigInteger.ONE > to) from else value + BigInteger.ONE return RotatingNumber(from, to, newValue) } operator fun plus(numberToAdd: Int): RotatingNumber { return plus(numberToAdd.toBigInteger()) } operator fun plus(numberToAdd: BigInteger): RotatingNumber { var newValue = value + numberToAdd while (newValue > to) { newValue -= diff } while (newValue < from) { newValue += diff } return RotatingNumber(from, to, newValue) } operator fun dec(): RotatingNumber { val newValue = if (value - BigInteger.ONE < from) to else value - BigInteger.ONE return RotatingNumber(from, to, newValue) } } class MinValue() { private var value: BigInteger? = null fun next(next: Int): Boolean { return next(next.toBigInteger()) } fun next(next: Long): Boolean { return next(next.toBigInteger()) } fun next(next: BigInteger): Boolean { if (value == null || value!! > next) { value = next return true } return false } fun hasValue(): Boolean { return value != null } fun get(): BigInteger { return value!! } } class MaxValue() { private var value: BigInteger? = null private var related: Any? = null fun next(next: Int, related: Any? = null) { next(next.toBigInteger(), related) } fun next(next: Long, related: Any? = null) { next(next.toBigInteger(), related) } fun next(next: BigInteger, related: Any? = null) { if (value == null || value!! < next) { value = next this.related = related } } fun hasValue(): Boolean { return value != null } fun get(): BigInteger { return value!! } fun getRelated(): Any { return related!! } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
3,334
adventofcode2021
The Unlicense
src/main/aoc2018/Day13.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 import Direction import Pos import next class Day13(input: List<String>) { enum class Turn { LEFT, STRAIGHT, RIGHT } data class Path(val exits: List<Direction>) data class Cart(var pos: Pos, var comingFrom: Direction) { var removed = false private var nextTurn = Turn.LEFT fun move(map: Map<Pos, Path>) { val possibleDirections = map.getValue(pos).exits.filterNot { it == comingFrom } if (possibleDirections.size == 1) { moveInDirection(possibleDirections.first()) } else { when (nextTurn) { Turn.LEFT -> moveInDirection(comingFrom.turnRight()) Turn.STRAIGHT -> moveInDirection(comingFrom.opposite()) Turn.RIGHT -> moveInDirection(comingFrom.turnLeft()) } nextTurn = nextTurn.next() } } private fun moveInDirection(direction: Direction) { pos = Pos(pos.x + direction.dx, pos.y + direction.dy) comingFrom = direction.opposite() } } private val map: Map<Pos, Path> private val carts: List<Cart> init { val map = mutableMapOf<Pos, Path>() val carts = mutableListOf<Cart>() for (y in input.indices) { for (x in input[y].indices) { when (input[y][x]) { '-' -> map[Pos(x, y)] = Path(listOf(Direction.Left, Direction.Right)) '|' -> map[Pos(x, y)] = Path(listOf(Direction.Up, Direction.Down)) '+' -> map[Pos(x, y)] = Path(listOf(Direction.Up, Direction.Left, Direction.Down, Direction.Right)) '/' -> { if (y > 0 && listOf('|', '+').any { it == input[y - 1][x] }) { map[Pos(x, y)] = Path(listOf(Direction.Up, Direction.Left)) } else { map[Pos(x, y)] = Path(listOf(Direction.Down, Direction.Right)) } } '\\' -> { if (y > 0 && listOf('|', '+').any { it == input[y - 1][x] }) { map[Pos(x, y)] = Path(listOf(Direction.Up, Direction.Right)) } else { map[Pos(x, y)] = Path(listOf(Direction.Down, Direction.Left)) } } '^' -> { map[Pos(x, y)] = Path(listOf(Direction.Up, Direction.Down)) carts.add(Cart(Pos(x, y), Direction.Down)) } 'v' -> { map[Pos(x, y)] = Path(listOf(Direction.Up, Direction.Down)) carts.add(Cart(Pos(x, y), Direction.Up)) } '<' -> { map[Pos(x, y)] = Path(listOf(Direction.Left, Direction.Right)) carts.add(Cart(Pos(x, y), Direction.Right)) } '>' -> { map[Pos(x, y)] = Path(listOf(Direction.Left, Direction.Right)) carts.add(Cart(Pos(x, y), Direction.Left)) } } } } this.map = map this.carts = carts } private fun runUntilCollision(): String { var tick = 0 while (true) { tick++ carts.sortedWith(compareBy({ it.pos.y }, { it.pos.x })).forEach { cart -> cart.move(map) if (carts.filter { it.pos == cart.pos }.size > 1) { return "${cart.pos.x},${cart.pos.y}" } } } } private fun runUntilOnlyOneCartRemaining(): String { var tick = 0 while (true) { tick++ val liveCars = carts.filterNot { it.removed }.sortedWith(compareBy({ it.pos.y }, { it.pos.x })) liveCars.forEach { cart -> cart.move(map) val cartsOnSamePos = liveCars.filter { it.pos == cart.pos } if (cartsOnSamePos.size > 1) { cartsOnSamePos.forEach { it.removed = true } } } if (carts.filterNot { it.removed }.size == 1) { return liveCars.first { !it.removed }.pos.let { "${it.x},${it.y}" } } } } fun solvePart1(): String { return runUntilCollision() } fun solvePart2(): String { return runUntilOnlyOneCartRemaining() } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
4,636
aoc
MIT License
src/main/kotlin/com/rtarita/days/Day7.kt
RaphaelTarita
724,581,070
false
{"Kotlin": 64943}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import kotlinx.datetime.LocalDate object Day7 : AoCDay { override val day: LocalDate = day(7) private fun parse(input: String) = input.lineSequence() .map { val (hand, bid) = it.split(" ") hand to bid.toInt() } private fun typeValuePart1(hand: String): Int { val groups = hand.groupingBy { it } .eachCount() return when (groups.size) { 1 -> 7 2 -> if (groups.values.any { it == 4 }) 6 else 5 3 -> if (groups.values.any { it == 3 }) 4 else 3 4 -> 2 5 -> 1 else -> error("invalid hand with size ${hand.length}") } } private fun cardValuePart1(card: Char) = when (card) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> 11 'T' -> 10 in '2'..'9' -> card.digitToInt() else -> error("invalid card: $card") } private fun totalWinnings( input: String, typeValue: (String) -> Int, cardValue: (Char) -> Int ) = parse(input) .map { (hand, bid) -> Triple(typeValue(hand), hand.map { cardValue(it) }, bid) } .sortedWith { (typeValue1, cardValues1, _), (typeValue2, cardValues2, _) -> val typeComp = typeValue1 - typeValue2 if (typeComp == 0) { for (i in cardValues1.indices) { val cardComp = cardValues1[i] - cardValues2[i] if (cardComp != 0) return@sortedWith cardComp } 0 } else typeComp }.foldIndexed(0) { idx, acc, (_, _, bid) -> acc + (idx + 1) * bid } override fun executePart1(input: String) = totalWinnings(input, ::typeValuePart1, ::cardValuePart1) private fun typeValuePart2(hand: String): Int { val jokerTarget = hand.groupingBy { it } .eachCount() .filterKeys { it != 'J' } .maxByOrNull { (_, groupSize) -> groupSize } ?.key ?: 'A' val replacedHand = hand.replace('J', jokerTarget) return typeValuePart1(replacedHand) } private fun cardValuePart2(card: Char) = when (card) { 'A' -> 14 'K' -> 13 'Q' -> 12 'T' -> 11 in '2'..'9' -> card.digitToInt() + 1 'J' -> 2 else -> error("invalid card: $card") } override fun executePart2(input: String) = totalWinnings(input, ::typeValuePart2, ::cardValuePart2) }
0
Kotlin
0
0
4691126d970ab0d5034239949bd399c8692f3bb1
2,570
AoC-2023
Apache License 2.0
src/Day05.kt
felldo
572,233,925
false
{"Kotlin": 76496}
import java.util.LinkedList fun main() { fun getSupplyStacks() = listOf( LinkedList(listOf("D", "M", "S", "Z", "R", "F", "W", "N")), LinkedList(listOf("W", "P", "Q", "G", "S")), LinkedList(listOf("W", "R", "V", "Q", "F", "N", "J", "C")), LinkedList(listOf("F", "Z", "P", "C", "G", "D", "L")), LinkedList(listOf("T", "P", "S")), LinkedList(listOf("H", "D", "F", "W", "R", "L")), LinkedList(listOf("Z", "N", "D", "C")), LinkedList(listOf("W", "N", "R", "F", "V", "S", "J", "Q")), LinkedList(listOf("R", "M", "S", "G", "Z", "W", "Y")), ) val testInput = readInput("Day05") val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") val part1List = getSupplyStacks() testInput.map { regex.find(it)!! } .map { val (amount, from, to) = it.destructured; Triple(amount.toInt(), from.toInt(), to.toInt()) } .forEach { (amount, from, to) -> val fromList = part1List[from - 1] val toList = part1List[to - 1] repeat(amount) { val removed = fromList.removeLast() toList.addLast(removed) } } //Part 1 part1List.joinToString("") { it.last }.also(::println) val part2List = getSupplyStacks() testInput.map { regex.find(it)!! } .map { val (amount, from, to) = it.destructured; Triple(amount.toInt(), from.toInt(), to.toInt()) } .forEach { (amount, from, to) -> val fromList = part2List[from - 1] val toList = part2List[to - 1] fromList.takeLast(amount).forEach { toList.addLast(it) } repeat(amount) { fromList.removeLast() } } //Part 2 part2List.joinToString("") { it.last }.also(::println) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
1,805
advent-of-code-kotlin-2022
Apache License 2.0
src/day02/Day02.kt
jpveilleux
573,221,738
false
{"Kotlin": 42252}
package day02 import readInput fun main() { // Opponent // ----------------- // A = Rock // B = Paper // C = Scissors // Player // ----------------- // X = Rock = 1 // Y = Paper = 2 // Z = Scissors = 3 val myMoveScores = mapOf( "X" to 1, "Y" to 2, "Z" to 3 ) // Outcome Scores // ----------------- // Win = 6 // Draw = 3 // Lost = 0 val outcomes = mapOf( "WIN" to 6, "DRAW" to 3, "LOSE" to 0 ) val oppMoves = mapOf( "rock" to "A", "paper" to "B", "scissors" to "C" ) val myMoves = mapOf( "rock" to "X", "paper" to "Y", "scissors" to "Z" ) val shouldWhat = mapOf( "LOSE" to "X", "DRAW" to "Y", "WIN" to "Z" ) val testInputFileName = "Day02_test"; val inputFileName = "Day02"; val testInput = readInput(testInputFileName) val input = readInput(inputFileName) fun part1(input: List<String>): Int { return input.sumOf { val oppMove = it.substring(0..0); val shouldDoMove = it.substring(2..2); when (oppMove) { oppMoves["rock"] -> { when (shouldDoMove) { shouldWhat["DRAW"] -> { outcomes["DRAW"]!! + myMoveScores[myMoves["rock"]]!!; } shouldWhat["WIN"] -> { outcomes["WIN"]!! + myMoveScores[myMoves["paper"]]!!; } shouldWhat["LOSE"] -> { outcomes["LOSE"]!! + myMoveScores[myMoves["scissors"]]!!; } else -> 0 } } oppMoves["paper"] -> { when (shouldDoMove) { shouldWhat["DRAW"] -> { outcomes["DRAW"]!! + myMoveScores[myMoves["paper"]]!!; } shouldWhat["WIN"] -> { outcomes["WIN"]!! + myMoveScores[myMoves["scissors"]]!!; } shouldWhat["LOSE"] -> { outcomes["LOSE"]!! + myMoveScores[myMoves["rock"]]!!; } else -> 0 } } oppMoves["scissors"] -> { when (shouldDoMove) { shouldWhat["DRAW"] -> { outcomes["DRAW"]!! + myMoveScores[myMoves["scissors"]]!!; } shouldWhat["WIN"] -> { outcomes["WIN"]!! + myMoveScores[myMoves["rock"]]!!; } shouldWhat["LOSE"] -> { outcomes["LOSE"]!! + myMoveScores[myMoves["paper"]]!!; } else -> 0 } } else -> 0 } } } println(part1(input)); fun part2(input: List<String>) { } }
0
Kotlin
0
0
5ece22f84f2373272b26d77f92c92cf9c9e5f4df
3,213
jpadventofcode2022
Apache License 2.0
src/main/kotlin/year2023/Day09.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2023 class Day09 { fun part1(input: String) = solve(parseInput(input, false)) fun part2(input: String) = solve(parseInput(input, true)) fun parseInput(input: String, reverse: Boolean) = input.lines() .map { line -> line.split(' ').map { num -> num.toLong() } .let { if (reverse) it.reversed() else it } .toMutableList() }.toMutableList() fun calculateNextRow(row: List<Long>): MutableList<Long> { return buildList { row.indices.drop(1).forEach { idx -> add(row[idx] - row[idx - 1]) } }.toMutableList() } fun solve(series: MutableList<MutableList<Long>>): Long { return series.map { line -> val rowList = mutableListOf<MutableList<Long>>() var row = line rowList.add(row) while (row.hasNonZeroes()) { val nextRow = calculateNextRow(row) rowList.add(nextRow) row = nextRow } rowList.indices.drop(1).reversed().forEach { idx -> rowList[idx - 1].add(rowList[idx - 1].last() + rowList[idx].last()) } rowList[0].last() }.sum() } fun List<Long>.hasNonZeroes() = any { it != 0L } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,318
aoc-2022
Apache License 2.0
src/day01/Day01.kt
Puju2496
576,611,911
false
{"Kotlin": 46156}
package day01 import readInput fun main() { // test if implementation meets criteria from the description, like: val input = readInput("src/day01", "Day01") val elfs = part1(input) part2(elfs) } private fun part1(input: List<String>): List<Int> { var sum = 0 val elfs = mutableListOf<Int>() var max = 0 input.forEach { if (it == "" || input.indexOf(it) == input.size - 1) { elfs.add(sum) if (sum > max) max = sum sum = 0 } else sum += it.toInt() } println("max: $max - index: ${elfs.indexOf(max) + 1}") return elfs } private fun part2(elfs: List<Int>) { val max: Int = elfs.max() var max2 = 0 var max3 = 0 elfs.forEach { if (it > max2 && it < max) max2 = it } elfs.forEach { if (it > max3 && it < max2) max3 = it } println("max2: $max2 && max3: $max3") println("${max + max2 + max3}") }
0
Kotlin
0
0
e04f89c67f6170441651a1fe2bd1f2448a2cf64e
1,003
advent-of-code-2022
Apache License 2.0
src/com/ajithkumar/aoc2022/Day04.kt
ajithkumar
574,372,025
false
{"Kotlin": 21950}
package com.ajithkumar.aoc2022 import com.ajithkumar.utils.* import java.util.stream.IntStream import kotlin.streams.toList fun main() { fun stringRangeToSet(stringRange: String): Set<Int> { val rangeArr = stringRange.split("-").map(String::toInt) val result = IntStream.rangeClosed(rangeArr[0], rangeArr[1]).toList().toSet() // println(result) return result } fun part1(input: List<String>): Int { val result = input.map { it.split(",") } .map { it.map { stringRange -> stringRangeToSet(stringRange) } } .count { (it[0].containsAll(it[1]) || it[1].containsAll(it[0])) } return result } fun part2(input: List<String>): Int { val result = input.map { it.split(",") } .map { it.map { stringRange -> stringRangeToSet(stringRange) } } .count { it[0].intersect(it[1]).isNotEmpty() } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val testResult1 = part1(testInput) val testResult2 = part2(testInput) println(testResult1) println(testResult2) check(testResult1 == 2) check(testResult2 == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f95b8d1c3c8a67576eb76058a1df5b78af47a29c
1,331
advent-of-code-kotlin-template
Apache License 2.0
src/test/kotlin/be/brammeerten/y2022/Day24Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.C import be.brammeerten.gcd import be.brammeerten.readFile import be.brammeerten.toCharList import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import java.util.* class Day24Test { val DIRECTIONS = listOf(C(0, 0), C.LEFT, C.RIGHT, C.UP, C.DOWN) @Test fun `part 1a`() { val valley = readValley("2022/day24/exampleInput.txt") Assertions.assertThat(solve(valley, start = C(0, -1), stop = C(5, 4))).isEqualTo(18) } @Test fun `part 1b`() { val valley = readValley("2022/day24/input.txt") Assertions.assertThat(solve(valley, start = C(0, -1), stop = C(99, 35))).isEqualTo(230) } @Test fun `part 2a`() { val valley = readValley("2022/day24/exampleInput.txt") Assertions.assertThat(solveThereAndBackAgainAndBackAgain(valley, start = C(0, -1), stop = C(5, 4))).isEqualTo(54) } @Test fun `part 2b`() { val valley = readValley("2022/day24/input.txt") Assertions.assertThat(solveThereAndBackAgainAndBackAgain(valley, start = C(0, -1), stop = C(99, 35))).isEqualTo(713) } fun solve(valley: Valley, start: C, stop: C): Int { val blizzardStates = getBlizzardStates(valley) return solve(start, stop, startTime = 0, blizzardStates) } fun solveThereAndBackAgainAndBackAgain(valley: Valley, start: C, stop: C): Int { val blizzardStates = getBlizzardStates(valley) var time = solve(start, stop, startTime = 0, blizzardStates) time = solve(stop, start, startTime = time, blizzardStates) return solve(start, stop, startTime = time, blizzardStates) } fun solve(start: C, stop: C, startTime: Int, blizzardStates: Array<Array<Array<Boolean>>>): Int { val queue = LinkedList<Pair<Int, C>>() val visited = Array(blizzardStates.size) { HashSet<C>() } queue.add(startTime to start) visited[startTime % blizzardStates.size].add(start) while (!queue.isEmpty()) { val node = queue.remove() for (option in getOptions(node, blizzardStates, start, stop)) { val time = option.first % blizzardStates.size val newNode = option.second if (!visited[time].contains(newNode)) { queue.add(option) visited[time].add(newNode) if (newNode == stop) return node.first + 1 } } } throw IllegalStateException("Niet opgelost") } fun getOptions(cur: Pair<Int, C>, blizzardState: Array<Array<Array<Boolean>>>, start: C, stop: C): List<Pair<Int, C>> { val newTime = cur.first + 1 val newState = blizzardState[newTime % blizzardState.size] return DIRECTIONS .map { cur.second + it } .filter { it == start || it == stop || (it.x >= 0 && it.y >= 0 && it.x < newState[0].size && it.y < newState.size) } .filter { it == start || it == stop || !newState[it.y][it.x] } .map { newTime to it } } fun getBlizzardStates(valley: Valley): Array<Array<Array<Boolean>>> { val repeatsAfter = (valley.w * valley.h) / gcd(valley.w, valley.h) val state = Array(repeatsAfter) { Array(valley.h) { Array(valley.w) { false } } } var cur = valley for (time in 0 until repeatsAfter) { cur.blizzards.keys.forEach { pos -> state[time][pos.y][pos.x] = true } cur = cur.step() } return state } fun readValley(file: String): Valley { val rows = readFile(file).drop(1).dropLast(1) val h = rows.size val w = rows[0].length - 2 return Valley(w, h, rows.flatMapIndexed { y, row -> row.toCharList().drop(1).dropLast(1).mapIndexedNotNull { x, c -> when (c) { '>' -> C(x, y) to listOf(C(1, 0)) '<' -> C(x, y) to listOf(C(-1, 0)) '^' -> C(x, y) to listOf(C(0, -1)) 'v' -> C(x, y) to listOf(C(0, 1)) else -> null } } }.toMap()) } data class Valley(val w: Int, val h: Int, val blizzards: Map<C, List<C>>) { fun step(): Valley { val newBlizzards = hashMapOf<C, ArrayList<C>>() blizzards .flatMap { blizzard -> blizzard.value.map { blizzard.key to it } } .forEach { (pos, dir) -> var newPos = pos + dir newPos = C((newPos.x + w) % w, (newPos.y + h) % h) newBlizzards.putIfAbsent(newPos, arrayListOf()) newBlizzards[newPos]!!.add(dir) } return Valley(w, h, newBlizzards) } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
4,857
Advent-of-Code
MIT License
leetcode2/src/leetcode/n-th-tribonacci-number.kt
hewking
68,515,222
false
null
package leetcode /** * 1137. 第 N 个泰波那契数 * https://leetcode-cn.com/problems/n-th-tribonacci-number/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-10-23 10:40 * 泰波那契序列 Tn 定义如下:  T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2 给你整数 n,请返回第 n 个泰波那契数 Tn 的值。   示例 1: 输入:n = 4 输出:4 解释: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 示例 2: 输入:n = 25 输出:1389537   提示: 0 <= n <= 37 答案保证是一个 32 位整数,即 answer <= 2^31 - 1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-th-tribonacci-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object NThTribonacciNumber { class Solution { /** * 思路: * 递归,但是性能不好,采用循环 */ fun tribonacci(n: Int): Int { if ( n == 0) { return 0 } if (n == 1 || n == 2) { return 1 } return tribonacci(n - 1) + tribonacci(n - 2) + tribonacci(n - 3) } fun tribonacci2(n: Int): Int { if ( n == 0) { return 0 } if (n == 1 || n == 2) { return 1 } var a = 0 var b = 1 var c = 1 for (i in 3 .. n) { val tmp = a + b + c a = b b = c c = tmp } return c } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,700
leetcode
MIT License
src/day7/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day7 import day7.CMDLine.Command import day7.CMDLine.Command.CD import day7.CMDLine.Command.CD.Back import day7.CMDLine.Command.CD.Root import day7.CMDLine.Command.CD.To import day7.CMDLine.Command.LS import day7.CMDLine.Output import day7.CMDLine.Output.DIR import day7.CMDLine.Output.FileInfo import readInput sealed interface CMDLine { sealed interface Command : CMDLine { sealed interface CD : Command { object Root : CD object Back : CD data class To(val dir: String) : CD companion object { fun parse(command: String) = when (command) { "/" -> Root ".." -> Back else -> To(command) } } } object LS : Command companion object { fun parse(command: String) = when { command.startsWith("cd") -> CD.parse(command.drop(3)) command.startsWith("ls") -> LS else -> throw UnsupportedOperationException(command) } } } sealed interface Output : CMDLine { data class DIR(val name: String) : Output data class FileInfo(val name: String, val size: Int) : Output companion object { fun parse(line: String) = when { line.startsWith("dir") -> DIR(line.drop(4)) else -> FileInfo(line.substringAfter(" "), line.substringBefore(" ").toInt()) } } } companion object { fun parse(line: String): CMDLine { return when { line.startsWith("$") -> Command.parse(line.drop(2)) else -> Output.parse(line) } } } } class File( val name: String, private val fileSize: Int = 0, val children: MutableList<File> = mutableListOf() ) { val isRoot get() = name == "/" val isNotRoot get() = !isRoot val isDirectory get() = fileSize == 0 val size: Int get() = fileSize + children.sumOf { it.size } fun firstChildren(predicate: (File) -> Boolean): File = children.first(predicate) fun findChildren(name: String): File = firstChildren { it.name == name } fun add(dir: File) = children.add(dir) override fun toString(): String { val type = if (fileSize == 0) "dir" else "file" return "$type $name $size" } } class FileTree { private val stack: ArrayDeque<File> = ArrayDeque() init { stack.add(File("/")) } fun getRoot() = stack.first() fun goBack() { if (stack.size == 1) return stack.removeLast() } fun currentDir() = stack.last() fun goTo(name: String) { stack.add(currentDir().findChildren(name)) } fun addFile(file: FileInfo) { currentDir().add(File(file.name, file.size)) } fun addDir(dir: DIR) { currentDir().add(File(dir.name)) } fun goToRoot() { while (stack.lastOrNull()?.isNotRoot == true) goBack() } companion object { fun fromHistory(history: List<String>): FileTree { val tree = FileTree() tree.applyHistory(history) tree.goToRoot() return tree } } private fun applyHistory(input: List<String>) { for (cmd in input.map(CMDLine::parse)) { when (cmd) { is Command -> when (cmd) { is CD -> when (cmd) { Root -> goToRoot() Back -> goBack() is To -> goTo(cmd.dir) } is LS -> Unit // ignore } is Output -> when (cmd) { is FileInfo -> addFile(cmd) is DIR -> addDir(cmd) } } } } fun visitDirectories(action: (File) -> Unit) { return stack.visit(File::isDirectory, action) } private fun Iterable<File>.visit(predicate: (File) -> Boolean = { true }, action: (File) -> Unit) { for (file in this@visit) { if (predicate(file)) { action(file) file.children.visit(predicate, action) } } } } fun main() { fun part1(input: List<String>): Int { val tree = FileTree.fromHistory(input) return buildList { tree.visitDirectories { if (it.size < 100000) add(it) } }.sumOf { it.size } } fun part2(input: List<String>): Int { val tree = FileTree.fromHistory(input) return buildList { val usedSpace = tree.getRoot().size tree.visitDirectories { file -> if (70000000 - 30000000 - usedSpace + file.size > 0) { add(file) } } }.minByOrNull { it.size }?.size ?: -1 } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
5,048
AoC-2022
Apache License 2.0
src/Day05.kt
Misano9699
572,108,457
false
null
fun main() { // list of stacks var stacks: MutableList<MutableList<String>> = MutableList(9) { mutableListOf() } // list of moves (number of elements to move, source stack, destination stack) var moves: MutableList<List<Int>> = mutableListOf() fun reset() { // needs to be reset before every run. Easier than using stacks and moves as method parameters stacks = MutableList(9) { mutableListOf() } moves = mutableListOf() } fun parseStacks(line: String) { val row = MutableList(9) { "" } line.indices.forEach { if (line[it] in 'A'..'Z') { // every character is on 1,5,9 to 33 so a division by 4 should give the correct index in the list row.add(it / 4, line[it].toString()) } } row.indices.forEach { if (row[it] != "") stacks[it].add(row[it]) } } fun parseMoves(line: String) { val move = line.split(" ") // move (1) from (3) to (5) moves.add(listOf(move[1].toInt(), move[3].toInt(), move[5].toInt())) } fun createStacksAndDetermineMoves(input: List<String>) { var determineMoves = false input.forEach { line -> if (line == "") { // switch from parsing the stack to parsing the moves determineMoves = true } else { if (determineMoves) { parseMoves(line) } else { parseStacks(line) } } } // as the rows are build in reverse order, we need to reverse the rows of our stacks before we apply the moves stacks.forEach { it.reverse() } } fun moveOneCrateAtATimeFromSourceToDestination(numberOfCratesToMove: Int, source: Int, destination: Int) { (1..numberOfCratesToMove).forEach { _ -> val element = stacks[source - 1].removeLast() stacks[destination - 1].add(element) } } fun moveCratesAtOnceFromSourceToDestination(numberOfCratesToMove: Int, source: Int, destination: Int) { val elements = stacks[source - 1].takeLast(numberOfCratesToMove) // takeLast doesn't remove the taken elements, so we need to do that (1..numberOfCratesToMove).forEach { _ -> stacks[source - 1].removeLast() } stacks[destination - 1].addAll(elements) } fun retrieveTopElementsFromEachStack(): String = stacks.map { if (it.isEmpty()) "" else it.last() }.joinToString("") { it } fun part1(input: List<String>): String { reset() createStacksAndDetermineMoves(input) moves.forEach { moveOneCrateAtATimeFromSourceToDestination(it[0], it[1], it[2]) } return retrieveTopElementsFromEachStack() } fun part2(input: List<String>): String { reset() createStacksAndDetermineMoves(input) moves.forEach { moveCratesAtOnceFromSourceToDestination(it[0], it[1], it[2]) } return retrieveTopElementsFromEachStack() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val input = readInput("Day05") check(part1(testInput).also { println("Answer test input part1: $it") } == "CMZ") println("Answer part1: " + part1(input)) check(part2(testInput).also { println("Answer test input part2: $it") } == "MCD") println("Answer part2: " + part2(input)) }
0
Kotlin
0
0
adb8c5e5098fde01a4438eb2a437840922fb8ae6
3,489
advent-of-code-2022
Apache License 2.0
src/main/kotlin/tw/gasol/aoc/aoc2022/Day9.kt
Gasol
574,784,477
false
{"Kotlin": 70912, "Shell": 1291, "Makefile": 59}
package tw.gasol.aoc.aoc2022 import kotlin.math.absoluteValue typealias Position = Pair<Int, Int> class Day9 { enum class Direction { UP, DOWN, LEFT, RIGHT; companion object { fun fromString(str: String): Direction { return when (str) { "U" -> UP "D" -> DOWN "L" -> LEFT "R" -> RIGHT else -> throw IllegalArgumentException("Unknown direction: $str") } } } } fun part1(input: String): Int { val locations = mutableListOf<Position>() locations.add(0 to 0) // s var previousDirection: Direction? = null readMovements(input).forEach { movement -> val (direction, distance) = movement val last = locations.last() val (lastX, lastY) = last val (offsetX, offsetY) = when (direction) { Direction.UP -> 0 to 1 Direction.DOWN -> 0 to -1 Direction.LEFT -> -1 to 0 Direction.RIGHT -> 1 to 0 } val movedLocations = (1..distance).map { Position(lastX + (offsetX * it), lastY + (offsetY * it)) } if (previousDirection != null && previousDirection != direction) { locations.removeLast() } locations.addAll(movedLocations) previousDirection = direction } return locations.toSet().size - 1 } private fun readMovements(input: String): List<Pair<Direction, Int>> { val regex = "(\\w) (\\d+)".toRegex() return input.lines() .filterNot { it.isBlank() } .map { line -> val (direction, distance) = regex.matchEntire(line) ?.destructured ?: error("Invalid input line: $line") Pair(Direction.fromString(direction), distance.toInt()) } } fun part2(input: String): Int { val movements = readMovements(input) val rope = Rope(10) return rope.countTailVisited(movements) } class Rope(private val numKnots: Int) { fun countTailVisited(movements: List<Pair<Direction, Int>>): Int { val visited = mutableSetOf<Position>() for (movement in movements) { move(movement) { val tail = knots.last() visited.add(Position(tail.x, tail.y)) } } return visited.count() } private fun move(movement: Pair<Direction, Int>, onMoved: () -> Unit = {}) { val (direction, distance) = movement repeat(distance) { knots[0].move(direction) for (i in 1 until knots.size) { knots[i].follow(knots[i - 1]) } onMoved() } } data class Knot(var initX: Int, var initY: Int) { var x = initX private set var y = initY private set fun move(direction: Direction) { val (offsetX, offsetY) = when (direction) { Direction.UP -> 0 to 1 Direction.DOWN -> 0 to -1 Direction.LEFT -> -1 to 0 Direction.RIGHT -> 1 to 0 } x += offsetX y += offsetY } fun follow(front: Knot) { val diffX = front.x - x val diffY = front.y - y if (diffX.absoluteValue < 2 && diffY.absoluteValue < 2) { return } if (diffX == 0) { y += diffY / 2 } else if (diffX == 1) { x += 1 y += diffY / 2 } else if (diffX == -1) { x -= 1 y += diffY / 2 } else if (diffY == 1) { x += diffX / 2 y += 1 } else if (diffY == 0) { x += diffX / 2 } else if (diffY == -1) { x += diffX / 2 y -= 1 } else { x += diffX / 2 y += diffY / 2 } } override fun toString(): String { return "Knot($x, $y)" } } private val knots = buildList { repeat(numKnots) { add(Knot(0, 0)) } } } }
0
Kotlin
0
0
a14582ea15f1554803e63e5ba12e303be2879b8a
4,675
aoc2022
MIT License
src/challenges/Day02.kt
paralleldynamic
572,256,326
false
{"Kotlin": 15982}
package challenges import utils.readInput fun main() { fun part1(games: List<String>): Int = games .map { round -> when(round) { "A X" -> 4 "A Y" -> 8 "A Z" -> 3 "B X" -> 1 "B Y" -> 5 "B Z" -> 9 "C X" -> 7 "C Y" -> 2 "C Z" -> 6 else -> 0 } }.sum() fun part2(games: List<String>): Int = games .map { round -> when(round) { "A X" -> 3 "A Y" -> 4 "A Z" -> 8 "B X" -> 1 "B Y" -> 5 "B Z" -> 9 "C X" -> 2 "C Y" -> 6 "C Z" -> 7 else -> 0 } }.sum() val testGames = readInput("Day02_test") val games = readInput("Day02") // part 1 check(part1(testGames) == 15) println(part1(games)) // part 2 check(part2(testGames) == 12) println(part2(games)) }
0
Kotlin
0
0
ad32a9609b5ce51ac28225507f77618482710424
1,085
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2021/Day05HydrothermalVenture.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput import kotlin.math.max import kotlin.math.min class Day05HydrothermalVenture(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val lines by lazy { input.lines().map { it.split(" -> ").map(Point::invoke) }.map(::Line) } override fun partOne() = lines .filter { it.isHorizontal() || it.isVertical() } .flatMap(Line::getCoveredPoints) .groupingBy { it } .eachCount() .count { it.value > 1 } override fun partTwo() = lines .flatMap(Line::getCoveredPoints) .groupingBy { it } .eachCount() .count { it.value > 1 } companion object { private data class Point( val x: Int, val y: Int ) { companion object { operator fun invoke(coordinates: String): Point { val (x, y) = coordinates.split(",").map(String::toInt) return Point(x, y) } } } private data class Line( val start: Point, val end: Point ) { constructor(points: List<Point>) : this(points.first(), points.last()) fun isHorizontal() = start.y == end.y fun isVertical() = start.x == end.x fun getCoveredPoints() = when { isHorizontal() -> IntRange(min(start.x, end.x), max(start.x, end.x)).map { Point(it, start.y) } isVertical() -> IntRange(min(start.y, end.y), max(start.y, end.y)).map { Point(start.x, it) } else -> { val left = if (start.x < end.x) start else end val right = listOf(start, end).minus(left).first() val gradient = if (left.y < right.y) 1 else -1 (left.x..right.x).map { Point(it, gradient * (it - left.x) + left.y) } } } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,997
AdventOfCode
MIT License
src/main/kotlin/DailyTemperatures.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * Given an array of integers temperatures represents the daily temperatures, * return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. * If there is no future day for which this is possible, keep answer[i] == 0 instead. * * * * Example 1: * * Input: temperatures = [73,74,75,71,69,72,76,73] * Output: [1,1,4,2,1,1,0,0] * Example 2: * * Input: temperatures = [30,40,50,60] * Output: [1,1,1,0] * Example 3: * * Input: temperatures = [30,60,90] * Output: [1,1,0] * * * Constraints: * * 1 <= temperatures.length <= 10^5 * 30 <= temperatures[i] <= 100 * @see <a href="https://leetcode.com/problems/daily-temperatures/">LeetCode</a> */ fun dailyTemperatures(temperatures: IntArray): IntArray { val stack = ArrayDeque<Pair<Int, Int>>() val answer = IntArray(temperatures.size) for (index in (0 until temperatures.size).reversed()) { while (stack.isNotEmpty() && temperatures[index] >= stack.last().first) { stack.removeLast() } answer[index] = if (stack.isEmpty()) 0 else stack.last().second - index stack.add(Pair(temperatures[index], index)) } return answer }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
1,223
kotlin-codes
Apache License 2.0
advent-of-code-2020/src/test/java/aoc/Day7HandyHaversacks.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test class Day7HandyHaversacks { @Test fun silverTest() { val parsed = parseBagPolicy(testInput) assertThat(countAllPossibleParentsOfShinyGoldBag(parsed)).isEqualTo(4) } @Test fun silver() { val parsed = parseBagPolicy(input) assertThat(countAllPossibleParentsOfShinyGoldBag(parsed)).isEqualTo(348) } private fun countAllPossibleParentsOfShinyGoldBag( policies: List<BagPolicy>, ): Int { val childToParent = mapChildrenToParents(policies) fun withAllParents(childName: String): Set<String> { val parents = childToParent.getOrDefault(childName, emptySet()) .flatMap { withAllParents(it) } .toSet() return parents.plus(childName) } return withAllParents("shiny gold").minus("shiny gold").count() } /** * Builds a map containing possible parents of each child. */ private fun mapChildrenToParents(policies: List<BagPolicy>): Map<String, Set<String>> { return mutableMapOf<String, MutableSet<String>>().apply { policies.forEach { bagPolicy -> bagPolicy.children.forEach { innerBag -> getOrPut(innerBag.name) { mutableSetOf() } .add(bagPolicy.name) } } }.toMap() } @Test fun goldTest() { val parsed = parseBagPolicy(testInput) assertThat(countChildrenOfShinyBag(parsed)).isEqualTo(32) } @Test fun goldTest2() { val parsed = parseBagPolicy(testInput2) assertThat(countChildrenOfShinyBag(parsed)).isEqualTo(126) } @Test fun gold() { val parsed = parseBagPolicy(input) assertThat(countChildrenOfShinyBag(parsed)).isEqualTo(18885) } data class BagPolicy( val name: String, val children: List<InnerBag>, ) data class InnerBag( val name: String, val amount: Int, ) /** Counts all children of a shiny gold bag recursively */ private fun countChildrenOfShinyBag(policies: List<BagPolicy>): Int { val bagToContents: Map<String, List<InnerBag>> = policies.associateBy( keySelector = { it.name }, valueTransform = { it.children } ) fun countAllChildrenOf(parent: String): Int { val innerBags = bagToContents.getValue(parent) return innerBags.sumBy { (name, amount) -> // bag itself, plus all its children times amount of bags (1 + countAllChildrenOf(name)) * amount } } return countAllChildrenOf("shiny gold") } private fun parseBagPolicy(input: String): List<BagPolicy> { return input.lines() .map { it .replace(" bags", "") .replace(" bag", "") .replace(".", "") } .map { line -> val name = line.substringBefore(" contain ") val children: List<InnerBag> = when { line.endsWith("no other") -> emptyList() else -> line.substringAfter(" contain ") .split(", ") .map { child -> InnerBag( child.substringAfter(" "), child.substringBefore(" ").toInt(), ) } } BagPolicy(name, children) } } private val testInput = """ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. """.trimIndent() private val testInput2 = """ shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags. """.trimIndent() private val input = """ bright indigo bags contain 4 shiny turquoise bags, 3 wavy yellow bags. dotted turquoise bags contain 3 vibrant salmon bags, 2 dotted maroon bags, 1 bright beige bag, 1 drab white bag. vibrant fuchsia bags contain 4 dark salmon bags. muted cyan bags contain 2 light gold bags, 5 mirrored salmon bags, 4 plaid blue bags. dotted tomato bags contain 3 vibrant gold bags, 4 faded blue bags. mirrored black bags contain 5 vibrant beige bags, 3 plaid blue bags. dim yellow bags contain 1 clear tan bag, 3 dim red bags. plaid lavender bags contain 2 dim coral bags, 4 mirrored maroon bags, 5 wavy lavender bags. drab magenta bags contain 3 muted yellow bags, 5 bright turquoise bags. mirrored silver bags contain 5 faded tan bags, 4 drab salmon bags, 3 clear chartreuse bags. drab lavender bags contain 3 plaid white bags, 5 pale salmon bags, 4 dull salmon bags. wavy cyan bags contain 4 dim bronze bags, 5 muted olive bags, 5 plaid gold bags, 4 muted red bags. bright fuchsia bags contain 4 faded orange bags, 4 posh teal bags. muted indigo bags contain 4 vibrant silver bags, 1 wavy tomato bag. pale olive bags contain 1 clear bronze bag, 3 posh black bags, 2 dim blue bags. dull crimson bags contain 4 dull tomato bags, 5 wavy green bags, 2 vibrant blue bags, 3 pale brown bags. dim salmon bags contain 2 bright black bags, 3 drab salmon bags, 5 vibrant beige bags. clear orange bags contain 4 dim coral bags, 4 light chartreuse bags, 5 wavy brown bags, 2 drab yellow bags. bright silver bags contain 3 dotted plum bags, 4 shiny salmon bags, 2 drab magenta bags. light turquoise bags contain 5 striped beige bags, 5 muted black bags, 1 striped maroon bag. light lavender bags contain 3 vibrant coral bags, 3 mirrored crimson bags. dull magenta bags contain 4 mirrored gray bags, 5 faded lime bags, 2 dotted green bags, 2 striped olive bags. shiny maroon bags contain 3 plaid aqua bags, 1 pale plum bag, 5 plaid salmon bags. wavy gray bags contain 5 pale cyan bags, 1 pale gold bag, 2 pale salmon bags. dark gray bags contain 2 pale gold bags, 3 muted orange bags, 1 dim maroon bag. dim beige bags contain 1 dark yellow bag. dull yellow bags contain 4 pale chartreuse bags. light aqua bags contain 3 plaid indigo bags, 5 dull black bags. vibrant silver bags contain 1 posh beige bag, 2 dim cyan bags, 4 light violet bags, 2 dark tan bags. striped aqua bags contain 4 dim olive bags, 4 vibrant magenta bags, 5 pale cyan bags. wavy beige bags contain 5 dim red bags, 2 dotted crimson bags, 1 muted orange bag. drab orange bags contain 3 dotted red bags, 1 drab yellow bag, 4 clear tan bags, 1 vibrant chartreuse bag. mirrored turquoise bags contain 4 striped yellow bags, 1 dark yellow bag. posh gold bags contain 2 clear maroon bags, 2 drab black bags. posh orange bags contain 3 dark red bags, 1 dull brown bag, 1 dark green bag. dim lavender bags contain 2 drab gray bags, 2 shiny brown bags, 2 dull tomato bags, 4 light teal bags. muted lavender bags contain 1 striped black bag, 1 vibrant brown bag, 1 wavy yellow bag. dotted aqua bags contain 2 muted yellow bags. pale aqua bags contain 5 striped blue bags. muted silver bags contain 3 pale plum bags, 4 mirrored aqua bags. pale teal bags contain 2 shiny beige bags. dim coral bags contain 2 vibrant gold bags. faded plum bags contain 3 vibrant yellow bags, 2 bright teal bags, 5 light magenta bags. light coral bags contain 2 vibrant brown bags, 2 light crimson bags, 2 dotted bronze bags. bright plum bags contain 3 wavy olive bags. vibrant yellow bags contain 4 muted olive bags, 1 dull tomato bag, 3 bright coral bags. muted fuchsia bags contain 3 clear maroon bags, 1 striped aqua bag, 1 pale brown bag. dull olive bags contain 4 muted tomato bags, 1 clear silver bag. wavy brown bags contain 2 dim cyan bags, 3 dim green bags, 3 faded chartreuse bags. bright lavender bags contain 5 dim lavender bags, 5 shiny turquoise bags, 4 clear turquoise bags. dim maroon bags contain 5 shiny coral bags, 5 pale white bags, 4 dim cyan bags. vibrant gold bags contain 2 posh crimson bags, 3 striped olive bags. dotted gold bags contain 5 faded teal bags. dull red bags contain 5 bright beige bags. striped purple bags contain 1 shiny brown bag, 1 light orange bag. dotted yellow bags contain 2 striped aqua bags, 2 muted olive bags, 4 shiny orange bags. plaid red bags contain 4 clear teal bags, 4 vibrant indigo bags, 2 faded tan bags. striped magenta bags contain 2 striped chartreuse bags, 5 drab red bags. dim aqua bags contain 1 shiny coral bag, 2 faded teal bags, 2 plaid cyan bags, 1 plaid salmon bag. vibrant tan bags contain 3 shiny silver bags, 4 faded tan bags. clear red bags contain 4 dotted gold bags. faded tan bags contain 4 plaid salmon bags, 4 plaid violet bags. faded maroon bags contain 3 mirrored turquoise bags, 1 dim black bag, 5 posh lavender bags. striped yellow bags contain 2 plaid bronze bags. light teal bags contain 3 clear blue bags, 5 pale maroon bags, 4 plaid white bags, 5 wavy tomato bags. dotted indigo bags contain 4 dim aqua bags, 4 light coral bags, 1 posh tan bag, 1 mirrored gold bag. clear maroon bags contain 2 drab red bags. light yellow bags contain 5 wavy coral bags, 2 light chartreuse bags, 5 dull lime bags. faded blue bags contain 4 vibrant yellow bags. dim purple bags contain 3 clear plum bags, 2 plaid green bags. plaid indigo bags contain 2 faded lime bags, 4 mirrored green bags, 5 dull plum bags. posh salmon bags contain 3 vibrant violet bags. dim olive bags contain 5 drab green bags. wavy violet bags contain 3 light chartreuse bags, 5 muted olive bags. dark magenta bags contain 3 wavy red bags. posh violet bags contain 5 faded silver bags, 4 wavy tomato bags, 3 mirrored salmon bags. posh yellow bags contain 3 plaid bronze bags. dotted lavender bags contain 2 plaid gray bags, 5 dull beige bags, 2 vibrant chartreuse bags, 3 muted chartreuse bags. mirrored aqua bags contain 1 striped coral bag, 5 plaid violet bags, 2 bright coral bags, 5 pale orange bags. clear lavender bags contain 2 posh chartreuse bags. vibrant plum bags contain 5 wavy tomato bags, 3 posh tomato bags, 1 striped chartreuse bag, 1 dim cyan bag. faded red bags contain 1 bright green bag. muted chartreuse bags contain 2 faded tan bags, 3 shiny violet bags. dotted lime bags contain 3 light yellow bags, 4 bright coral bags. vibrant turquoise bags contain 1 clear black bag. dull fuchsia bags contain 1 wavy maroon bag, 1 posh black bag, 5 light magenta bags, 1 dotted tomato bag. vibrant tomato bags contain 4 striped chartreuse bags. shiny chartreuse bags contain 4 faded gray bags, 4 dark tan bags, 5 posh crimson bags. mirrored white bags contain 1 light blue bag, 2 muted gold bags. light magenta bags contain no other bags. dark fuchsia bags contain 2 shiny coral bags, 3 pale tomato bags. mirrored maroon bags contain 1 dim indigo bag. plaid black bags contain 3 muted tomato bags. dotted magenta bags contain 5 dark aqua bags. shiny bronze bags contain 3 dim green bags. drab violet bags contain 4 dotted bronze bags. dark cyan bags contain no other bags. dim violet bags contain 3 mirrored salmon bags, 2 shiny plum bags, 3 plaid salmon bags. plaid teal bags contain 5 dull indigo bags. dull teal bags contain 4 posh teal bags, 3 plaid plum bags, 3 dim lavender bags. plaid turquoise bags contain 4 drab yellow bags, 1 vibrant lavender bag, 2 vibrant yellow bags, 5 light violet bags. posh fuchsia bags contain 4 vibrant gold bags, 4 shiny silver bags. clear purple bags contain 1 faded tomato bag. mirrored coral bags contain 1 striped black bag, 3 plaid chartreuse bags. bright beige bags contain 4 faded lavender bags, 1 faded teal bag, 3 dark red bags, 1 pale maroon bag. bright yellow bags contain 4 dark orange bags, 2 muted tomato bags. dark chartreuse bags contain 4 mirrored gold bags, 4 dark tan bags, 5 posh yellow bags. posh green bags contain 4 bright bronze bags, 3 faded aqua bags, 1 shiny lime bag, 2 dotted magenta bags. posh brown bags contain 3 drab gray bags. pale lavender bags contain 2 pale gold bags, 4 dark orange bags. dim bronze bags contain 4 dull white bags. bright teal bags contain 1 mirrored gray bag, 4 faded indigo bags, 2 dim cyan bags, 1 posh plum bag. striped orange bags contain 4 vibrant plum bags, 4 shiny cyan bags, 5 pale beige bags, 4 dim beige bags. vibrant cyan bags contain 3 posh plum bags, 1 bright teal bag. drab gold bags contain 1 wavy orange bag. shiny salmon bags contain 5 faded indigo bags, 3 bright turquoise bags, 3 pale violet bags, 4 dotted coral bags. drab blue bags contain 4 posh fuchsia bags. dark gold bags contain 1 clear black bag, 1 dark chartreuse bag, 1 faded lime bag, 2 bright olive bags. striped gray bags contain 4 bright coral bags, 4 striped coral bags, 1 muted gold bag. bright gold bags contain 2 plaid fuchsia bags, 5 striped olive bags, 2 mirrored tomato bags, 5 muted tomato bags. wavy lavender bags contain 1 pale violet bag, 1 dotted gray bag. wavy orange bags contain 3 bright fuchsia bags, 4 posh yellow bags, 3 vibrant brown bags, 5 posh beige bags. bright bronze bags contain 3 pale blue bags, 2 shiny cyan bags, 2 vibrant tan bags, 5 posh crimson bags. dotted teal bags contain 1 plaid indigo bag, 4 posh salmon bags. muted salmon bags contain 3 wavy maroon bags, 2 dotted olive bags. dotted crimson bags contain 2 dotted bronze bags, 1 bright yellow bag, 2 dark cyan bags, 5 clear salmon bags. striped tan bags contain 2 posh violet bags, 5 dark silver bags, 5 light teal bags. pale maroon bags contain 1 dark cyan bag, 4 faded indigo bags. muted crimson bags contain 2 faded cyan bags. dull tomato bags contain 4 muted teal bags, 5 posh plum bags. light crimson bags contain 3 light gold bags. bright orange bags contain 5 plaid indigo bags, 5 plaid beige bags, 1 light teal bag. posh red bags contain 4 shiny plum bags. light bronze bags contain 5 dark green bags, 4 shiny silver bags. dull violet bags contain 1 mirrored gray bag, 4 shiny crimson bags. posh silver bags contain 2 dull maroon bags. light salmon bags contain 3 dim plum bags. vibrant olive bags contain 2 faded aqua bags, 4 faded blue bags. pale orange bags contain 5 bright coral bags, 5 dark cyan bags, 2 dull plum bags, 4 dim cyan bags. vibrant green bags contain 5 dark orange bags, 1 drab yellow bag, 3 dotted plum bags. dull lavender bags contain 2 dark tomato bags. dim tan bags contain 1 muted teal bag, 4 dull white bags, 1 shiny gold bag. plaid white bags contain 3 faded silver bags. pale lime bags contain 4 plaid bronze bags, 1 posh white bag. mirrored crimson bags contain 4 dim tan bags, 3 vibrant turquoise bags, 1 faded lime bag, 5 striped yellow bags. muted bronze bags contain 3 plaid green bags, 4 drab yellow bags, 5 plaid purple bags. clear black bags contain 4 dark yellow bags. drab plum bags contain 5 light cyan bags. plaid yellow bags contain 1 bright silver bag, 1 light bronze bag. bright green bags contain 3 posh gray bags, 1 mirrored black bag. wavy lime bags contain 1 pale white bag, 2 dim orange bags, 4 dull bronze bags. striped turquoise bags contain 2 drab lavender bags. dotted chartreuse bags contain 1 posh violet bag, 2 mirrored aqua bags. faded olive bags contain 1 bright bronze bag, 3 mirrored tan bags, 3 vibrant silver bags. dull green bags contain 4 plaid olive bags. bright salmon bags contain 5 mirrored salmon bags, 4 muted teal bags, 1 vibrant yellow bag, 3 bright magenta bags. light plum bags contain 4 dull turquoise bags, 3 dim bronze bags. mirrored red bags contain 2 dull blue bags. dark maroon bags contain 4 clear yellow bags. pale yellow bags contain 1 dull crimson bag, 1 clear black bag, 5 shiny lime bags. striped lime bags contain 1 bright aqua bag, 1 faded lime bag, 2 posh coral bags. drab tomato bags contain 3 shiny aqua bags, 2 striped crimson bags, 5 bright coral bags, 3 dull lime bags. striped silver bags contain 3 dim beige bags, 2 bright tomato bags. posh crimson bags contain 5 plaid bronze bags, 5 muted teal bags, 1 dark cyan bag. muted olive bags contain 5 muted gold bags, 1 bright coral bag, 4 muted tomato bags, 2 pale maroon bags. drab gray bags contain 2 shiny silver bags, 5 plaid cyan bags. dark tomato bags contain 3 bright tomato bags, 3 drab yellow bags. pale beige bags contain 5 striped blue bags, 5 plaid tomato bags, 2 mirrored indigo bags. striped bronze bags contain 3 wavy tomato bags, 1 dark brown bag, 4 plaid salmon bags, 5 dark magenta bags. dotted green bags contain 3 faded orange bags, 1 striped olive bag, 2 dark cyan bags, 2 bright coral bags. dull lime bags contain 3 wavy black bags, 4 shiny tan bags, 2 clear crimson bags, 1 dark cyan bag. light cyan bags contain 5 light violet bags, 5 posh black bags. bright crimson bags contain 1 plaid tomato bag, 5 faded green bags, 2 posh chartreuse bags. bright magenta bags contain 3 wavy red bags, 4 bright lime bags. shiny orange bags contain 4 light blue bags, 3 dotted green bags, 3 shiny brown bags. dim tomato bags contain 4 vibrant green bags. drab teal bags contain 4 dull tomato bags, 4 shiny coral bags, 4 pale silver bags. mirrored blue bags contain 1 wavy chartreuse bag, 1 dull plum bag, 1 plaid bronze bag. shiny gold bags contain 1 pale maroon bag, 3 plaid blue bags, 5 dull tan bags. clear bronze bags contain 1 pale coral bag, 1 light yellow bag. wavy bronze bags contain 5 posh turquoise bags, 4 mirrored tan bags. drab chartreuse bags contain 4 dark lavender bags, 4 clear silver bags, 4 dotted tan bags, 5 posh silver bags. vibrant orange bags contain 4 bright black bags. shiny indigo bags contain 5 striped coral bags. clear beige bags contain 4 striped olive bags, 5 clear indigo bags, 3 dark cyan bags. plaid brown bags contain 3 mirrored bronze bags. light olive bags contain 5 dark white bags, 1 plaid red bag. shiny fuchsia bags contain 4 dark cyan bags, 3 pale chartreuse bags, 5 light fuchsia bags. bright black bags contain 5 plaid white bags, 3 plaid cyan bags. mirrored beige bags contain 1 dim plum bag. light black bags contain 3 bright silver bags, 3 wavy chartreuse bags, 4 bright chartreuse bags. vibrant coral bags contain 1 faded tomato bag, 3 striped coral bags. muted beige bags contain 4 striped olive bags. dotted black bags contain 2 muted crimson bags, 4 plaid olive bags. pale chartreuse bags contain 2 muted beige bags. wavy maroon bags contain 4 vibrant cyan bags, 5 posh white bags, 2 shiny black bags. faded brown bags contain 2 mirrored violet bags, 4 wavy silver bags. dotted white bags contain 1 mirrored purple bag. striped salmon bags contain 2 posh tomato bags, 1 muted silver bag, 3 dull violet bags, 4 mirrored plum bags. striped red bags contain 2 posh bronze bags. clear teal bags contain 4 vibrant aqua bags, 1 plaid lime bag, 3 bright lime bags, 1 posh beige bag. mirrored cyan bags contain 5 light green bags. muted teal bags contain no other bags. drab bronze bags contain 4 dim salmon bags, 1 shiny violet bag, 1 dotted white bag, 3 wavy yellow bags. pale fuchsia bags contain 4 plaid magenta bags. mirrored tomato bags contain 1 shiny gray bag, 5 dull lime bags, 5 shiny turquoise bags, 1 clear crimson bag. clear cyan bags contain 4 mirrored tomato bags, 5 bright lime bags. clear gray bags contain 4 faded plum bags, 4 posh yellow bags, 2 clear violet bags, 4 plaid red bags. dotted brown bags contain 2 dotted maroon bags. dotted salmon bags contain 5 striped bronze bags, 1 shiny bronze bag, 5 light olive bags, 2 striped magenta bags. dark red bags contain 5 faded orange bags. dull brown bags contain 5 dim green bags, 5 drab salmon bags. faded white bags contain 2 faded blue bags. pale blue bags contain 1 mirrored lime bag. striped lavender bags contain 1 posh white bag, 5 faded magenta bags, 5 drab crimson bags. shiny olive bags contain 2 posh tomato bags, 1 faded indigo bag. vibrant white bags contain 1 dark purple bag, 5 light lime bags. light purple bags contain 4 shiny black bags. plaid chartreuse bags contain 5 dim gray bags, 3 dull magenta bags. faded violet bags contain 2 faded tomato bags, 1 dark aqua bag, 2 pale lavender bags. drab maroon bags contain 1 plaid fuchsia bag. drab turquoise bags contain 5 dull indigo bags, 1 striped tomato bag, 4 dull cyan bags, 4 vibrant plum bags. shiny plum bags contain 3 drab salmon bags, 5 wavy tomato bags. faded chartreuse bags contain 5 posh black bags. wavy indigo bags contain 4 dim cyan bags, 3 vibrant tan bags. pale salmon bags contain 1 wavy olive bag, 4 pale cyan bags, 2 faded tomato bags, 3 vibrant tan bags. dull bronze bags contain 3 wavy red bags, 2 plaid red bags, 2 muted purple bags. posh plum bags contain no other bags. mirrored chartreuse bags contain 1 clear gray bag. dull chartreuse bags contain 1 faded teal bag, 2 wavy orange bags, 1 bright indigo bag. muted plum bags contain 4 faded silver bags, 5 shiny tan bags. striped plum bags contain 3 posh beige bags. clear green bags contain 2 dark lime bags, 3 muted purple bags, 2 striped bronze bags. dull maroon bags contain 3 faded lavender bags, 3 mirrored white bags, 2 light blue bags, 4 dull tomato bags. faded silver bags contain 3 dim plum bags, 2 pale orange bags, 3 plaid blue bags. dull white bags contain 1 pale indigo bag, 2 bright turquoise bags. mirrored purple bags contain 2 light bronze bags, 1 dark orange bag, 2 dark fuchsia bags, 2 striped violet bags. plaid tomato bags contain 5 bright coral bags. shiny teal bags contain 4 faded red bags, 5 mirrored green bags, 4 shiny coral bags. plaid purple bags contain 3 drab yellow bags, 1 plaid green bag, 4 dim plum bags. dark brown bags contain 5 dull plum bags, 5 dotted bronze bags, 2 wavy tomato bags. dotted plum bags contain 2 faded indigo bags. dim gray bags contain 4 dotted gold bags, 5 mirrored tomato bags. vibrant teal bags contain 2 posh black bags. dotted violet bags contain 3 mirrored yellow bags, 3 mirrored orange bags. wavy white bags contain 1 pale indigo bag, 5 vibrant lavender bags, 2 dim tan bags. posh teal bags contain 1 mirrored brown bag, 3 bright coral bags. pale indigo bags contain 2 posh crimson bags. muted magenta bags contain 1 muted black bag, 4 dull turquoise bags. drab brown bags contain 5 striped gold bags. posh beige bags contain 3 shiny gold bags, 1 shiny cyan bag, 1 posh crimson bag, 2 wavy yellow bags. dark lavender bags contain 5 dim fuchsia bags, 5 mirrored beige bags, 1 dark indigo bag, 3 dull brown bags. faded cyan bags contain 4 vibrant aqua bags, 2 dark magenta bags, 1 dark yellow bag, 3 wavy red bags. bright brown bags contain 1 wavy orange bag, 3 dim plum bags. wavy coral bags contain 4 posh yellow bags, 4 light lime bags. bright maroon bags contain 4 clear turquoise bags, 4 posh salmon bags, 1 striped gold bag. wavy gold bags contain 5 pale purple bags, 5 plaid maroon bags, 2 light purple bags, 2 faded gray bags. dark yellow bags contain 3 plaid green bags, 4 dark teal bags, 4 dark plum bags, 4 vibrant yellow bags. plaid aqua bags contain 5 muted teal bags, 4 posh indigo bags. bright tomato bags contain 5 posh violet bags, 4 wavy tomato bags. drab red bags contain 5 vibrant magenta bags, 2 dark orange bags. dull salmon bags contain 5 drab gray bags, 3 light lime bags. drab indigo bags contain 1 faded red bag, 5 dull maroon bags. shiny white bags contain 3 light blue bags, 5 bright indigo bags, 4 plaid purple bags. plaid lime bags contain 5 clear turquoise bags, 2 plaid cyan bags, 3 dotted olive bags. wavy fuchsia bags contain 1 light violet bag, 4 dark tomato bags, 2 bright green bags. vibrant magenta bags contain 5 mirrored gold bags, 3 dotted red bags. light red bags contain 2 posh crimson bags, 3 wavy orange bags, 1 wavy yellow bag. dim crimson bags contain 3 striped tan bags, 3 pale blue bags, 2 drab yellow bags. dark teal bags contain 1 plaid bronze bag, 1 vibrant aqua bag. shiny magenta bags contain 3 light salmon bags, 4 dark bronze bags, 1 shiny plum bag, 4 clear blue bags. clear lime bags contain 3 vibrant salmon bags, 5 muted magenta bags, 4 posh black bags. dull coral bags contain 1 shiny coral bag, 2 bright black bags. shiny black bags contain 1 dotted purple bag, 2 posh teal bags. striped maroon bags contain 3 drab red bags, 5 light gold bags. vibrant brown bags contain 3 dim green bags, 3 posh white bags, 3 dotted green bags. shiny brown bags contain 1 posh bronze bag. dark lime bags contain 5 light magenta bags, 5 shiny turquoise bags. vibrant crimson bags contain 2 striped bronze bags. posh coral bags contain 2 dim silver bags. dull orange bags contain 5 clear coral bags, 4 shiny tan bags. striped beige bags contain 1 dim olive bag, 3 plaid chartreuse bags, 4 dark chartreuse bags. faded indigo bags contain 5 dark cyan bags, 1 light violet bag, 2 bright coral bags. bright aqua bags contain 1 clear salmon bag, 1 dark orange bag, 5 faded gold bags. plaid orange bags contain 5 vibrant cyan bags, 5 plaid silver bags, 2 wavy olive bags, 2 bright olive bags. posh bronze bags contain 1 faded indigo bag. plaid cyan bags contain 1 muted teal bag, 5 muted olive bags, 3 dull tomato bags, 5 light magenta bags. striped coral bags contain 2 posh black bags. light brown bags contain 5 muted lavender bags, 2 muted coral bags, 1 vibrant tan bag, 5 drab lime bags. shiny tomato bags contain 4 bright turquoise bags, 1 muted tomato bag, 2 clear fuchsia bags. dark green bags contain 4 vibrant magenta bags. drab beige bags contain 4 faded lime bags. shiny turquoise bags contain 3 dark tan bags, 3 faded lavender bags, 5 faded tomato bags. mirrored gold bags contain 4 dull magenta bags, 2 clear turquoise bags, 2 dull white bags, 3 dull tomato bags. dotted purple bags contain 2 shiny brown bags, 1 bright lime bag, 4 faded lavender bags, 2 faded indigo bags. shiny silver bags contain 1 wavy tomato bag, 1 dull gold bag, 2 striped yellow bags. mirrored salmon bags contain 2 posh beige bags. pale red bags contain 4 dotted crimson bags, 3 posh teal bags, 4 dull maroon bags. vibrant salmon bags contain 3 striped maroon bags. dim fuchsia bags contain 5 pale plum bags, 3 light fuchsia bags, 2 bright tomato bags, 2 dark violet bags. clear turquoise bags contain 4 bright lime bags, 3 dark magenta bags. wavy aqua bags contain 1 vibrant turquoise bag, 5 clear gold bags, 1 muted indigo bag, 4 striped gray bags. mirrored fuchsia bags contain 1 posh maroon bag, 2 clear salmon bags. bright purple bags contain 2 vibrant tomato bags. striped blue bags contain 5 dark white bags, 5 wavy orange bags, 5 dark magenta bags. dim plum bags contain 2 pale maroon bags, 1 mirrored blue bag, 5 bright coral bags. clear white bags contain 1 muted cyan bag, 3 mirrored gold bags. vibrant aqua bags contain 2 dull plum bags, 4 muted tomato bags. dark black bags contain 2 posh green bags. muted white bags contain 2 faded green bags, 1 dull gray bag, 2 striped coral bags, 4 dim black bags. posh tomato bags contain 2 mirrored blue bags, 3 posh red bags, 2 faded tan bags, 3 clear tan bags. muted red bags contain 5 plaid crimson bags, 4 plaid turquoise bags, 5 clear gold bags. pale silver bags contain 3 bright turquoise bags. posh lavender bags contain 4 mirrored violet bags. pale tan bags contain 5 mirrored bronze bags. drab aqua bags contain 2 posh bronze bags, 1 vibrant orange bag, 1 light magenta bag. clear magenta bags contain 4 bright olive bags, 5 dim purple bags. light silver bags contain 4 vibrant brown bags, 3 dim olive bags, 3 posh bronze bags. dark plum bags contain 5 vibrant gold bags. posh tan bags contain 3 posh purple bags. mirrored bronze bags contain 1 wavy white bag, 5 bright beige bags, 4 bright turquoise bags, 1 bright yellow bag. dotted fuchsia bags contain 2 faded indigo bags. pale turquoise bags contain 3 vibrant lime bags, 1 vibrant fuchsia bag, 1 dim black bag. light lime bags contain 1 pale orange bag, 3 pale maroon bags, 4 dull maroon bags. bright gray bags contain 5 mirrored bronze bags, 4 dotted purple bags, 5 bright beige bags, 5 posh bronze bags. dull blue bags contain 1 dull gold bag, 3 shiny coral bags. dark salmon bags contain 2 dark teal bags, 3 striped bronze bags, 2 pale plum bags, 5 faded teal bags. light indigo bags contain 1 light green bag, 4 faded fuchsia bags. light fuchsia bags contain 5 shiny black bags, 2 plaid turquoise bags. vibrant gray bags contain 2 faded teal bags, 1 dark brown bag, 1 dark magenta bag, 3 pale white bags. faded fuchsia bags contain 5 pale cyan bags, 2 wavy aqua bags. wavy purple bags contain 1 posh fuchsia bag, 2 clear turquoise bags. dark purple bags contain 5 dotted olive bags, 4 shiny tan bags, 4 clear blue bags. vibrant chartreuse bags contain 4 clear teal bags, 1 plaid coral bag. plaid silver bags contain 4 wavy beige bags, 5 bright aqua bags, 1 vibrant yellow bag. dull turquoise bags contain 1 faded orange bag, 4 vibrant blue bags, 1 vibrant brown bag, 1 clear gold bag. bright violet bags contain 4 plaid fuchsia bags, 1 clear blue bag, 4 dull purple bags, 1 dark yellow bag. wavy turquoise bags contain 4 plaid violet bags, 4 drab gray bags. muted tan bags contain 5 posh white bags, 3 drab salmon bags, 3 light tan bags, 1 dark cyan bag. light maroon bags contain 4 dotted turquoise bags, 5 dim tan bags. plaid gray bags contain 3 dotted cyan bags, 4 striped blue bags, 3 shiny white bags. dotted olive bags contain 5 posh plum bags, 3 mirrored lime bags, 4 clear turquoise bags. plaid crimson bags contain 2 faded lavender bags, 3 shiny tan bags. clear brown bags contain 5 faded lavender bags. shiny lavender bags contain 5 faded gray bags, 5 posh chartreuse bags, 5 dim purple bags. dotted cyan bags contain 2 mirrored blue bags, 5 plaid salmon bags, 1 faded orange bag, 4 dull tomato bags. posh purple bags contain 4 dark beige bags, 3 dim maroon bags, 5 bright beige bags, 5 drab beige bags. vibrant red bags contain 4 dark orange bags. dotted red bags contain 3 plaid blue bags, 5 vibrant lavender bags. muted green bags contain 2 clear fuchsia bags. pale purple bags contain 3 muted tomato bags. muted turquoise bags contain 2 light coral bags, 1 mirrored gray bag. posh chartreuse bags contain 1 dark orange bag, 3 striped olive bags, 5 faded teal bags. bright chartreuse bags contain 3 vibrant maroon bags. shiny cyan bags contain 3 muted olive bags, 1 muted tomato bag. mirrored teal bags contain 2 pale black bags. plaid bronze bags contain 3 muted gold bags, 2 faded indigo bags. dim teal bags contain 2 plaid tomato bags. clear tan bags contain 2 dim green bags, 1 mirrored gray bag, 3 dotted cyan bags. faded crimson bags contain 3 vibrant lavender bags. wavy olive bags contain 4 mirrored lime bags. pale plum bags contain 2 plaid turquoise bags, 5 shiny indigo bags, 3 faded blue bags. dark white bags contain 5 shiny black bags. drab green bags contain 5 muted gold bags. vibrant bronze bags contain 5 bright olive bags, 1 dull gray bag, 3 dark purple bags. pale green bags contain 4 muted teal bags. clear plum bags contain 4 posh violet bags, 1 light blue bag. clear violet bags contain 4 dark aqua bags, 5 muted black bags. posh black bags contain no other bags. shiny gray bags contain 3 vibrant lavender bags. dark crimson bags contain 4 dull tan bags, 1 shiny cyan bag, 5 vibrant indigo bags. dim brown bags contain 3 faded silver bags, 3 dark purple bags. dotted tan bags contain 1 dim indigo bag, 2 vibrant teal bags, 4 bright beige bags, 4 clear silver bags. light gray bags contain 1 faded indigo bag, 1 light tan bag, 1 mirrored lime bag. bright lime bags contain 5 drab yellow bags, 3 plaid cyan bags, 5 faded orange bags. posh maroon bags contain 3 drab teal bags, 2 dotted beige bags. shiny beige bags contain 5 vibrant olive bags, 1 dull blue bag. striped fuchsia bags contain 5 wavy aqua bags. dim indigo bags contain 3 clear aqua bags, 3 clear crimson bags. dull silver bags contain 3 muted lavender bags. wavy teal bags contain 1 clear gray bag, 2 shiny tan bags, 4 shiny brown bags. dull tan bags contain 1 clear silver bag. vibrant maroon bags contain 1 faded lavender bag, 4 bright coral bags, 5 vibrant coral bags. faded magenta bags contain 5 shiny black bags, 3 light crimson bags. dim magenta bags contain 2 shiny tan bags. pale coral bags contain 1 striped black bag, 2 posh violet bags. clear salmon bags contain 5 wavy tomato bags, 4 dull gold bags, 3 dotted olive bags, 2 bright turquoise bags. clear silver bags contain 1 bright coral bag, 3 light magenta bags, 4 muted teal bags, 4 light violet bags. mirrored lavender bags contain 4 faded cyan bags, 4 dotted fuchsia bags, 4 mirrored salmon bags, 5 muted beige bags. muted lime bags contain 5 vibrant olive bags, 1 light chartreuse bag, 5 faded yellow bags, 5 drab plum bags. plaid plum bags contain 2 faded tomato bags. posh cyan bags contain 4 drab green bags, 3 posh plum bags, 4 vibrant gold bags, 5 vibrant aqua bags. faded orange bags contain no other bags. plaid gold bags contain 3 vibrant teal bags. light chartreuse bags contain 5 vibrant cyan bags, 2 drab green bags, 3 shiny plum bags. plaid olive bags contain 1 dim lime bag. wavy yellow bags contain 2 posh bronze bags, 3 plaid blue bags, 2 posh crimson bags, 3 muted gold bags. striped tomato bags contain 3 dim lime bags, 5 plaid crimson bags, 4 pale lime bags. clear aqua bags contain 3 muted tomato bags, 2 striped olive bags. light tan bags contain 1 pale gold bag. mirrored yellow bags contain 2 dim maroon bags, 1 posh violet bag, 3 drab salmon bags. clear crimson bags contain 3 pale cyan bags. dull plum bags contain 4 posh black bags, 4 dark cyan bags, 4 dull olive bags, 5 light violet bags. wavy red bags contain 1 pale maroon bag. faded yellow bags contain 4 bright chartreuse bags, 3 striped gold bags. faded purple bags contain 2 posh yellow bags, 2 shiny black bags, 1 dim magenta bag, 5 vibrant blue bags. vibrant lime bags contain 5 drab tan bags, 5 pale beige bags, 1 faded turquoise bag, 4 dull gold bags. mirrored violet bags contain 1 mirrored bronze bag. drab crimson bags contain 2 dim indigo bags. dim gold bags contain 5 plaid green bags. shiny yellow bags contain 2 faded black bags, 1 posh crimson bag, 4 plaid turquoise bags, 3 pale chartreuse bags. mirrored tan bags contain 3 posh red bags. drab salmon bags contain 3 clear turquoise bags, 2 striped plum bags, 2 plaid turquoise bags. vibrant beige bags contain 1 plaid violet bag. striped crimson bags contain 3 striped bronze bags. light tomato bags contain 5 faded orange bags, 5 mirrored bronze bags, 1 pale orange bag. wavy magenta bags contain 5 drab magenta bags, 2 vibrant tan bags, 2 striped indigo bags. dotted beige bags contain 2 posh bronze bags, 1 faded silver bag. faded gold bags contain 5 vibrant teal bags, 4 dim plum bags, 2 vibrant yellow bags. dark blue bags contain 4 faded plum bags, 3 vibrant crimson bags, 1 vibrant maroon bag. striped olive bags contain 3 posh beige bags, 4 dull white bags. striped black bags contain 2 plaid bronze bags, 4 posh bronze bags. plaid green bags contain 2 dull magenta bags, 2 vibrant indigo bags, 1 dim silver bag. dark silver bags contain 2 wavy brown bags. wavy plum bags contain 4 plaid violet bags. plaid violet bags contain 5 posh crimson bags, 2 dark tan bags. plaid salmon bags contain 4 faded lavender bags, 1 dull olive bag, 4 posh crimson bags, 2 posh plum bags. mirrored indigo bags contain 4 shiny orange bags, 4 dim green bags. striped violet bags contain 1 bright teal bag, 1 bright black bag. shiny coral bags contain 3 bright coral bags. pale bronze bags contain 4 vibrant gray bags, 1 striped maroon bag, 4 dark magenta bags. drab olive bags contain 4 plaid beige bags. dull beige bags contain 4 posh orange bags. muted yellow bags contain 2 muted teal bags, 5 bright coral bags, 4 mirrored beige bags, 1 wavy red bag. drab tan bags contain 4 bright aqua bags, 4 dark crimson bags, 4 muted coral bags. mirrored brown bags contain 1 muted gold bag. striped gold bags contain 1 clear olive bag, 5 muted purple bags. dark orange bags contain 1 mirrored aqua bag, 5 pale brown bags, 3 shiny turquoise bags, 5 dim plum bags. dim green bags contain 1 posh crimson bag, 5 wavy yellow bags, 3 mirrored blue bags, 3 mirrored brown bags. light green bags contain 1 dull cyan bag, 1 striped gold bag, 3 dull maroon bags. faded tomato bags contain 5 posh bronze bags, 3 wavy tomato bags, 2 mirrored gray bags. pale crimson bags contain 3 wavy indigo bags, 5 drab white bags. plaid coral bags contain 2 bright maroon bags, 2 pale chartreuse bags, 5 bright beige bags. dark beige bags contain 3 plaid plum bags, 4 light blue bags, 1 vibrant plum bag. bright coral bags contain no other bags. wavy blue bags contain 5 mirrored plum bags, 5 plaid yellow bags, 1 bright aqua bag. shiny purple bags contain 1 wavy fuchsia bag, 4 wavy bronze bags. light violet bags contain no other bags. muted gray bags contain 4 dull white bags. faded salmon bags contain 2 dotted bronze bags. mirrored green bags contain 4 dark cyan bags, 1 faded silver bag. faded teal bags contain 5 clear silver bags, 3 muted olive bags, 4 light magenta bags, 3 dark cyan bags. muted blue bags contain 2 bright teal bags, 1 vibrant tan bag. dim blue bags contain 4 dark orange bags, 3 bright lime bags, 5 clear salmon bags, 1 striped blue bag. plaid beige bags contain 4 posh fuchsia bags, 1 posh violet bag, 1 drab gray bag, 4 pale white bags. wavy tomato bags contain 2 dark cyan bags, 5 clear silver bags. plaid fuchsia bags contain 4 wavy turquoise bags, 2 clear salmon bags, 1 bright turquoise bag, 3 plaid blue bags. bright tan bags contain 4 dotted green bags, 1 dull orange bag, 1 mirrored violet bag, 4 dim green bags. drab white bags contain 2 dim tan bags. light white bags contain 1 pale gold bag, 4 posh magenta bags. clear olive bags contain 4 plaid cyan bags. light gold bags contain 1 muted gold bag. shiny green bags contain 4 bright maroon bags. drab silver bags contain 5 posh gold bags, 5 drab salmon bags. drab yellow bags contain 1 light violet bag, 2 pale maroon bags, 2 faded orange bags, 2 posh black bags. dark violet bags contain 4 light cyan bags. plaid blue bags contain 4 clear silver bags, 5 plaid bronze bags, 4 shiny tan bags, 2 mirrored gray bags. pale white bags contain 5 posh plum bags, 3 pale maroon bags, 3 muted gold bags, 1 dull tan bag. dull black bags contain 5 pale lavender bags, 5 wavy coral bags. dark indigo bags contain 3 pale orange bags, 5 mirrored lime bags, 5 drab red bags, 4 shiny black bags. drab lime bags contain 4 plaid gray bags. wavy silver bags contain 5 bright magenta bags, 5 dotted beige bags, 1 dim indigo bag. dark turquoise bags contain 2 dim beige bags. vibrant purple bags contain 3 pale orange bags, 3 striped olive bags, 5 clear gold bags, 3 wavy orange bags. wavy green bags contain 3 dull magenta bags, 4 posh bronze bags, 2 plaid tomato bags. faded green bags contain 4 dim silver bags, 3 pale chartreuse bags. light blue bags contain 4 mirrored blue bags, 3 dark cyan bags. dim turquoise bags contain 1 dull maroon bag, 5 light crimson bags, 4 light gold bags. posh turquoise bags contain 3 wavy white bags. dull purple bags contain 5 wavy olive bags, 2 dim crimson bags, 2 dotted plum bags. dark bronze bags contain 5 muted beige bags, 5 mirrored brown bags. pale cyan bags contain 5 muted teal bags, 4 dim plum bags, 3 light gold bags, 5 dark cyan bags. plaid maroon bags contain 4 faded blue bags. faded black bags contain 1 drab lavender bag, 5 posh purple bags. posh indigo bags contain 4 faded tan bags, 1 faded teal bag, 4 pale chartreuse bags, 5 pale gray bags. dull gray bags contain 1 light lime bag. vibrant blue bags contain 1 dotted olive bag, 5 clear fuchsia bags. pale brown bags contain 4 plaid salmon bags, 1 posh yellow bag, 1 faded indigo bag, 2 muted gold bags. vibrant indigo bags contain 5 drab yellow bags, 2 dark cyan bags, 1 muted teal bag, 1 striped coral bag. wavy chartreuse bags contain 3 muted olive bags, 2 faded teal bags. dim chartreuse bags contain 1 wavy white bag, 5 mirrored violet bags, 4 dull fuchsia bags. clear chartreuse bags contain 4 drab white bags, 1 muted plum bag. drab fuchsia bags contain 4 muted teal bags, 1 shiny lime bag, 2 dotted gold bags. striped green bags contain 5 dim tan bags, 5 dark teal bags. drab coral bags contain 4 clear tan bags. dotted silver bags contain 5 wavy coral bags, 3 bright yellow bags, 4 plaid maroon bags. pale black bags contain 3 dim violet bags, 2 mirrored plum bags, 4 dotted maroon bags. clear fuchsia bags contain 1 posh black bag, 5 dim magenta bags. striped teal bags contain 1 pale red bag, 2 mirrored lime bags, 1 pale blue bag. muted maroon bags contain 1 plaid violet bag, 1 faded teal bag. faded gray bags contain 3 dim tan bags, 2 drab teal bags. dim lime bags contain 5 mirrored gold bags. light orange bags contain 3 bright maroon bags. bright red bags contain 5 bright brown bags, 1 mirrored tan bag, 5 muted coral bags, 4 striped chartreuse bags. shiny tan bags contain 4 posh plum bags, 1 pale maroon bag, 4 faded indigo bags, 3 posh black bags. posh blue bags contain 3 clear maroon bags, 3 shiny maroon bags. bright blue bags contain 3 light bronze bags, 5 dim silver bags. dull indigo bags contain 3 plaid salmon bags, 5 shiny indigo bags, 3 dotted crimson bags, 4 clear tan bags. clear blue bags contain 5 mirrored gold bags, 4 plaid bronze bags, 2 dull gold bags, 3 clear crimson bags. striped chartreuse bags contain 2 bright magenta bags, 4 bright lime bags. muted orange bags contain 1 dull plum bag, 1 posh red bag. muted aqua bags contain 2 dotted olive bags, 2 dim violet bags. dull gold bags contain 1 posh plum bag. striped brown bags contain 4 vibrant coral bags, 3 dull lavender bags. clear tomato bags contain 4 light gold bags. dull cyan bags contain 3 clear salmon bags, 2 dark lime bags. muted coral bags contain 4 striped plum bags, 1 posh green bag, 2 plaid violet bags. drab cyan bags contain 3 wavy lime bags. vibrant violet bags contain 2 dark orange bags, 1 drab salmon bag, 2 posh beige bags. pale tomato bags contain 3 drab beige bags, 1 wavy coral bag. light beige bags contain 4 plaid lime bags, 5 dark lavender bags, 4 plaid red bags, 4 drab white bags. dim cyan bags contain 5 plaid cyan bags, 5 faded orange bags, 5 posh plum bags, 3 clear silver bags. wavy tan bags contain 5 striped cyan bags, 5 plaid violet bags. pale gray bags contain 4 clear gold bags, 5 posh turquoise bags. plaid magenta bags contain 2 dark green bags, 1 vibrant crimson bag, 3 dotted gray bags. faded beige bags contain 3 faded violet bags, 2 dotted green bags, 5 mirrored cyan bags. shiny aqua bags contain 4 dotted coral bags, 3 vibrant violet bags, 3 bright maroon bags, 1 shiny cyan bag. dim red bags contain 4 plaid blue bags, 2 plaid lime bags, 1 dark red bag. pale violet bags contain 3 mirrored white bags, 2 posh white bags. faded aqua bags contain 1 faded silver bag, 5 clear fuchsia bags. dim silver bags contain 1 muted gold bag, 1 dim tan bag, 3 striped yellow bags, 5 faded indigo bags. dotted maroon bags contain 3 bright teal bags, 1 clear white bag. dotted blue bags contain 3 dotted plum bags, 2 faded crimson bags, 3 bright coral bags, 2 light fuchsia bags. mirrored orange bags contain 2 plaid yellow bags, 2 faded tan bags. faded lime bags contain 2 plaid crimson bags, 5 bright coral bags, 2 vibrant gold bags, 2 vibrant aqua bags. vibrant black bags contain 4 dim bronze bags, 4 dull tomato bags. mirrored gray bags contain 3 dull olive bags, 3 clear silver bags, 3 wavy chartreuse bags. clear yellow bags contain 1 shiny green bag. bright turquoise bags contain 3 wavy chartreuse bags. muted black bags contain 1 muted gold bag. faded coral bags contain 1 posh plum bag. striped white bags contain 3 clear coral bags, 2 plaid blue bags, 4 plaid aqua bags, 5 drab brown bags. bright cyan bags contain 1 faded teal bag, 4 dim coral bags, 5 shiny red bags. drab purple bags contain 5 shiny beige bags, 2 shiny indigo bags, 5 vibrant aqua bags, 3 pale purple bags. striped cyan bags contain 5 dotted blue bags. posh magenta bags contain 5 pale red bags, 1 drab white bag, 5 pale white bags, 5 dotted plum bags. clear coral bags contain 3 dark chartreuse bags. dull aqua bags contain 4 clear blue bags, 1 dotted green bag. muted brown bags contain 2 shiny brown bags, 2 clear fuchsia bags, 5 pale yellow bags, 1 dotted tan bag. vibrant lavender bags contain 1 posh crimson bag. posh gray bags contain 5 vibrant beige bags, 4 dark red bags. wavy salmon bags contain 3 faded coral bags. dotted orange bags contain 3 clear cyan bags, 5 shiny silver bags, 2 muted gold bags, 2 dim tomato bags. dotted gray bags contain 3 posh bronze bags, 4 shiny tan bags. dark tan bags contain 1 dull plum bag, 2 muted teal bags, 3 mirrored brown bags, 3 faded teal bags. muted tomato bags contain no other bags. muted violet bags contain 1 drab green bag, 5 wavy green bags. dotted bronze bags contain 5 dim tan bags. shiny violet bags contain 4 posh beige bags, 4 pale lime bags, 1 dim aqua bag. clear indigo bags contain 1 wavy olive bag, 5 dim purple bags, 5 striped blue bags. clear gold bags contain 5 posh teal bags, 2 dull tomato bags. mirrored magenta bags contain 5 clear green bags, 4 vibrant black bags, 2 drab lavender bags. wavy black bags contain 3 clear salmon bags, 4 light teal bags, 1 clear fuchsia bag, 5 dull tan bags. shiny crimson bags contain 3 plaid blue bags, 2 wavy black bags, 3 mirrored black bags. muted gold bags contain no other bags. posh aqua bags contain 5 shiny plum bags. dim white bags contain 4 shiny white bags, 4 dark tan bags, 2 striped olive bags, 5 clear yellow bags. dim black bags contain 3 faded blue bags, 1 dark white bag. mirrored olive bags contain 3 mirrored beige bags, 1 striped tomato bag, 3 wavy olive bags. bright white bags contain 5 posh teal bags, 2 dark purple bags, 2 bright tan bags. mirrored lime bags contain 1 muted tomato bag, 2 dark red bags, 5 plaid bronze bags. dark coral bags contain 1 striped chartreuse bag, 5 bright gray bags. dotted coral bags contain 3 posh crimson bags, 5 posh fuchsia bags. dim orange bags contain 1 dim magenta bag, 3 clear turquoise bags, 4 pale lime bags, 3 faded teal bags. mirrored plum bags contain 3 striped teal bags. posh olive bags contain 2 plaid lavender bags, 5 shiny red bags. shiny blue bags contain 4 plaid turquoise bags, 2 dim red bags. faded lavender bags contain 3 dim cyan bags, 5 plaid bronze bags. posh white bags contain 1 vibrant aqua bag. drab black bags contain 3 vibrant yellow bags, 2 vibrant teal bags, 5 dark teal bags. shiny red bags contain 4 dotted tan bags, 1 faded plum bag, 4 drab magenta bags. pale gold bags contain 3 dull magenta bags. faded turquoise bags contain 1 mirrored maroon bag, 3 vibrant purple bags. muted purple bags contain 3 drab red bags, 2 wavy tomato bags, 3 wavy chartreuse bags, 2 dark teal bags. posh lime bags contain 5 wavy crimson bags, 4 dull silver bags, 5 plaid magenta bags. bright olive bags contain 5 shiny indigo bags. faded bronze bags contain 2 dark crimson bags, 2 clear orange bags, 4 striped beige bags. dark olive bags contain 4 vibrant chartreuse bags, 4 light coral bags, 1 faded purple bag. dark aqua bags contain 4 plaid salmon bags, 4 dim plum bags, 2 dim orange bags. pale magenta bags contain 3 dull turquoise bags, 2 mirrored purple bags, 5 clear olive bags, 5 dotted red bags. plaid tan bags contain 2 light salmon bags, 3 dim lime bags, 2 dim maroon bags, 4 wavy gray bags. shiny lime bags contain 4 striped olive bags, 3 dim coral bags. striped indigo bags contain 3 wavy red bags, 5 posh white bags, 5 light tan bags, 1 plaid bronze bag. wavy crimson bags contain 2 dull fuchsia bags, 5 striped tomato bags. """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
48,292
advent-of-code
MIT License
src/day5/Day05.kt
ousa17
573,435,223
false
{"Kotlin": 8095}
package day5 import readInput val list1 = mutableListOf("S", "L", "W") val list2 = mutableListOf("J", "T", "N", "Q") val list3 = mutableListOf("S", "C", "H", "F", "J") val list4 = mutableListOf("T", "R", "M", "W", "N", "G", "B") val list5 = mutableListOf("T", "R", "L", "S", "D", "H", "Q", "B") val list6 = mutableListOf("M", "J", "B", "V", "F", "H", "R", "L") val list7 = mutableListOf("D", "W", "R", "N", "J", "M") val list8 = mutableListOf("B", "Z", "T", "F", "H", "N", "D", "J") val list9 = mutableListOf("H", "L", "Q", "N", "B", "F", "T") val listAll = mutableListOf(list1, list2, list3, list4, list5, list6, list7, list8, list9) fun main() { val input = readInput("day5/Day05") part1(input) part2(input) } private fun part1(input: List<String>) { input.map { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() val matchResult = regex.find(it) val (numberOfCrate, fromStack, toStack) = matchResult!!.destructured val fromIndex = fromStack.toInt() - 1 val toIndex = toStack.toInt() - 1 repeat(numberOfCrate.toInt()) { val lastItem = listAll[fromIndex].last() listAll[toIndex].apply { add(lastItem) } listAll[fromIndex].apply { //remove(last()) wrong //remove(lastItem) wrong removeAt(this.size-1) } } } listAll.map { print(it.last()) } } private fun part2(input: List<String>) { input.map { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() val matchResult = regex.find(it) val (numberOfCrate, fromStack, toStack) = matchResult!!.destructured val fromIndex = fromStack.toInt() - 1 val toIndex = toStack.toInt() - 1 val listToMove = listAll[fromIndex].let { it.subList(it.size - numberOfCrate.toInt(), it.size) } listAll[toIndex].apply { addAll(listToMove) } listAll[fromIndex] = listAll[fromIndex].run { this.subList(0, this.size - numberOfCrate.toInt()) } } listAll.map { print(it.last()) } }
0
Kotlin
0
0
aa7f2cb7774925b7e88676a9ca64ca9548bce5b2
2,191
advent-day-1
Apache License 2.0
src/main/kotlin/com/oocode/PipesGrid.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun pipesGridFrom(input: String): PipesGrid { val lines = input.split("\n") val tiles = lines.mapIndexed { y, line -> tilesFrom(y, line) } return PipesGrid(tiles) } data class PipesGrid(val tiles: List<List<Tile>>) { fun furthestDistanceFromStart() = path().size / 2 fun path(): MutableList<Tile> { val path = mutableListOf<Tile>() var current: Tile? = start() while (current != null) { path.add(current) current = nextTile(current, path) } return path } fun start() = tiles.flatten().first { it.type == START } fun nextTile(current: Tile, path: List<Tile>): Tile? = neighbouringTiles(current.position) .filter { !path.contains(it.tile) } .filter { it.canBeReachedFrom(it.directionTowardsThis.opposite) } .filter { current.canBeReachedFrom(it.directionTowardsThis) } .map { it.tile } .firstOrNull() fun neighbouringTiles(sourcePosition: Position) = neighbouringPositions(sourcePosition) .map { NeighbouringTile(it.outwardDirection, tileAt(it.position)) } private fun tileAt(position: Position): Tile = tiles[position.y][position.x] override fun toString(): String = tiles .map { it.map { it.type.toString() }.joinToString("") } .joinToString("\n") private fun neighbouringPositions(position: Position): Set<NeighbouringPosition> = Compass.values() .map { NeighbouringPosition(position + it.relativePosition, it) } .filter { isInBounds(it) } .toSet() private fun isInBounds(neighbouringPosition: NeighbouringPosition) = neighbouringPosition.position.let { position -> position.x >= 0 && position.y >= 0 && position.x < width && position.y < height } val width: Int get() = tiles[0].size val height: Int get() = tiles.size } enum class Compass(val relativePosition: Position) { North(Position(0, -1)), South(Position(0, 1)), East(Position(1, 0)), West(Position(-1, 0)); val opposite: Compass get() = when(this) { North -> South South -> North East -> West West -> East } } interface TileType { fun canBeReachedFrom(positionRelativeToMe: Compass): Boolean } data class ConnectingTileType(val representation: String, val outgoing1: Compass, val outgoing2: Compass) : TileType { override fun canBeReachedFrom(positionRelativeToMe: Compass) = outgoing1 == positionRelativeToMe || outgoing2 == positionRelativeToMe override fun toString() = representation } data class Ground(val representation: String) : TileType { override fun canBeReachedFrom(positionRelativeToMe: Compass) = false override fun toString() = representation } private data class NeighbouringPosition(val position: Position, val outwardDirection: Compass) data class NeighbouringTile(val directionTowardsThis: Compass, val tile: Tile) { fun canBeReachedFrom(direction: Compass) = tile.canBeReachedFrom(direction) } data class Start(val representation: String) : TileType { override fun canBeReachedFrom(positionRelativeToMe: Compass) = true override fun toString() = representation } val NE = ConnectingTileType("L", Compass.North, Compass.East) val NW = ConnectingTileType("J", Compass.North, Compass.West) val NS = ConnectingTileType("|", Compass.North, Compass.South) val EW = ConnectingTileType("-", Compass.East, Compass.West) val SE = ConnectingTileType("F", Compass.South, Compass.East) val SW = ConnectingTileType("7", Compass.South, Compass.West) val GROUND = Ground(".") val START = Start("S") data class Position(val x: Int, val y: Int) { operator fun plus(other: Position): Position = Position(x + other.x, y + other.y) } data class Tile(val type: TileType, val position: Position) { fun canBeReachedFrom(direction: Compass): Boolean = direction.let { type.canBeReachedFrom(it) } } fun tilesFrom(y: Int, line: String): List<Tile> = line.mapIndexed { x, c -> tileFor(c.toString(), x, y) } fun tileFor(name: String, x: Int, y: Int) = Tile(tileTypeFor(name), Position(x, y)) fun tileTypeFor(name: String) = when (name) { "|" -> NS "-" -> EW "F" -> SE "7" -> SW "L" -> NE "J" -> NW "." -> GROUND "S" -> START else -> { throw RuntimeException("Unexpected name: $name") } }
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
4,397
advent-of-code-2023
MIT License
src/cn/leetcode/codes/simple18/Simple18_2.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple18 import java.util.* import kotlin.collections.ArrayList class Simple18_2 { fun fourSum(nums: IntArray, target: Int): List<List<Int>> { val list = ArrayList<ArrayList<Int>>() if (nums.size < 4) return list //对数组进行排序 Arrays.sort(nums) val count = nums.size //外层循环 for (i in 0 until count - 3) { //跳过本次循环 if (i > 0 && nums[i] == nums[i - 1]) { continue } //由于是排序之后的数组 如果前四个数据已经大于 target 没有必要进行在循环 if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) { break } //如果后三个数据 小于 target 则没有必要再循环 if (nums[i] + nums[count - 1] + nums[count - 2] + nums[count - 3] < target) { continue } //第二层外层循环 for (j in i + 1 until count - 2) { //去重 后一个数据 和前一个相同 if (j > i + 1 && nums[j] == nums[j - 1]) { continue } //前三个数据已大于 target 没有必要再循环 if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target){ break } //如果后三个数据已经小于 target 没有必要再循环下去 if (nums[i] + nums[j] + nums[count - 1] + nums[count - 2] < target){ continue } //双指针区间 var l = j + 1 var r = nums.size - 1 while (l < r) { val sum = nums[i] + nums[j] + nums[l] + nums[r] when { sum > target -> { r-- } sum < target -> { l++ } else -> { list.add(arrayListOf(nums[i], nums[j], nums[l], nums[r])) //去重 while (l < r && nums[l] == nums[l + 1]) l++ while (l < r && nums[r] == nums[r - 1]) r-- r-- l++ } } } } } return list } }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
2,552
LeetCodeSimple
Apache License 2.0
src/main/kotlin/tw/gasol/aoc/aoc2022/Day5.kt
Gasol
574,784,477
false
{"Kotlin": 70912, "Shell": 1291, "Makefile": 59}
package tw.gasol.aoc.aoc2022 import java.util.Scanner class Day5 { fun part1(input: String): String { val stackBuilder = StringBuilder() var stacks: List<ArrayDeque<Char>>? = null input.lineSequence() .forEach { line -> if (stacks == null) { if (line.isBlank()) { stacks = buildStack(stackBuilder.toString()) } else { stackBuilder.appendLine(line) } } else if (line.isNotBlank()) { val procedure = parseProcedure(line) runProcedure(stacks!!, procedure) } } return stacks?.map { it.last() }?.joinToString("").orEmpty() } private fun runProcedure(stacks: List<ArrayDeque<Char>>, procedure: MoveProcedure) { repeat(procedure.quantity) { val from = stacks[procedure.from - 1] val to = stacks[procedure.to - 1] to.addLast(from.removeLast()) } } private fun runProcedure9001(stacks: List<ArrayDeque<Char>>, procedure: MoveProcedure) { // CrateMover 9001 (1..procedure.quantity).map { _ -> stacks[procedure.from - 1].removeLast() }.reversed().forEach { char -> stacks[procedure.to - 1].addLast(char) } } private fun parseProcedure(line: String) = MoveProcedure.fromString(line) private fun buildStack(input: String): List<ArrayDeque<Char>> { val crateLines = input.lines() .filterNot { it.isBlank() } .filterNot { it.startsWith(" 1 ") } val emptyCrateReplacement = "[-]" val crateLists = crateLines .map { line -> line.replace("^ {3}".toRegex(), emptyCrateReplacement) .replace(" ", " $emptyCrateReplacement") .split(" ") .filterNot { it.isBlank() } .map { it.trim()[1] } } .filterNot { it.isEmpty() } val stackSize = crateLists.maxOf { it.size } val stacks = buildList(stackSize) { repeat(stackSize) { add(ArrayDeque<Char>()) } } crateLists.flatten() .forEachIndexed { index, crate -> if (crate != '-') { stacks[index % stacks.size].addFirst(crate) } } return stacks } fun part2(input: String): String { val stackBuilder = StringBuilder() var stacks: List<ArrayDeque<Char>>? = null input.lineSequence() .forEach { line -> if (stacks == null) { if (line.isBlank()) { stacks = buildStack(stackBuilder.toString()) } else { stackBuilder.appendLine(line) } } else if (line.isNotBlank()) { val procedure = parseProcedure(line) runProcedure9001(stacks!!, procedure) } } return stacks?.map { it.last() }?.joinToString("").orEmpty() } } data class MoveProcedure(val quantity: Int, val from: Int, val to: Int) { companion object { fun fromString(line: String): MoveProcedure = Scanner(line).use { scanner -> val command = scanner.next() assert(command == "move") { "Invalid command: $command" } val quantity = scanner.nextInt() assert(quantity >= 0) { "Invalid quantity: $quantity" } scanner.next() val from = scanner.nextInt() scanner.next() val to = scanner.nextInt() return MoveProcedure(quantity, from, to) } } }
0
Kotlin
0
0
a14582ea15f1554803e63e5ba12e303be2879b8a
3,805
aoc2022
MIT License
src/main/kotlin/day5.kt
tianyu
574,561,581
false
{"Kotlin": 49942}
import assertk.assertThat import assertk.assertions.containsExactly import assertk.assertions.isEqualTo private fun main() { val crateMover9000 = CargoCrane { stacks, count, from, to -> stacks[to].append(stacks[from].unappend(count).reversed()) } val crateMover9001 = CargoCrane { stacks, count, from, to -> stacks[to].append(stacks[from].unappend(count)) } tests { "Popping off the top of the stack" { val stringBuilder = StringBuilder("abcdef") assertThat(stringBuilder.unappend(1)).isEqualTo("f") assertThat(stringBuilder.toString()).isEqualTo("abcde") assertThat(stringBuilder.unappend(3)).isEqualTo("cde") assertThat(stringBuilder.toString()).isEqualTo("ab") } "Getting the top of each stack" { val stacks = listOf( StringBuilder("abcde"), StringBuilder("abc"), StringBuilder("abcdef"), ) assertThat(stacks.topCrates()).isEqualTo("ecf") } "Reading stacks" { val stack = """ [D] [N] [C] [Z] [M] [P] 1 2 3 """.trimIndent() assertThat(stack.lines().iterator().readStacks().map(StringBuilder::toString)) .containsExactly("ZN", "MCD", "P") } val example = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 """.trimIndent() "Part 1 Example" { assertThat(crateMover9000.moveCrates(example.lineSequence()).map(CharSequence::toString)) .containsExactly("C", "M", "PDNZ") } "Part 2 Example" { assertThat(crateMover9001.moveCrates(example.lineSequence()).map(CharSequence::toString)) .containsExactly("M", "C", "PZND") } } part1("Using the CrateMover9000, the crates at the top are:") { crateMover9000.moveCrates().topCrates() } part2("Using the CrateMover9001, the crates at the top are:") { crateMover9001.moveCrates().topCrates() } } private fun interface CargoCrane { fun move(stacks: List<StringBuilder>, count: Int, from: Int, to: Int) } private fun CargoCrane.moveCrates(): List<CharSequence> = withInputLines("day5.txt", this::moveCrates) private fun CargoCrane.moveCrates(input: Sequence<String>): List<CharSequence> { val lines = input.iterator() val stacks = lines.readStacks() assert(lines.next() == "") for (line in lines) { if (!line.startsWith("move ")) break val (count, from, to) = line.split(' ').mapNotNull(String::toIntOrNull) move(stacks, count, from - 1, to - 1) } return stacks } private fun Iterator<String>.readStacks(): List<StringBuilder> = buildList { for (line in this@readStacks) { if (line.startsWith(" 1 ")) break val numColumns = (line.length + 1) / 4 ensureSize(numColumns, ::StringBuilder) repeat(numColumns) { val crate = line[4 * it + 1] if (crate != ' ') this[it].append(crate) } } forEach(StringBuilder::reverse) } private inline fun <T> MutableList<T>.ensureSize(n: Int, init: () -> T) { repeat((size until n).count()) { add(init()) } } private fun StringBuilder.unappend(count: Int): String { return substring(length - count, length).also { deleteRange(length - count, length) } } private fun List<CharSequence>.topCrates() = buildString(size) { this@topCrates.forEach { append(it.last()) } }
0
Kotlin
0
0
6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea
3,453
AdventOfCode2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/AreOccurrencesEqual.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 1941. Check if All Characters Have Equal Number of Occurrences * link https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/ */ fun interface AreOccurrencesEqual { operator fun invoke(s: String): Boolean } class AreOccurrencesEqualKotlin : AreOccurrencesEqual { override operator fun invoke(s: String): Boolean { val num = s.count { it == s[0] } for (i in 1 until s.length) { if (num != s.count { it == s[i] }) return false } return true } } class AreOccurrencesEqualBF : AreOccurrencesEqual { override operator fun invoke(s: String): Boolean { val fr = IntArray(ALPHABET_LETTERS_COUNT) s.chars().forEach { c -> fr[c - 'a'.code]++ } return fr.filter { f -> f > 0 }.all { f -> f == fr.max() } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,564
kotlab
Apache License 2.0
src/main/kotlin/calculations/Matrix.kt
J-MR-T
359,117,393
false
null
package calculations import calculations.* import kotlin.math.abs private val Array<Array<Double>>.asNumberMatrix: Array<Array<out Number>> get() { return if (flatMap { doubles: Array<Double> -> doubles.asIterable() } .all { d: Double -> d.toString().endsWith(".0") }) { map { doubles -> doubles.map { d -> d.toInt() }.toTypedArray() }.toTypedArray() } else { map { doubles -> doubles.map { d -> d }.toTypedArray() }.toTypedArray() } } /** * This is an array of ***rows*** (Arrays themselves), which then contain the actual numbers */ class Matrix(private var matrix: Array<Array<out Number>>) : Iterable<Array<Number>> { companion object { fun getIdentityMatrix(dimension: Int): Matrix { return Matrix(Array(dimension) { indexRow -> Array(dimension) { indexColumn -> if (indexRow == indexColumn) 1 else 0 } }) } fun readMatrix(text: String = "Input matrix, row by row, spaces between members, end matrix with empty line"): Matrix { return Matrix(readDoubleMatrix(text).asNumberMatrix) } fun readDoubleMatrix(text: String = "Input matrix, row by row, spaces between members, end matrix with empty line"): Array<Array<Double>> { val lines: MutableList<String> = mutableListOf() println(text) do { val lastInput = readLine() ?: "" if (lastInput != "") lines.add(lastInput) } while (lastInput != "") val matrix = try { lines.map { it.splitToSequence(" ").filter(String::isNotBlank).map { s -> s.toDouble() }.toList().toTypedArray() }.toTypedArray() } catch (e: NumberFormatException) { error("Did not input only numbers: $e") } if (!matrix.map(Array<Double>::size).all { i -> i == matrix[0].size }) { error("Non uniform dimensions") } return matrix } private operator fun Array<Array<out Number>>.times(other: Array<Array<out Number>>): Array<Array<Number>>? { return multiply(this, other) } private fun multiply(left: Array<Array<out Number>>, right: Array<Array<out Number>>): Array<Array<Number>>? { //Otherwise matrix multiplication isn't possible return if (left[0].size == right.size) { val returnMatrix: Array<Array<Number>> = Array(left.size) { Array(right[0].size) { 0 } } returnMatrix.forEachIndexed { indexRow, arrayOfNumbers -> arrayOfNumbers.forEachIndexed { indexColumn, _ -> returnMatrix[indexRow][indexColumn] = left[indexRow].mapIndexed { index, number -> number * right[index][indexColumn] } .reduce(::add) } } returnMatrix } else { null } } private fun multiplyMod( left: Array<Array<out Number>>, right: Array<Array<out Number>>, mod: Int = 2, ): Array<Array<Number>>? { if (mod == 0) return multiply(left, right) //Otherwise matrix multiplication isn't possible return if (left[0].size == right.size) { val returnMatrix: Array<Array<Number>> = Array(left.size) { Array(right[0].size) { 0 } } returnMatrix.forEachIndexed { indexRow, arrayOfNumbers -> arrayOfNumbers.forEachIndexed { indexColumn, _ -> returnMatrix[indexRow][indexColumn] = left[indexRow].mapIndexed { index, number -> number * right[index][indexColumn] } .reduce { x, y -> addMod(x, y, mod) } } } returnMatrix } else { null } } private fun add(left: Array<Array<out Number>>, right: Array<Array<out Number>>): Array<Array<Number>>? { //Otherwise matrix multiplication isn't possible return if (left.size == right.size && left[0].size == right[0].size) { val returnMatrix: Array<Array<Number>> = Array(left.size) { Array(left[0].size) { 0 } } returnMatrix.forEachIndexed { indexRow, arrayOfNumbers -> arrayOfNumbers.forEachIndexed { indexColumn, _ -> returnMatrix[indexRow][indexColumn] = left[indexRow][indexColumn] + right[indexRow][indexColumn] } } returnMatrix } else { null } } operator fun Number.times(matrix: Matrix): Matrix { return Matrix(this * matrix.matrix) } private operator fun Number.times(matrix: Array<Array<out Number>>): Array<Array<out Number>> { return matrix.map { row -> row.map { it * this }.toTypedArray() }.toTypedArray() } fun List<Matrix>.multiplyAll(): Matrix { return Matrix(map { matrix -> matrix.matrix }.multiplyAll()) } fun List<Matrix>.addAll(): Matrix { return Matrix(map { matrix -> matrix.matrix }.addAll()) } private fun List<Array<Array<out Number>>>.multiplyAll(): Array<Array<out Number>> { return reduce { left, right -> (left * right)?.map { arrayOfNumbers -> arrayOfNumbers.map { it }.toTypedArray() }?.toTypedArray() ?: error("Matrix multiplication not defined on inputs") } } private fun List<Array<Array<out Number>>>.addAll(): Array<Array<out Number>> { return reduce { left, right -> (add(left, right))?.map { arrayOfNumbers -> arrayOfNumbers.map { it }.toTypedArray() }?.toTypedArray() ?: error("Matrix add not defined on inputs") } } } val numRows: Int get() = this.matrix.size val numColumns: Int get() = this.matrix.getOrNull(0)?.size ?: 0 private val toIntsIfApplicable: Matrix get() = Matrix(this.matrix.toIntsIfApplicable) private val Array<Array<Number>>.addOut: Array<Array<out Number>> get() { return this.map { arrayOfNumbers -> arrayOfNumbers.map { number -> number }.toTypedArray() }.toTypedArray() } val columnVectors: Matrix get() { if (!this::savedColumnVectors.isInitialized) { savedColumnVectors = transposed() } return savedColumnVectors } private lateinit var savedColumnVectors: Matrix fun asLatex(whichKind: String = "pmatrix"): String { return matrix.asLatex(whichKind) } private fun Array<Array<out Number>>.asLatex(whichKind: String = "pmatrix"): String { return this.joinToString( separator = "\\\\", prefix = "\\begin{$whichKind}", postfix = "\\end{$whichKind}", ) { arrayOfNumbers -> arrayOfNumbers.joinToString("&") } } infix fun pow(int: Int): Matrix? { var matrix: Matrix? = this repeat(int - 1) { matrix = this * matrix } return matrix } operator fun times(other: Matrix?): Matrix? { if (other == null) return null return (this.matrix * other.matrix)?.let { Matrix(it.addOut) } } operator fun times(number: Number): Matrix { return Matrix(number * this.matrix) } operator fun plus(other: Matrix): Matrix? { return (this.matrix + other.matrix)?.let { Matrix(it.addOut) } } operator fun minus(other: Matrix): Matrix? { return this + (-other) } private operator fun Array<Array<out Number>>.plus(other: Array<Array<out Number>>): Array<Array<Number>>? { return add(this, other) } fun printMatrix() { print(this.toString()) } private fun Array<Array<out Number>>.printMatrix() { println(joinToString(System.lineSeparator()) { array -> array.joinToString(" ") }) } fun transpose() { this.matrix = this.matrix.transposed() } fun transposed(): Matrix { return Matrix(this.matrix.transposed()) } private fun Array<Array<out Number>>.transposed(): Array<Array<out Number>> { return Array(this[0].size) { indexRow -> Array(this.size) { indexColumn -> this[indexColumn][indexRow] } } } // fun gauss(rightSideVector: Matrix = Matrix(Array(numRows) { Array(1) { 0 } })): Matrix { // //TODO // val returnMatrix = deepCopy() // for (i in 0 until numRows) { // val matricesWithNonZeroAtCurrentColumn = returnMatrix.matrix.filter { row -> row[i] != 0 }.map { a->a.map { b->b }.toTypedArray()} // var sourceRow = matricesWithNonZeroAtCurrentColumn.firstOrNull { row -> // row.take(i).all { num -> // //num==0 check // abs(num.toDouble()) < 2 * Double.MIN_VALUE // } // } ?: continue // // //normalize source row // // //should always be != 0 // val firstRelevantOfSourceRow = sourceRow[i] // sourceRow = sourceRow.map { num -> num / firstRelevantOfSourceRow }.toTypedArray() // // //multiply and add source row with others to make them 0 // for (currentRow in matricesWithNonZeroAtCurrentColumn) { // val firstRelevantOfCurrentRow = currentRow[i] // currentRow.forEachIndexed { index, number -> // //FIXME because of the <out Number> and mapping shenanigans this will probably not override the actual return array // currentRow[index] = (-1 / firstRelevantOfCurrentRow) * sourceRow[index] + currentRow[index] // } // // } // } // } fun deepCopy(): Matrix { return Matrix( Array(numRows) { i -> Array(numColumns) { j -> this[i, j] } } ) } private val Array<Array<out Number>>.toIntsIfApplicable: Array<Array<out Number>> get() { return if (flatMap { numbers -> numbers.asIterable() }.all { number -> number is Int }) { this } else { if (flatMap { numbers -> numbers.asIterable() } .all { d: Number -> d.toString().endsWith(".0") }) { map { numbers -> numbers.map { d -> d.toInt() }.toTypedArray() }.toTypedArray() } else { map { numbers -> numbers.map { d -> d }.toTypedArray() }.toTypedArray() } } } private fun Array<Array<Double>>.convertToIntMatrixOrNull(): Array<Array<Int>>? { return if (flatMap { doubles: Array<Double> -> doubles.asIterable() } .all { d: Double -> d.toString().endsWith(".0") }) { map { doubles -> doubles.map { d -> d.toInt() }.toTypedArray() }.toTypedArray() } else { null } } operator fun unaryMinus(): Matrix { return this * -1 } operator fun get(row: Int, column: Int): Number { return matrix[row][column] } operator fun get(row: Int): Array<out Number> { return matrix[row] } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Matrix) return false if (!matrix.contentDeepEquals(other.matrix)) return false return true } override fun hashCode(): Int { return matrix.contentDeepHashCode() } override fun iterator(): Iterator<Array<Number>> { return matrix.map { a -> a.map { b -> b }.toTypedArray() }.toTypedArray().iterator() } override fun toString(): String { val stringBuilder = StringBuilder(matrix.size * (matrix.getOrNull(0)?.size ?: return "")) val maxSpaces = flatMap { it.asIterable() }.maxOf { number: Number -> number.toString().length } forEach { ints -> ints.forEach { stringBuilder.append("$it" + " ".repeat(maxSpaces - it.toString().length + 1)) } stringBuilder.appendLine() } return stringBuilder.toString() } fun mulMod(matrix: Matrix, mod: Int = 2): Matrix? { return Matrix(multiplyMod(this.matrix, matrix.matrix, mod)?.addOut ?: return null) } }
0
Kotlin
0
0
2295152b89fc2fd9f5a9a48db8c9655fea035451
12,803
MatrixMultiplication
MIT License
src/main/kotlin/day1/Solution.kt
krazyglitch
573,086,664
false
{"Kotlin": 31494}
package day1 import util.Utils import java.time.Duration import java.time.LocalDateTime class Solution { // Parse elves from input and find the elf with the highest calorie count fun part1(input: List<String>): Int { val elves = parseElves(input) return elves.maxOf { e -> e.calorieCount } } // Parse elves from input, sort the list, then sum the three highest calorie counts fun part2(input: List<String>): Int { var elves = parseElves(input) elves = elves.sortedBy { e -> e.calorieCount } return elves.subList(elves.size - 3, elves.size).sumOf { e -> e.calorieCount } } /** * Initialise list with first elf * Iterate over the input lines * If line cannot be parsed to integer, a new elf must be added as the line is empty * If line can be parsed to integer, add the value from the line into the last elf in the list */ private fun parseElves(input: List<String>): List<Elf> { var addElf = false val elves = ArrayList<Elf>() var elf = Elf() elves.add(elf) for (line in input) { val parsedInt = line.toIntOrNull() if (parsedInt == null) { addElf = true } else { elves[elves.size - 1].calorieCount += parsedInt } if (addElf) { addElf = false elf = Elf() elves.add(elf) } } return elves } class Elf { var calorieCount: Int = 0 override fun toString(): String { return "Elf calories: $calorieCount" } } } fun main() { val runner = Solution() val input = Utils.readLines(runner, "input.txt", runner.javaClass.packageName) println("Solving first part of day 1") var start = LocalDateTime.now() println("Elf carrying the most calories has: ${input?.let { runner.part1(it) }} calories") var end = LocalDateTime.now() println("Solved first part of day 1") var milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve first part of day 1") println() println("Solving second part of day 1") start = LocalDateTime.now() println("The three elves carrying the most calories have ${input?.let { runner.part2(it) }} calories") end = LocalDateTime.now() println("Solved second part of day 1") milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve second part of day 1") }
0
Kotlin
0
0
db6b25f7668532f24d2737bc680feffc71342491
2,570
advent-of-code2022
MIT License
src/Day05.kt
CrazyBene
573,111,401
false
{"Kotlin": 50149}
import java.util.* fun main() { data class Instruction(val from: Int, val to: Int, val repeat: Int = 1) abstract class Crane { abstract fun performInstruction(state: List<Stack<Char>>, instruction: Instruction) } class CrateMover9000 : Crane() { override fun performInstruction(state: List<Stack<Char>>, instruction: Instruction) { for (i in 0 until instruction.repeat) { val crate = state[instruction.from].pop() state[instruction.to].push(crate) } } } class CrateMover9001 : Crane() { override fun performInstruction(state: List<Stack<Char>>, instruction: Instruction) { val poppedCrates = mutableListOf<Char>() for (i in 0 until instruction.repeat) { poppedCrates += state[instruction.from].pop() } for (crate in poppedCrates.reversed()) { state[instruction.to].push(crate) } } } class Cargo(initialState: String) { val state: List<Stack<Char>> init { state = mutableListOf() val numberOfStacks = initialState.last().toString().toInt() for (i in 0 until numberOfStacks) { val stack = Stack<Char>() initialState .split("\r\n") .reversed() .drop(1) .map { try { it[(i + 1) + i * 3] } catch (e: IndexOutOfBoundsException) { ' ' } } .filter { it != ' ' } .forEach { stack.push(it) } state += stack } } fun performInstruction(crane: Crane, instruction: Instruction) { crane.performInstruction(state, instruction) } fun getTopOfStacks(): String { return state.map { it.peek() }.joinToString("") } } fun String.toInstruction(): Instruction { val regex = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex() val result = regex.find(this) result?.groupValues?.get(0) ?: error("Can not map line $$this to instruction.") val repeat = result.groupValues[1].toInt() val from = result.groupValues[2].toInt() - 1 val to = result.groupValues[3].toInt() - 1 return Instruction(from, to, repeat) } fun String.toStateAndInstructions(): Pair<Cargo, List<Instruction>> { val (stateInput, instructionsInput) = this .split("\r\n\r\n") // windows needs \r\n splitting, instead of just \n .also { if (it.size != 2) error("Can not split into state and instructions.") } val state = Cargo(stateInput) val instructions = instructionsInput .split("\n") .map { it.toInstruction() } return state to instructions } fun part1(input: String): String { val (state, instructions) = input.toStateAndInstructions() val crane = CrateMover9000() instructions.forEach { state.performInstruction(crane, it) } return state.getTopOfStacks() } fun part2(input: String): String { val (state, instructions) = input.toStateAndInstructions() val crane = CrateMover9001() instructions.forEach { state.performInstruction(crane, it) } return state.getTopOfStacks() } val testInput = readInputAsText("Day05Test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputAsText("Day05") println("Question 1 - Answer: ${part1(input)}") println("Question 2 - Answer: ${part2(input)}") }
0
Kotlin
0
0
dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26
3,924
AdventOfCode2022
Apache License 2.0
src/Day10.kt
zirman
572,627,598
false
{"Kotlin": 89030}
fun main() { fun part1(input: List<String>): Int { return input .scan(listOf(1)) { signals, line -> val x = signals.last() val s = line.split(" ") when (s[0]) { "addx" -> listOf(x, x + s[1].toInt()) "noop" -> listOf(x) else -> throw Exception() } } .flatten() .mapIndexedNotNull { index, x -> when (index + 1) { 20, 60, 100, 140, 180, 220 -> x * (index + 1) else -> null } } .sum() } fun part2(input: List<String>): String { return input .scan(listOf(1)) { signals, line -> val x = signals.last() val s = line.split(" ") when (s[0]) { "addx" -> listOf(x, x + s[1].toInt()) "noop" -> listOf(x) else -> throw Exception() } } .flatten() .mapIndexed { index, x -> if (x in (index % 40) - 1..(index % 40) + 1) "#" else "." } .windowed(40, 40, false) .map { line -> line.joinToString("") { it } } .joinToString("\n") { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") println(part1(input)) check( part2(testInput) == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() ) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
1,945
aoc2022
Apache License 2.0
WordSearch.kt
ncschroeder
604,822,497
false
{"Kotlin": 19399}
/* https://leetcode.com/problems/word-search/ Given an m x n grid of characters `board` and a string `word`, return `true` if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: Input: board = [ ["A","B","C","E"], ["S","F","C","S"], ["A","F","E","E"] ] word = "ABCCEF" Output: true Explanation: Start at A in the 1st row and col, go right 2 cols to get the B and the C, go down 2 rows to get the C and the E, go left 1 col to get the F. */ fun exist(board: Array<CharArray>, word: String): Boolean { // canFormWord returns true if the param word starting at startIndex can be formed when starting at // startCoord in the grid and with all previously visited coords in visitedCoords fun canFormWord(startIndex: Int, startCoord: Pair<Int, Int>, visitedCoords: Set<Pair<Int, Int>>): Boolean { if (startIndex > word.lastIndex) { return true } val (row, col) = startCoord val newVisitedCoords: Set<Pair<Int, Int>> = visitedCoords + startCoord return arrayOf( Pair(row - 1, col), Pair(row, col + 1), Pair(row + 1, col), Pair(row, col - 1) ) .filter { otherCoord -> val (otherRow, otherCol) = otherCoord board.getOrNull(otherRow)?.getOrNull(otherCol) == word[startIndex] && otherCoord !in visitedCoords } .any { canFormWord(startIndex = startIndex + 1, startCoord = it, visitedCoords = newVisitedCoords) } } for (row in board.indices) { for (col in board.first().indices) { if (board[row][col] == word.first() && canFormWord(startIndex = 1, startCoord = Pair(row, col), visitedCoords = emptySet())) { return true } } } return false }
0
Kotlin
0
0
c77d0c8bb0595e61960193fc9b0c7a31952e8e48
1,999
Coding-Challenges
MIT License
src/Day06.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { line -> var marker = 0 for (i in 0..line.lastIndex - 3) { if (line.subSequence(i, i + 4).toSet().size == 4) { marker = i + 4 break } } marker } } fun part2(input: List<String>): Int { return input.sumOf { line -> var marker = 0 for (i in 0..line.lastIndex - 13) { if (line.subSequence(i, i + 14).toSet().size == 14) { marker = i + 14 break } } marker } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 39) check(part2(testInput) == 120) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
994
aoc-2022
Apache License 2.0
src/main/kotlin/io/github/lawseff/aoc2023/optimization/WinStrategyCounter.kt
lawseff
573,226,851
false
{"Kotlin": 37196}
package io.github.lawseff.aoc2023.optimization import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt class WinStrategyCounter { companion object { private const val MINUS_ONE = -1.0 } fun countWinStrategies(race: Race): Long { val minDistanceToWin = race.recordDistanceMillimeters + 1 // 1) We start with the 0 speed. Then we wait for X milliseconds, which allows us to have // the speed of X for the remaining of the race. The longer we wait, the higher the // starting speed is, but the less time we have to actually use it. // 2) So a winning strategy would be to wait for a relatively short amount of time X1, // getting a slower speed, but more time to run. Or to wait a relatively long amount of // time X2, thus getting a high speed, and less time to run. And all the strategies // in-between. // 3) Let's try to find a formula for X1 and X2. First, some variables // D - the required distance to beat the record; // T - the race time; // X1 - the shortest amount of time to wait before the start to win; // X2 - the longest amount of time to wait before the start to win; // TR - the remaining time after the waiting time. // The waiting time X is converted to the speed, so they are equal. // 4) Distance formula: // D = 0*X + X*TR; D = X * TR; // TR = T - X; // D = X * (T - X); D = X*T - X^2; // -X^2 + T*X - D = 0. // Now we get a quadratic equation with a = -1, b = T, C = -D. val times = solveQuadraticEquation( MINUS_ONE, race.timeMillis.toDouble(), MINUS_ONE * minDistanceToWin ) // Rounding up, because at this point the passed distance growths linearly with the X. // If we reduce the X by rounding, the distance is less, than required. val minWaitingTime = ceil(times.first).toLong() // Rounding down, because at this point the passed distance starts decreasing linearly. // If we increase the X by rounding, the distance is less, than required. val maxWaitingTime = floor(times.second).toLong() val numberOfStrategies = maxWaitingTime - minWaitingTime + 1 return numberOfStrategies } private fun solveQuadraticEquation(a: Double, b: Double, c: Double): Pair<Double, Double> { val discriminant = b * b - 4 * a * c if (discriminant < 0) { // No real roots throw IllegalArgumentException() } val root1 = (-b + sqrt(discriminant)) / (2 * a) val root2 = (-b - sqrt(discriminant)) / (2 * a) return Pair(root1, root2) } }
0
Kotlin
0
0
b60ab611aec7bb332b8aa918aa7c23a43a3e61c8
2,723
advent-of-code-2023
MIT License
src/main/kotlin/day13/Day13.kt
jankase
573,187,696
false
{"Kotlin": 70242}
package day13 import Day import safeTimes import solve typealias Signal = List<Any> class Day13 : Day(13, 2022, "Distress Signal") { override fun part1(): Int { val signalGroups = inputAsGroups.map { (firstSetOfSignals, secondSetOfSignals) -> Pair(firstSetOfSignals.toSignal(), secondSetOfSignals.toSignal()) } return signalGroups.mapIndexed { index, (left, right) -> if (left.compareTo(right) <= 0) index + 1 else 0 }.sum() } override fun part2(): Int { val allSignals = input.filter(onlyDataLines).map { it.toSignal() }.toMutableList() val signal2 = listOf(listOf<Any>(2)) val signal6 = listOf(listOf<Any>(6)) allSignals.add(signal2) allSignals.add(signal6) allSignals.sortWith { o1, o2 -> o1.compareTo(o2) } val indexOf2 = allSignals.indexOf(signal2) + 1 val indexOf6 = allSignals.indexOf(signal6) + 1 return indexOf2 safeTimes indexOf6 } private fun String.toSignal(): Signal { var workingString = removeSurrounding("[", "]") val stack = mutableListOf<MutableList<Any>>(mutableListOf()) val separators = listOf('[', ']', ',') while (workingString.isNotEmpty()) { val (newWorkingString, segment, separator) = workingString.dropTillSeparators(separators) workingString = newWorkingString if (segment.toIntOrNull() != null) stack.last().add(segment.toInt()) when (separator) { "[" -> stack.add(mutableListOf()) "]" -> { val closedList = stack.removeLast() stack.last().add(closedList) } } } return stack.single() } private fun String.dropTillSeparators(separators: List<Char>): Triple<String, String, String> { val newSegment = takeWhile { !separators.contains(it) } var newResult = removePrefix(newSegment) val separator = newResult.take(1) newResult = newResult.removePrefix(separator) return Triple(newResult, newSegment, separator) } @Suppress("KotlinConstantConditions", "UNCHECKED_CAST") private fun Signal.compareTo(other: Signal): Int { val leftIterator = this.iterator() val rightIterator = other.iterator() var nextLeft = leftIterator.nextOrNull() var nextRight = rightIterator.nextOrNull() while (nextRight != null || nextLeft != null) { val result = when { nextRight == null && nextLeft != null -> 1 nextRight != null && nextLeft == null -> -1 nextRight is Int && nextLeft is Int -> nextLeft.compareTo(nextRight) nextLeft is Int && nextRight !is Int -> listOf<Any>(nextLeft).compareTo(nextRight as Signal) nextLeft !is Int && nextRight is Int -> (nextLeft as Signal).compareTo(listOf(nextRight)) else -> (nextLeft as Signal).compareTo(nextRight as Signal) } if (result != 0) return result nextLeft = leftIterator.nextOrNull() nextRight = rightIterator.nextOrNull() } return 0 } private fun <T> Iterator<T>.nextOrNull(): T? = if (hasNext()) next() else null } fun main() { solve<Day13> { day13Demo part1 13 part2 140 } } val day13Demo = """ [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()
0
Kotlin
0
0
0dac4ec92c82a5ebb2179988fb91fccaed8f800a
3,678
adventofcode2022
Apache License 2.0
puzzles/src/main/kotlin/com/kotlinground/puzzles/search/binarysearch/searchrotatedsortedarray/rotatedSortedArray.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.search.binarysearch.searchrotatedsortedarray fun search(nums: IntArray, target: Int): Int { var left = 0 var right = nums.size - 1 while (left <= right) { val middle = (left + right) / 2 if (nums[middle] == target) { return middle } // we search the left sorted portion if (nums[left] <= nums[middle]) { // if our target is greater than our middle value or less than the left most value, then we need to move our // left pointer to the middle plus 1, this means our target is in the right sorted portion if (target > nums[middle] || target < nums[left]) { left = middle + 1 } else { // if not, we move our right pointer to the middle. Meaning our target is in the left sorted portion right = middle - 1 } } // right sorted portion else { // else our target is in the right sorted portion. We check if the target is less than our middle or our // target is greater than our right most value. Then we move to the left portion by moving our right pointer // to the middle value if (target < nums[middle] || target > nums[right]) { right = middle - 1 } else { // Move our left to the middle position if our target is greater than middle value or less than right // most value left = middle + 1 } } } return -1 } /** * Performs a search of target in the nums list that is already sorted in non-decreasing order(that is increasing) * & does not contain distinct values. Nums has been rotated at an unknown pivot index * @param nums [IntArray] list of integers sorted in non-decreasing order with non-distinct values rotated at an unknown * pivot * @param target [Int]: number being sought for in nums. * @return [Boolean] True if the target can be found in the nums list, False otherwise */ fun searchWithDuplicates(nums: IntArray, target: Int): Boolean { var left = 0 var right = nums.size - 1 while (left <= right) { val middle = (left + right) / 2 // we have found the target in the middle if (nums[middle] == target) { return true } // we search the left sorted portion else if (nums[left] < nums[middle]) { // if our target is greater than a left value and less than the middle value then we need to move our // right pointer to the middle - 1(right before the midpoint) else we move left pointer to the middle plus 1, if (nums[left] <= target && target < nums[middle]) { // this means our target is in the left sorted portion right = middle - 1 } else { // this means our target is in the right sorted portion left = middle + 1 } } // right sorted portion else if (nums[left] > nums[middle]) { // if the target greater than the middle value and less than or equal to a right value. Then the left pointer // is moved to the middle +1(right after the middle), denoting that the search should be happening on the // right. Else we move the right pointer to the left i.e. middle - 1(right before the middle) e if (nums[middle] < target && target <= nums[right]) { // search the right section left = middle + 1 } else { // search the left section right = middle - 1 } } else { // if neither a left value is greater than the middle value nor less than the middle value, we move the // pointer to the right by 1 step. left += 1 } } return false }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
3,954
KotlinGround
MIT License
src/main/kotlin/be/inniger/euler/problems01to10/Problem09.kt
bram-inniger
135,620,989
false
{"Kotlin": 20003}
package be.inniger.euler.problems01to10 private const val TRIPLET_SUM = 1000 /** * Special Pythagorean triplet * * A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, * a^2 + b^2 = c^2 * For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. * There exists exactly one Pythagorean triplet for which a + b + c = 1000. * Find the product abc. */ fun solve09() = (1..TRIPLET_SUM) .flatMap { a -> (1..TRIPLET_SUM).map { b -> PythagoreanTriplet(a, b, TRIPLET_SUM - a - b) } } .first(PythagoreanTriplet::valid) .prod private data class PythagoreanTriplet(val a: Int, val b: Int, val c: Int) { internal val valid = a > 0 && b > 0 && c > 0 && a * a + b * b == c * c internal val prod = a * b * c }
0
Kotlin
0
0
8fea594f1b5081a824d829d795ae53ef5531088c
775
euler-kotlin
MIT License
2023/src/main/kotlin/day13.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.Parser import utils.Solution import utils.mapItems import utils.flipAxis fun main() { Day13.run() } object Day13 : Solution<List<Grid<Char>>>() { override val name = "day13" override val parser = Parser.blocks.mapItems { Parser.charGrid(it) } private fun reflects(g: Grid<Char>, x: Int, errors: Int): Boolean { val len = minOf(x, g.width - x) return (0 until len).sumOf { g[x - it - 1].values.zip(g[x + it].values).count { (a, b) -> a != b } } == errors } private fun solve(errors: Int = 0): Int { return input.sumOf { line -> listOf(line to 1, line.flipAxis() to 100).sumOf { (g, mul) -> (1 until g.width).sumOf { if (reflects(g, it, errors)) it else 0 } * mul } } } override fun part1() = solve() override fun part2() = solve(errors = 1) }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
843
aoc_kotlin
MIT License
src/questions/MinTotalInTriangle.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import kotlin.math.min /** * Given a triangle array, return the minimum path sum from top to bottom. * For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the * current row, you may move to either index i or index i + 1 on the next row. * * [Source](https://leetcode.com/problems/triangle/) */ @UseCommentAsDocumentation fun minimumTotal(triangle: List<List<Int>>): Int { val minCumulativeSumTriangle = MutableList<MutableList<Int?>>(triangle.size) { MutableList(it + 1) { null } } minCumulativeSumTriangle[0][0] = triangle[0][0] // initialize for (row in 1..triangle.lastIndex) { for (col in 0..triangle.last().lastIndex) { val currentValue = triangle.getOrNull(row)?.getOrNull(col) ?: continue // get previous row's col-1 and col // then sum it with currentValue // take the minimum of the two val minCumulativeSumYet = min( minCumulativeSumTriangle[row - 1].getOrNull(col)?.plus(currentValue) ?: Int.MAX_VALUE, minCumulativeSumTriangle[row - 1].getOrNull(col - 1)?.plus(currentValue) ?: Int.MAX_VALUE ) minCumulativeSumTriangle[row][col] = minCumulativeSumYet } } // answer is minimum value in the last row return minCumulativeSumTriangle.last().filterNotNull().minOrNull()!! } fun main() { minimumTotal(listOf(listOf(2), listOf(3, 4), listOf(6, 5, 7), listOf(4, 1, 8, 3))) shouldBe 11 minimumTotal(listOf(listOf(-10))) shouldBe -10 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,660
algorithms
MIT License
2023/src/main/kotlin/day4.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parse import utils.Parser import utils.Solution import utils.mapItems import utils.pow2 fun main() { Day4.run(skipTest = false) } object Day4 : Solution<List<Day4.Card>>() { override val name = "day4" override val parser = Parser.lines.mapItems { parseCard(it) } @Parse("Card {id}: {r ' ' winning} | {r ' ' numbers}") data class Card( val id: Int, val winning: List<Int>, val numbers: List<Int>, ) { val score: Pair<Int, Int> get() { val count = (winning.toSet() intersect numbers.toSet()).count() val score = if (count == 0) 0 else pow2(count - 1) return count to score } } override fun part1(input: List<Card>): Int { return input.sumOf { it.score.second } } override fun part2(input: List<Card>): Int { if (input.isEmpty()) { return 0 } val card = input.first() val count = input.count { it.id == card.id } val (winCount, _) = card.score // add extra cards val next = input.filter { it.id != card.id } + (1 .. count).flatMap { input.subList(1, winCount + 1) } return count + part2(next) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,115
aoc_kotlin
MIT License
src/main/kotlin/cz/tomasbublik/Day06.kt
tomasbublik
572,856,220
false
{"Kotlin": 21908}
package cz.tomasbublik import java.util.LinkedList import java.util.Queue fun String.allUnique(): Boolean = all(hashSetOf<Char>()::add) fun Queue<Char>.allUnique(): Boolean = all(hashSetOf<Char>()::add) fun main() { fun allCharsDifferent(nums: Queue<Char>): Boolean { return nums.allUnique() } fun calculateArrayOfMarkers( input: List<String>, markerlength: Int ): ArrayList<Int> { val arrayOfMarkers = ArrayList<Int>() for (line in input) { val nums: Queue<Char> = LinkedList<Char>() for (charIndex in line.indices) { if (nums.size == markerlength) { nums.remove() } nums.add(line[charIndex]) if (nums.size == markerlength) { if (allCharsDifferent(nums)) { arrayOfMarkers.add(charIndex + 1) break } } } } return arrayOfMarkers } fun part1(input: List<String>): List<Int> { val markerLength = 4 return calculateArrayOfMarkers(input, markerLength) } fun part2(input: List<String>): List<Int> { val markerLength = 14 val arrayOfMarkers = calculateArrayOfMarkers(input, markerLength) return arrayOfMarkers } // test if implementation meets criteria from the description, like: val testInput = readFileAsLinesUsingUseLines("src/main/resources/day_6_input_test") check(part1(testInput) == listOf(7, 5, 6, 10, 11)) check(part2(testInput) == listOf(19, 23, 23, 29, 26)) val input = readFileAsLinesUsingUseLines("src/main/resources/day_6_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c26a93e8f6f7ab0f260c75a287608dd7218d0f0
1,778
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader fun main() { val testInput = """ 2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8 """.trimIndent() check(partOne(testInput.reader()) == 2) val input = file("Day04.txt") println(partOne(input.bufferedReader())) check(partTwo(testInput.reader()) == 4) println(partTwo(input.bufferedReader())) } private fun partOne(source: Reader): Int { var fullyCountains = 0 source.forEachLine { line -> val (a, b) = line.split(',') val (aMin, aMax) = a.split('-').map { it.toInt() } val (bMin, bMax) = b.split('-').map { it.toInt() } val aNumbers = (aMin..aMax).toSet() val bNumbers = (bMin..bMax).toSet() if (aNumbers.containsAll(bNumbers) || bNumbers.containsAll(aNumbers)) { fullyCountains++ } } return fullyCountains } private fun partTwo(source: Reader): Int { var overlaps = 0 source.forEachLine { line -> val (a, b) = line.split(',') val (aMin, aMax) = a.split('-').map { it.toInt() } val (bMin, bMax) = b.split('-').map { it.toInt() } val aNumbers = (aMin..aMax).toSet() val bNumbers = (bMin..bMax).toSet() val intersect = aNumbers.intersect(bNumbers) if (intersect.isNotEmpty()) { overlaps++ } } return overlaps }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
1,391
advent-of-code-2022-kotlin
Apache License 2.0
src/algorithms/PopularChaAlgorithm.kt
aaronoe
186,243,764
false
null
package de.aaronoe.algorithms import de.aaronoe.models.Seminar import de.aaronoe.models.Student import org.jgrapht.alg.matching.HopcroftKarpMaximumCardinalityBipartiteMatching import org.jgrapht.graph.DefaultEdge import org.jgrapht.graph.SimpleGraph object PopularChaAlgorithm : StudentMatchingAlgorithm { override suspend fun execute(students: List<Student>, seminars: List<Seminar>): Map<Seminar, List<Student>> { data class MapResult( val students: List<Student>, val seminar: Seminar, val hasCapacityLeft: Boolean ) { override fun toString(): String { return "${seminar.name} - $hasCapacityLeft" } } val houseCapacityOverview = students.groupBy { it.preferences.first() } val matchedStudents = houseCapacityOverview .mapValues { MapResult(it.value, it.key, it.value.count() <= it.key.capacity) } .filter { it.value.hasCapacityLeft } .flatMap { it.value.students } .also { it.forEach { student -> student.match = student.preferences.first().also { it.assignments.add(student) } } } val unmatchedStudents = students - matchedStudents val availableSeminars = seminars.filter(Seminar::canAssignMore).toHashSet() val graph = SimpleGraph<String, DefaultEdge>(DefaultEdge::class.java) unmatchedStudents.forEach { graph.addVertex(it.id) } // map of new id's with suffix to original seminar val idSeminarMap = mutableMapOf<String, Seminar>() val seminarMap = availableSeminars.map { seminar -> seminar to (0 until (seminar.capacity - seminar.assignments.size)).map { val newId = "${seminar.id}$$it" idSeminarMap[newId] = seminar seminar.copy(id = newId) } }.toMap().toMutableMap() seminarMap.forEach { (_, list) -> list.forEach { graph.addVertex(it.id) } } // create f and s houses for students val studentPrefs = unmatchedStudents.map { val fHouse = it.preferences.first() val sHouse = it.preferences.firstOrNull { it != fHouse && houseCapacityOverview[it]!!.size < it.capacity } ?: Seminar("l-house_${it.id}", 1).also { seminarMap[it] = listOf(it) // last resort house idSeminarMap[it.id] = it graph.addVertex(it.id) } it to (fHouse to sHouse) } studentPrefs.forEach { (student, prefs) -> prefs.toList().forEach { seminarMap.getValue(it).forEach { graph.addEdge(student.id, it.id) } } } val algorithm = HopcroftKarpMaximumCardinalityBipartiteMatching<String, DefaultEdge>( graph, unmatchedStudents.map { it.id }.toSet(), seminarMap.flatMap { it.value.map { it.id } }.toSet() ) val studentMap = unmatchedStudents.associateBy { it.id } val matching = algorithm.matching println("IsPerfect: ${matching.edges.size == unmatchedStudents.size}") matching.edges.forEach { edge -> val student = studentMap[graph.getEdgeSource(edge)]!! val seminar = idSeminarMap[graph.getEdgeTarget(edge)]!! seminar.assignments.add(student) } students.forEach { student -> val match = seminars.firstOrNull { it.assignments.contains(student) } val index = student.preferences.indexOf(match) (0 until index).forEach { if (student.preferences[it].canAssignMore) { println("Opt possible") } } } println("Done Opt") return seminars.map { it to it.assignments.toList() }.toMap() } }
0
Kotlin
0
1
8265e6553aca23c3bf2c5236ba56d46ab7e2b3f3
4,061
matching_server
MIT License
atcoder/arc159/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc159 fun main() { readInt() val a = readInts().toIntArray() val ans = mutableListOf<IntArray>() fun apply(p: IntArray) { for (i in a.indices) a[i] += p[i] ans.add(p) } var sumOk = false for (j in a.indices) { if (a.sum() % a.size == 0) { sumOk = true break } val b = a.indices.sortedBy { a[it] } val p = IntArray(a.size) for (i in a.indices) p[b[i]] = a.size - 1 - i apply(p) } if (!sumOk) return println("No") println("Yes") while (true) { val delta = a.sum() / a.size for (i in a.indices) a[i] -= delta val x = a.indexOf(a.max()!!) if (a[x] == 0) break val y = a.indexOf(a.min()!!) val k = minOf(a[x], -a[y], a.size - 1) val p = IntArray(a.size) { -1 } p[y] = 0 p[x] = k var t = 1 for (i in p.indices) { if (p[i] >= 0) continue if (t == k) t++ p[i] = t++ } val q = IntArray(a.size) { a.size - 1 - p[it] } p[y] = k p[x] = 0 apply(q) apply(p) } println(ans.size) println(ans.joinToString("\n") { p -> p.joinToString(" ") { (it + 1).toString() } }) } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,236
competitions
The Unlicense
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[74]搜索二维矩阵.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: // // // 每行中的整数从左到右按升序排列。 // 每行的第一个整数大于前一行的最后一个整数。 // // // // // 示例 1: // // //输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 //输出:true // // // 示例 2: // // //输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 //输出:false // // // // // 提示: // // // m == matrix.length // n == matrix[i].length // 1 <= m, n <= 100 // -104 <= matrix[i][j], target <= 104 // // Related Topics 数组 二分查找 矩阵 // 👍 475 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { //方法一 暴力破解 时间复杂度 O(m*n) //遍历数组 /* var all = ArrayList<Int>() matrix.forEach { IntArray-> IntArray.forEach { all.add(it) } } all.forEach { if (target == it) return true } return false*/ //方法二 二分查找 if(matrix.isEmpty() || matrix[0].isEmpty())return false var row = matrix.size var col = matrix[0].size var left = 0 var right = row * col -1 while (left <= right){ var mid = left + (right - left)/2 var midVal = matrix[mid/col][mid%col] if(midVal <target){ left = mid+1 }else if(midVal > target){ right = mid -1 }else{ return true } } return false } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,853
MyLeetCode
Apache License 2.0
src/Day01.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
fun main() { fun List<String>.calcSums(): List<Int> { val sums = mutableListOf<Int>() sums.add(0) for (line in this) { if (line == "") { sums.add(0) } else { sums[sums.lastIndex] += line.toInt() } } return sums } fun List<Int>.topSum(n: Int): Int { return sortedDescending().take(n).sum() } fun part1(input: List<String>): Int { return input.calcSums().topSum(1) } fun part2(input: List<String>): Int { return input.calcSums().topSum(3) } check(part1(readInput("Day01_test")) == 24000) check(part2(readInput("Day01_test")) == 45000) println(part1(readInput("Day01"))) println(part2(readInput("Day01"))) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
790
aoc-2022
Apache License 2.0
src/day01/Day01.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day01 import readInput fun main() { data class Elf(val calories: Int) fun parseElves(input: List<String>): List<Elf> { val elves = mutableListOf<Elf>() var currentElf = Elf(0) input.forEach { when { it.isEmpty() -> elves.add(currentElf.copy()).also { currentElf = Elf(0) } else -> currentElf = currentElf.copy(calories = currentElf.calories + it.toInt()) } } elves.add(currentElf) return elves } fun part1(input: List<String>): Int = parseElves(input).maxBy { it.calories }.calories fun part2(input: List<String>): Int = parseElves(input).sortedByDescending { it.calories }.take(3).sumOf { it.calories } // test if implementation meets criteria from the description, like: val testInput = readInput("/day01/Day01_test") check(part1(testInput) == 24000) val input = readInput("/day01/Day01") println(part1(input)) println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
1,053
advent-of-code
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day07.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day07 : Day<Long> { private val containerRegex = Regex("^([a-z ]+) bags contain .+$") private val contentsRegex = Regex(" ([0-9]+) ([a-z ]+) bags?[,.]") private val rules = readDayInput() .lineSequence() .parse() data class Rule(val color: String, val contents: List<Content>) { data class Content(val count: Int, val color: String) } private fun Sequence<String>.parse(): Sequence<Rule> = map { rule -> val nameResult = containerRegex.find(rule)!! val contentsResult = contentsRegex.findAll(rule) Rule( color = nameResult.groupValues[1], contents = contentsResult.map { res -> Rule.Content( count = res.groupValues[1].toInt(), color = res.groupValues[2] ) }.toList() ) } data class Bag(val color: String, var contents: List<Content> = emptyList()) { data class Content(val count: Int, val bag: Bag) val size: Long get() = 1 + contents.sumOf { (count, bag) -> count * bag.size } fun contains(bag: Bag): Boolean = when { contents.any { (_, containedBag) -> containedBag == bag } -> true else -> contents.any { (_, containedBag) -> containedBag.contains(bag) } } } private val bags = rules.map { rule -> rule.color to Bag(color = rule.color) }.toMap() private fun bagByColor(color: String): Bag = bags[color]!! init { // Initialize bag contents rules.forEach { rule -> bagByColor(rule.color).apply { contents = rule.contents.map { (count, color) -> Bag.Content( count = count, bag = bagByColor(color) ) } } } } override fun step1(): Long { val target = bagByColor("shiny gold") return bags.values.count { bag -> bag.contains(target) }.toLong() } override fun step2(): Long { val target = bagByColor("shiny gold") return target.size - 1 } override val expectedStep1: Long = 332 override val expectedStep2: Long = 10875 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,430
adventofcode
Apache License 2.0
src/Day02.kt
pejema
576,456,995
false
{"Kotlin": 7994}
import kotlin.streams.toList fun main() { fun getPointsPart1(elfShape: String, myShape: String) : Int { var points = 0 if (elfShape == "A" && myShape == "X") { points = 1 + 3 } else if (elfShape == "A" && myShape == "Y") { points = 2 + 6 } else if (elfShape == "A" && myShape == "Z") { points = 3 } else if (elfShape == "B" && myShape == "X") { points = 1 } else if (elfShape == "B" && myShape == "Y") { points = 2 + 3 } else if (elfShape == "B" && myShape == "Z") { points = 3 + 6 } else if (elfShape == "C" && myShape == "X") { points = 1 + 6 } else if (elfShape == "C" && myShape == "Y") { points = 2 } else if (elfShape == "C" && myShape == "Z") { points = 3 + 3 } return points } fun getPointsPart2(elfShape: String, myShape: String) : Int { var points = 0 if (elfShape == "A" && myShape == "X") { points = 3 } else if (elfShape == "A" && myShape == "Y") { points = 1 + 3 } else if (elfShape == "A" && myShape == "Z") { points = 2 + 6 } else if (elfShape == "B" && myShape == "X") { points = 1 } else if (elfShape == "B" && myShape == "Y") { points = 2 + 3 } else if (elfShape == "B" && myShape == "Z") { points = 3 + 6 } else if (elfShape == "C" && myShape == "X") { points = 2 } else if (elfShape == "C" && myShape == "Y") { points = 3 + 3 } else if (elfShape == "C" && myShape == "Z") { points = 1 + 6 } return points } /* * First column: A for Rock, B for Paper, and C for Scissors. * Second column: X for Rock, Y for Paper, and Z for Scissors. * The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) * plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). * */ fun part1(input: List<String>): Int { return input.stream() .map { line -> line.split(" ") } .map { shapes -> getPointsPart1(shapes[0], shapes[1]) } .toList().sum() } /* * First column: A for Rock, B for Paper, and C for Scissors. * Second column: X you lose: 0 points, Y you draw: 3 points, and Z you win: 6 points. * The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) * plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). * */ fun part2(input: List<String>): Int { return input.stream() .map { line -> line.split(" ") } .map { shapes -> getPointsPart2(shapes[0], shapes[1]) } .toList().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") part1(input).println() part2(input).println() }
0
Kotlin
0
0
b2a06318f0fcf5c6067058755a44e5567e345e0c
3,282
advent-of-code
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent/day4/Day4.kt
michaelbull
225,205,583
false
null
package com.github.michaelbull.advent.day4 fun readRange(): IntRange { return ClassLoader.getSystemResourceAsStream("day4.txt") .bufferedReader() .readLine() .split("-") .map(String::toInt) .let { IntRange(it[0], it[1]) } } fun IntRange.validPasswords(criteria: (Int) -> Boolean): Int { return filter(criteria).size } fun part1(password: Int): Boolean { return password.digitsIncreaseLtr() && password.hasTwoAdjacentDigits() } fun part2(password: Int): Boolean { return password.digitsIncreaseLtr() && password.hasOnlyTwoAdjacentDigits() } private fun Int.hasTwoAdjacentDigits(): Boolean { val string = toString() for (i in 0 until string.length - 1) { val currChar = string[i] val nextChar = string[i + 1] if (currChar == nextChar) { return true } } return false } private fun Int.digitsIncreaseLtr(): Boolean { val string = toString() for (i in 0 until string.length - 1) { val currDigit = string[i].toInt() val nextDigit = string[i + 1].toInt() if (nextDigit < currDigit) { return false } } return true } private fun Int.hasOnlyTwoAdjacentDigits(): Boolean { val string = toString() for (i in 0 until string.length - 1) { val currChar = string[i] val nextChar = string[i + 1] if (currChar == nextChar) { val withinGroup = i > 0 && currChar == string[i - 1] val joiningGroup = i < string.length - 2 && currChar == string[i + 2] if (!withinGroup && !joiningGroup) { return true } } } return false } fun main() { val range = readRange() println("part 1 = ${range.validPasswords(::part1)}") println("part 2 = ${range.validPasswords(::part2)}") }
0
Kotlin
0
2
d271a7c43c863acd411bd1203a93fd10485eade6
1,863
advent-2019
ISC License
src/main/kotlin/Puzzle11.kt
namyxc
317,466,668
false
null
object Puzzle11 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle11::class.java.getResource("puzzle11.txt").readText() val calculateOccupiedSeats = calculateOccupiedSeats(input, Puzzle11::countImmediatelyAdjacentSeats, 4) println(calculateOccupiedSeats) val calculateOccupiedSeatsVisible = calculateOccupiedSeats(input, Puzzle11::countVisibleAdjacentSeats, 5) println(calculateOccupiedSeatsVisible) } fun calculateOccupiedSeats(input: String, counter: (i: Int, rows: Int, j: Int, cols: Int, input: List<CharArray>) -> Int, minOccupiedToLeave: Int): Int { var arrayWithResult = Pair(inputToArrayLists(input), true) while (arrayWithResult.second){ arrayWithResult = applyRules(arrayWithResult.first, counter, minOccupiedToLeave) } return arrayWithResult.first.sumOf { line -> line.count { it == '#' } } } private fun applyRules( input: List<CharArray>, counter: (i: Int, rows: Int, j: Int, cols: Int, input: List<CharArray>) -> Int, minOccupiedToLeave: Int ): Pair<List<CharArray>, Boolean> { val rows = input.size val cols = input.first().size val output = List(rows) {CharArray(cols)} var changed = false for (row in 0 until rows){ for (col in 0 until cols){ val countOccupied = counter(row, rows, col, cols, input) if (input[row][col] == 'L'){ if (countOccupied == 0){ output[row][col] = '#' changed = true }else{ output[row][col] = 'L' } }else if (input[row][col] == '#'){ if (countOccupied >= minOccupiedToLeave){ output[row][col] = 'L' changed = true }else{ output[row][col] = '#' } }else{ output[row][col] = '.' } } } return Pair(output, changed) } fun countImmediatelyAdjacentSeats(i: Int, rows: Int, j: Int, cols: Int, input: List<CharArray>): Int { var countOccupied = 0 for (x in -1..1) for (y in -1..1) { if ( (x != 0 || y != 0) && i + x >= 0 && i + x <= rows - 1 && j + y >= 0 && j + y <= cols - 1 && input[i + x][j + y] == '#' ) { countOccupied++ } } return countOccupied } fun countVisibleAdjacentSeats(row: Int, rows: Int, col: Int, cols: Int, input: List<CharArray>): Int { var countOccupied = 0 for (dCol in -1..1) { var currentCol = col + dCol if (currentCol in 0 until cols) { for (dRow in -1..1) { if (dCol != 0 || dRow != 0) { var currentRow = row + dRow currentCol = col + dCol while (currentCol in 0 until cols && currentRow in 0 until rows && input[currentRow][currentCol] == '.') { currentCol += dCol currentRow += dRow } if (currentCol in 0 until cols && currentRow in 0 until rows && input[currentRow][currentCol] == '#') { countOccupied++ } } } } } return countOccupied } private fun inputToArrayLists(input: String): List<CharArray> { return input.split("\n").map { it.toCharArray() } } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
3,868
adventOfCode2020
MIT License
src/main/kotlin/Day06.kt
arosenf
726,114,493
false
{"Kotlin": 40487}
import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.isEmpty() or (args.size < 2)) { println("Almanac not specified") exitProcess(1) } val fileName = args.first() println("Reading $fileName") val lines = readLines(fileName).toList() val result = if (args[1] == "part1") { val times = splitDay06Part1(lines[0]) val distances = splitDay06Part1(lines[1]) Day06().findMarginOfError(times, distances) } else { val times = splitDay06Part2(lines[0]) val distances = splitDay06Part2(lines[1]) Day06().findMarginOfError(times, distances) } println("Result: $result") } private val delimiterDay06 = "\\s+".toRegex() fun splitDay06Part1(line: String): List<Long> { return line.substringAfter(':') .trim() .split(delimiterDay06) .map(String::toLong) } fun splitDay06Part2(line: String): List<Long> { return listOf( line.substringAfter(':') .replace(delimiterDay06, "") .toLong() ) } class Day06 { fun findMarginOfError(times: List<Long>, distances: List<Long>): Int { return times.zip(distances) .map { (time, distance) -> (distancesForMs(time) to distance) } .map { (times, distance) -> times.filter { time -> time > distance } } .map { recordTimes -> recordTimes.count() } .reduce { x, y -> x * y } } private fun distancesForMs(ms: Long): Sequence<Long> { return generateSequence(1) { if (it < ms) it + 1 else null } .map { (ms - it) * it } } }
0
Kotlin
0
0
d9ce83ee89db7081cf7c14bcad09e1348d9059cb
1,665
adventofcode2023
MIT License
leetcode2/src/leetcode/find-all-numbers-disappeared-in-an-array.kt
hewking
68,515,222
false
null
package leetcode import java.util.* /**448. 找到所有数组中消失的数字 * https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/ * Created by test * Date 2019/7/17 0:56 * Description *给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 示例: 输入: [4,3,2,7,8,2,3,1] 排序后: [1,2,2,3,3,4,7,8] 输出: [5,6] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object FindAllNumbersDisappearedInAnArray { @JvmStatic fun main(args:Array<String>) { } class Solution { fun findDisappearedNumbers(nums: IntArray): List<Int> { val result = mutableListOf<Int>() Arrays.sort(nums) for (i in 1..nums.size) { if (Arrays.binarySearch(nums, i) < 0) { result.add(i) } } return result } /** * 思路: * 置所有数组正整数值为下标,把所有值作为下标的值设 * 为负数, */ fun findDisappearedNumbers3(nums: IntArray): List<Int> { val result = mutableListOf<Int>() for (i in 0 until nums.size) { var index = Math.abs(nums[i]) -1 nums[index] = - Math.abs(nums[index]) } for (i in 0 until nums.size) { if (nums[i] > 0) { result.add(i + 1) } } return result } // fun findDisappearedNumbers2(nums: IntArray): List<Int> { // val result = mutableListOf<Int>() // Arrays.sort(nums) // var curIndex = 0 // for (i in 1..nums.size) { // if (i == nums[curIndex]) { // curIndex++ // continue // } else if (i > nums[curIndex]) { // while (i > nums[curIndex]) { // curIndex++ // } // } else if (i < nums[curIndex]) { // result.add(nums[i - 1]) // } // } // return result // } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,638
leetcode
MIT License
2022/23/23.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
typealias Point = Pair<Int, Int> val DIRS8 = listOf(-1 to -1, -1 to 0, -1 to 1, 0 to 1, 1 to 1, 1 to 0, 1 to -1, 0 to -1) val DIRS = mutableListOf( listOf(DIRS8[0], DIRS8[1], DIRS8[2]), // N listOf(DIRS8[4], DIRS8[5], DIRS8[6]), // S listOf(DIRS8[6], DIRS8[7], DIRS8[0]), // E listOf(DIRS8[2], DIRS8[3], DIRS8[4]), // W ) fun main() { val input = generateSequence(::readlnOrNull) .flatMapIndexed { y, row -> row.mapIndexed { x, v -> (y to x) to v } } .filter { it.second == '#' } .map { it.first } .toMutableSet() var round = 0 while (true) { val proposals: MutableMap<Point, MutableList<Point>> = mutableMapOf() for ((y, x) in input) { val adj = DIRS.map { it.map { (ya, xa) -> y+ya to x+xa } } if (adj.flatten().count { input.contains(it) } > 0) for (dirs in adj) { if (dirs.count { input.contains(it) } > 0) continue if (dirs[1] !in proposals) proposals[dirs[1]] = mutableListOf() proposals[dirs[1]]!!.add(y to x) break } } for ((point, candidates) in proposals) { if (candidates.size == 1) { input.remove(candidates[0]) input.add(point) } } DIRS.add(DIRS.removeAt(0)) round++ if (round == 10) { val minY = input.minOf { it.first } val minX = input.minOf { it.second } val maxY = input.maxOf { it.first } val maxX = input.maxOf { it.second } println((maxY - minY + 1) * (maxX - minX + 1) - input.size) } if (proposals.isEmpty()) break } println(round) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,836
adventofcode
Apache License 2.0
src/Day01.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { fun calculateElvesCalories(input: List<String>): List<Int> { val elvesCalories = arrayListOf<Int>() var currentElfCalories = 0 input.forEach { if (it.isEmpty()) { elvesCalories.add(currentElfCalories) currentElfCalories = 0 } else { currentElfCalories += it.toInt() } } elvesCalories.add(currentElfCalories) return elvesCalories } fun part1(input: List<String>): Int { val elvesCalories = calculateElvesCalories(input) return elvesCalories.max() } fun part2(input: List<String>): Int { val elvesCalories = calculateElvesCalories(input) return elvesCalories.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
1,040
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/aoc/Day9.kt
dtsaryov
573,392,550
false
{"Kotlin": 28947}
package aoc import kotlin.math.abs import kotlin.math.hypot /** * [AoC 2022: Day 9](https://adventofcode.com/2022/day/9) */ fun getRopeTailPositionsCount(moves: List<String>, length: Int): Int { val points = IntRange(0, length - 1) .map { Point(1, 1) } .toTypedArray() var head: Point var tail: Point val positions = mutableSetOf(points[0]) for (move in moves) { val (direction, distance) = parseMove(move) for (d in 1..distance) { head = points[0] head = moveHead(head, direction) points[0] = head for (i in 1 until points.size) { tail = points[i] if (shouldMoveTail(head, tail)) { tail = moveTail(tail, head) points[i] = tail if (i == length - 1) { positions += tail } } head = points[i] } } } return positions.size } private fun moveHead(head: Point, direction: Direction): Point { return when (direction) { Direction.UP -> Point(head.x, head.y + 1) Direction.RIGHT -> Point(head.x + 1, head.y) Direction.DOWN -> Point(head.x, head.y - 1) Direction.LEFT -> Point(head.x - 1, head.y) } } private fun parseMove(move: String): Move { val (direction, distance) = move.split(" ") return Move(Direction.fromKey(direction), distance.toInt()) } private fun shouldMoveTail(head: Point, tail: Point): Boolean { val (hx, hy) = head val (tx, ty) = tail return hypot((hx - tx).toDouble(), (hy - ty).toDouble()) >= 2 } private fun moveTail(tail: Point, head: Point): Point { val (tx, ty) = tail val (hx, hy) = head var dx = 0 var dy = 0 if (tx == hx) { dy = pointNearby(hy, ty) } else if (ty == hy) { dx = pointNearby(hx, tx) } else { if (abs(hx - tx) < abs(hy - ty)) { dx = hx - tx dy = pointNearby(hy, ty) } else if (abs(hx - tx) > abs(hy - ty)) { dx = pointNearby(hx, tx) dy = hy - ty } else { dx = pointNearby(hx, tx) dy = pointNearby(hy, ty) } } return Point(tx + dx, ty + dy) } private fun pointNearby(h: Int, t: Int): Int = h - t - sign(h - t) private fun sign(n: Int): Int = if (n >= 0) 1 else -1 private data class Move(val direction: Direction, val distance: Int) private data class Point(val x: Int, val y: Int) private enum class Direction { UP, RIGHT, DOWN, LEFT; companion object { fun fromKey(key: String): Direction { return values().find { it.name.startsWith(key) }!! } } }
0
Kotlin
0
0
549f255f18b35e5f52ebcd030476993e31185ad3
2,757
aoc-2022
Apache License 2.0