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/days/Day19.kt
hughjdavey
225,440,374
false
null
package days import common.IntcodeComputer import common.stackOf class Day19 : Day(19) { private fun program() = inputString.split(",").map { it.trim().toLong() }.toMutableList() override fun partOne(): Any { val tractorPoints = getTractorPoints(49, 49) return tractorPoints.count { it.pulled } } // todo this takes 18s on my machine - speed up override fun partTwo(): Any { System.err.println("Part 2 takes around 20s... result is coming") // will need about 100 + half again hashes to be able to fit the square as the beam leans away // skip 5 rows at a time for performance as this doesn't need to be too accurate var y = generateSequence(0L) { it + 5 }.map { getTractorPointsRow(it) }.indexOfFirst { it.count { it.pulled } > 150 } * 5L val closestToEmitter: Pair<Long, Long>? while (true) { val row = getTractorPointsRow(++y) val lastHashInRow = row.findLast { it.pulled } if (lastHashInRow != null) { val hashX = lastHashInRow.coord.first val rowPlus100 = getTractorPointsRow(y + 99) if (rowPlus100[hashX.toInt()].pulled && rowPlus100[hashX.toInt() - 99].pulled) { closestToEmitter = lastHashInRow.coord.first - 99 to lastHashInRow.coord.second break } } } return closestToEmitter?.let { (it.first * 10000) + it.second } ?: 0 } data class TractorPoint(val coord: Pair<Long, Long>, val pulled: Boolean) fun getTractorPoints(highX: Long, highY: Long): List<TractorPoint> { return (0L..highY).flatMap { y -> (0L..highX).map { x -> val out = IntcodeComputer(program()).runWithIO(stackOf(x, y)).last() TractorPoint(x to y, out == 1L) } } } fun asString(points: List<TractorPoint>): String { val highY = points.maxBy { it.coord.second }?.coord?.second ?: 1 return (0L..highY).joinToString("\n") { y -> points.getRow(y).map { if (it.pulled) '#' else '.' }.joinToString("") } } private fun getTractorPointsRow(y: Long): List<TractorPoint> { return (0L..y).map { x -> val out = IntcodeComputer(program()).runWithIO(stackOf(x, y)).last() TractorPoint(x to y, out == 1L) } } private fun List<TractorPoint>.getRow(y: Long): List<TractorPoint> { return filter { it.coord.second == y }.sortedBy { it.coord.first } } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
2,517
aoc-2019
Creative Commons Zero v1.0 Universal
src/Day01.kt
rafael-ribeiro1
572,657,838
false
{"Kotlin": 15675}
fun main() { fun part1(input: List<String>): Int { return input.caloriesPerElf().max() } fun part2(input: List<String>): Int { return input.caloriesPerElf().sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } fun List<String>.caloriesPerElf(): List<Int> { val res = mutableListOf<List<Int>>() var prev = 0 this.withIndex() .filter { it.value.isBlank() } .forEach { i -> res.add(this.subList(prev, i.index).map { it.toInt() }) prev = i.index + 1 } res.add(this.subList(prev, this.size).map { it.toInt() }) return res.map { it.sum() } }
0
Kotlin
0
0
5cae94a637567e8a1e911316e2adcc1b2a1ee4af
902
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day20.kt
poqueque
430,806,840
false
{"Kotlin": 101024}
package days import printMap import util.Coor class Day20 : Day(20) { val algorithm: String = inputList[0] val input = mutableMapOf<Coor, Int>() val C = listOf(".", "#") init { var height = 0 var width = 0 inputList.forEachIndexed() { i, it -> if (i > 1) { //input[Coor(-1,i)] = 0 //input[Coor(-2,i)] = 0 it.forEachIndexed { x, c -> input[Coor(x, i)] = if (c == '#') 1 else 0 } if (it.length > width) width = it.length //input[Coor(width,i)] = 0 //input[Coor(width+1,i)] = 0 } height = i } //printMap(input.mapValues { C[it.value] }) } override fun partOne(): Any { val output = applyAlgorithm(input, 1) val output1 = applyAlgorithm(output, 2) return output1.values.count { it == 1 } } private fun applyAlgorithm(input: MutableMap<Coor, Int>, step: Int): MutableMap<Coor, Int> { val output = mutableMapOf<Coor, Int>() val minX = input.keys.minOf { it.x } val minY = input.keys.minOf { it.y } val maxX = input.keys.maxOf { it.x } val maxY = input.keys.maxOf { it.y } val dv = if (step % 2 == 0 && algorithm[0] == '#') 1 else 0 for (x in minX - 1..maxX + 1) { for (y in minY - 1..maxY + 1) { var binData = (input[Coor(x - 1, y - 1)] ?: dv).toString() binData += (input[Coor(x, y - 1)] ?: dv).toString() binData += (input[Coor(x + 1, y - 1)] ?: dv).toString() binData += (input[Coor(x - 1, y)] ?: dv).toString() binData += (input[Coor(x, y)] ?: dv).toString() binData += (input[Coor(x + 1, y)] ?: dv).toString() binData += (input[Coor(x - 1, y + 1)] ?: dv).toString() binData += (input[Coor(x, y + 1)] ?: dv).toString() binData += (input[Coor(x + 1, y + 1)] ?: dv).toString() val num = binData.toInt(2) output[Coor(x, y)] = if (algorithm[num] == '#') 1 else 0 } } //printMap(output.mapValues { it -> C[it.value] }) return output } override fun partTwo(): Any { var output = input for(i in 1..50) { output = applyAlgorithm(output, i) } return output.values.count { it == 1 } } }
0
Kotlin
0
0
4fa363be46ca5cfcfb271a37564af15233f2a141
2,482
adventofcode2021
MIT License
src/algorithmdesignmanualbook/searching/SmallestMissingNumber.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.searching import kotlin.test.assertTrue /** * [4-34] * Suppose that you are given a sorted sequence of distinct integers {a1, a2, . . . , an}, * drawn from 1 to m where n < m. Give an O(lg n) algorithm to find an integer ≤ m * that is not present in a. For full credit, find the smallest such integer. * * Solution: Binary search into the array. * Since its sorted and starts from index 1, every element at index i should have element i. * */ private fun smallestMissingNumber(array: IntArray, low: Int, high: Int): Int { if (low >= high) { // a[i] == i so missing element is the index return low } if (array.first() != 1) { return 1 } else if (array.last() == array.size) { return array.lastIndex + 1 + 1 } // Calibrate to find midIndex val midIndex = (low - 1 + high - 1) / 2 val midItem = array[midIndex] // index i should have element i // Since elements are distinct, if condition is not met, then there is some missing element at left if (midItem != midIndex + 1) { return smallestMissingNumber(array, low, midIndex + 1 - 1) } else { // Since a[i] == i so all left elements are sequential so missing element must be at right return smallestMissingNumber(array, midIndex + 1 + 1, array.size) } } fun main() { assertTrue { val array = intArrayOf(2, 3, 4, 5, 8, 10, 12, 19, 26) smallestMissingNumber(array, 1, array.size) == 1 } assertTrue { val array = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) smallestMissingNumber(array, 1, array.size) == 10 } assertTrue { val array = intArrayOf(1, 2, 3, 4, 5, 6, 7, 9, 12) smallestMissingNumber(array, 1, array.size) == 8 } assertTrue { val array = intArrayOf(1, 5, 6, 7, 8) smallestMissingNumber(array, 1, array.size) == 2 } assertTrue { val array = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 10) smallestMissingNumber(array, 1, array.size) == 9 } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,062
algorithms
MIT License
src/app.kt
MaciejPawlik
225,872,902
false
null
import centile.Centile import centile.model.Standard import centile.model.Gender import centile.model.Type import java.io.File import kotlin.math.pow fun main() { println("Youngster gender? (Girl / Boy):") // Todo: add inputs check ;) val pickedGender = readLine().toString() val gender = Gender.valueOf(pickedGender.toUpperCase()) println("Age(months)?:") val age = readLine()!!.toInt() println("Weight(kg)?:") val weight = readLine()!!.toDouble() println("Height(cm)?:") val height = readLine()!!.toDouble() findCentile(gender, age, weight, height) } fun findCentile(gender: Gender, age: Int, weight: Double, height: Double) { val standards = getCentiles() .filter { it.gender == gender && it.age == age } if (standards.isNotEmpty()) { val bmi = weight / (height / 100).pow(2.0) val typeToValue = mapOf(Type.WEIGHT to weight, Type.HEIGHT to height, Type.BMI to bmi) typeToValue.forEach { printCentile(it.key, it.value, standards) } } else { println("No data for this age") } } fun printCentile(type: Type, value: Double, standards: List<Standard>) { val centiles = standards.firstOrNull { it.type == type } ?.centiles val result = centiles?.let { getPercentile(it, value) } ?: "no data for this age" println("Centile $type: $result") } fun getPercentile(centiles: List<Centile>, value: Double) : Int { val centile = centiles .filter { it.value <= value } .lastOrNull() return centile?.percentile ?: 1 } fun getCentiles(): List<Standard> { val csvFile = "./src/centile/centiles.csv" val centiles = mutableListOf<Standard>() val reader = File(csvFile).readLines() for (line in reader) { val dataField = line.split(",") centiles.add( Standard( Gender.valueOf(dataField[0]), Type.valueOf(dataField[1]), dataField[2].toInt(), listOf( Centile(1, dataField[3].toDouble()), Centile(3, dataField[4].toDouble()), Centile(5, dataField[5].toDouble()), Centile(10, dataField[6].toDouble()), Centile(15, dataField[7].toDouble()), Centile(25, dataField[8].toDouble()), Centile(50, dataField[9].toDouble()), Centile(75, dataField[10].toDouble()), Centile(85, dataField[11].toDouble()), Centile(90, dataField[12].toDouble()), Centile(95, dataField[13].toDouble()), Centile(97, dataField[14].toDouble()), Centile(99, dataField[15].toDouble()) ) ) ) } return centiles }
0
Kotlin
0
0
8f8ccf7d7fa7f0317871efa0309ae8f2c86d14c7
2,929
youngster_bmi
MIT License
src/main/kotlin/adventofcode2017/potasz/P12DigitalPlumber.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz object P12DigitalPlumber { data class Program(val id: Int, val peers: MutableSet<Int> = mutableSetOf()) fun solve(lines: List<String>): List<Set<Int>> { val programs = mutableMapOf<Int, Program>() lines.map { it.split(" <-> ") } .map { Pair(it[0].toInt(), it[1].split(", ").map{ it.toInt() }) } .forEach { pair -> val p = programs.getOrPut(pair.first) { Program(pair.first) } pair.second .map { programs.getOrPut(it, {Program(it)}).apply { this.peers.add(p.id) } } .forEach { p.peers.add(it.id) } } return findGroups(programs.toMap()) } private fun findGroups(programs: Map<Int, Program>): List<Set<Int>> { val groups = mutableListOf<Set<Int>>() val foundPrograms = mutableSetOf<Int>() var root = programs.keys.minus(foundPrograms).sorted().firstOrNull() while (root != null) { val group = mutableSetOf<Int>() findPeersFrom(root, programs, group) groups.add(group) foundPrograms.addAll(group) root = programs.keys.minus(foundPrograms).sorted().firstOrNull() } return groups.toList() } private fun findPeersFrom(root: Int, programs: Map<Int, Program>, group: MutableSet<Int>) { programs[root]!!.peers .filter { it !in group } .forEach { group.add(it) findPeersFrom(it, programs, group) } } @JvmStatic fun main(args: Array<String>) { val input = readLines("input12.txt") val groups = solve(input) println("Group size containing 0: ${groups[0].size}") println("Number of groups: ${groups.size}") } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
1,881
adventofcode2017
Apache License 2.0
src/Day03.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
fun main() { val lookup = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun part1(input: List<String>): Int = input .map { it.chunked(it.length / 2) } .map { it.first() .split("") .intersect(it.last().split("").toSet()).first { it.isNotEmpty() } } .sumOf { lookup.indexOf(it) } fun part2(input: List<String>): Int = input.filterNot { it == "" }.chunked(3) .map { it.first() .split("") .intersect(it[1].split("").toSet()) .intersect(it.last().split("").toSet()).first { it.isNotEmpty() } } .sumOf { lookup.indexOf(it) } val testInput = readInput("Day03_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
971
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/adventofcode2017/Day08LikeRegisters.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2017 import adventofcode2017.Comparator.* import adventofcode2017.RegisterOperation.* class Day08LikeRegisters enum class RegisterOperation { INC, DEC } enum class Comparator { LT, LET, EQ, NE, GET, GT } data class Register(val name: String, var value: Int = 0) { fun inc(incValue: Int) { value += incValue } fun dec(decValue: Int) { value -= decValue } } data class Instruction(val register: String, val operation: RegisterOperation, val value: Int, val condition: String) { val comparator: Comparator val compareValue: Int val registerToCheck: String init { val parts = condition.split(" ") registerToCheck = parts[0] compareValue = parts[2].toInt() val comp = parts[1] comparator = when { comp == "<" -> LT comp == "<=" -> LET comp == "==" -> EQ comp == "!=" -> NE comp == ">=" -> GET else -> GT } } companion object { fun fromLineInput(input: String): Instruction { // Example: vk inc 880 if pnt == 428 val parts = input.split(" ") val operation = if (parts[1] == "inc") INC else DEC return Instruction(parts[0], operation, parts[2].toInt(), input.substringAfter("if ")) } } fun evaluate(registerValue: Int) = when (comparator) { LT -> registerValue < compareValue LET -> registerValue <= compareValue EQ -> registerValue == compareValue NE -> registerValue != compareValue GET -> registerValue >= compareValue GT -> registerValue > compareValue } } class RegisterMachine { private val instructions = mutableListOf<Instruction>() private val registers = mutableListOf<Register>() var registerMax = 0 val highestRegister: Int get() = registers.maxByOrNull { it.value }?.value ?: 0 fun readInstructions(input: List<String>) { input.forEach { instructions.add(Instruction.fromLineInput(it)) } instructions.forEach { registers.add(Register(it.register)) } } fun runInstructions() { instructions.forEach { instruction -> val registerName = instruction.register val registerToCheckName = instruction.registerToCheck val (register, registerToCheck) = findRegisters(registerName, registerToCheckName) if (checkCondition(registerToCheck, instruction)) { register?.run { when (instruction.operation) { INC -> inc(instruction.value) DEC -> dec(instruction.value) } if (value > registerMax) registerMax = value } } } } private fun checkCondition(registerToCheck: Register?, instruction: Instruction): Boolean { return registerToCheck?.let { instruction.evaluate(registerToCheck.value) } ?: false } private fun findRegisters(registerName: String, registerToCheckName: String): Pair<Register?, Register?> { val register = registers.find { it.name == registerName } val registerToCheck = registers.find { it.name == registerToCheckName } return register to registerToCheck } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
3,348
kotlin-coding-challenges
MIT License
src/Day10.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
fun main() { fun part1(input: List<String>): Int { return acc(input, 0, 1, 1, listOf(20, 60, 100, 140, 180, 220)) } fun part2(input: List<String>) { var X = 1 var pointer = 0 var endCycle = false var cycle = 0 for (y in 0..5) { for (x in 0..39) { cycle += 1 if (x in setOf(X - 1, X, X + 1)) print("#") else print(".") if (input[pointer] == "noop") { pointer += 1 endCycle = false } else { val number = input[pointer].split(" ")[1].toInt() if (endCycle) { X += number pointer += 1 endCycle = false } else { endCycle = true } } } println() } } val testInput = readLines("Day10_test") val input = readLines("Day10") check(part1(testInput) == 13140) part2(testInput) println(part1(input)) part2(input) } fun acc(input: List<String>, pointer: Int, currentCycle: Int, register: Int, cycles: List<Int>): Int { return if (cycles.isEmpty()) 0 else { if (input[pointer] == "noop") { if (currentCycle == cycles[0]) { currentCycle * register + acc(input, pointer.inc(), currentCycle.inc(), register, cycles.takeLast(cycles.size - 1)) } else { acc(input, pointer.inc(), currentCycle.inc(), register, cycles) } } else { val number = input[pointer].split(" ")[1].toInt() if (currentCycle == cycles[0]) { currentCycle * register + acc(input, pointer.inc(), currentCycle + 2, register + number, cycles.takeLast(cycles.size - 1)) } else if (currentCycle + 1 == cycles[0]) { (currentCycle + 1) * register + acc(input, pointer.inc(), currentCycle + 2, register + number, cycles.takeLast(cycles.size - 1)) } else { acc(input, pointer.inc(), currentCycle + 2, register + number, cycles) } } } }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
2,271
advent-of-code-kotlin-2022
Apache License 2.0
src/Day12.kt
janbina
112,736,606
false
null
package day12 import getInput import java.util.* import kotlin.test.assertEquals fun main(args: Array<String>) { val input = getInput(12) .readLines() .map { Regex("\\w+").findAll(it).map { it.value.toInt() }.toList() } val nodes = parseInput(input) assertEquals(175, part1(nodes)) assertEquals(213, part2(nodes)) } fun parseInput(input: List<List<Int>>): Map<Int, Set<Int>> { val map = mutableMapOf<Int, MutableSet<Int>>() input.forEach { line -> val node = map.computeIfAbsent(line[0]) { mutableSetOf() } line.drop(1).forEach { node.add(it)} } return map } fun getGroup(nodes: Map<Int, Set<Int>>, start: Int): Set<Int> { val group = mutableSetOf<Int>() val queue = LinkedList<Int>() queue.add(start) while (queue.isNotEmpty()) { queue.pop().let { if (group.add(it)) { nodes[it]!!.forEach { queue.add(it) } } } } return group } fun part1(nodes: Map<Int, Set<Int>>): Int { return getGroup(nodes, 0).size } fun part2(nodes: Map<Int, Set<Int>>): Int { val inGroup = mutableSetOf<Int>() var groups = 0 while (inGroup.size != nodes.size) { nodes.keys.first { !inGroup.contains(it) }.let { inGroup.addAll(getGroup(nodes, it)) groups++ } } return groups }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
1,382
advent-of-code-2017
MIT License
src/exercises/Day10.kt
Njko
572,917,534
false
{"Kotlin": 53729}
// ktlint-disable filename package exercises import readInput fun main() { fun part1(input: List<String>): Int { var cycle = 1 var x = 1 val cyclesToCheck = mutableMapOf(20 to 0, 60 to 0, 100 to 0, 140 to 0, 180 to 0, 220 to 0) input.forEach { instruction -> if (instruction != "noop") { cycle += 1 cyclesToCheck.keys.contains(cycle).let { if (it) { cyclesToCheck[cycle] = cycle * x } } val (_, value) = instruction.split(" ") x += value.toInt() } cycle += 1 cyclesToCheck.keys.contains(cycle).let { if (it) { cyclesToCheck[cycle] = cycle * x } } } return cyclesToCheck.values.sum() } fun drawOnScreenAtPosition(screen: MutableList<String>, cycle: Int, spritePosition: Int) { val cycleIndex: Int = cycle - 1 val lineIndex: Int = cycleIndex / 40 val pixelIndex: Int = cycleIndex % 40 val spriteRange = spritePosition until spritePosition + 3 val line = screen[lineIndex].toCharArray() line[pixelIndex] = if (spriteRange.contains(pixelIndex)) '#' else '.' screen[lineIndex] = String(line) } fun part2(input: List<String>) { val screen = mutableListOf( "........................................", "........................................", "........................................", "........................................", "........................................", "........................................" ) var spritePosition = 0 var cycle = 1 input.forEach { instruction -> drawOnScreenAtPosition(screen, cycle, spritePosition) if (instruction != "noop") { cycle += 1 drawOnScreenAtPosition(screen, cycle, spritePosition) val (_, value) = instruction.split(" ") spritePosition += value.toInt() } cycle += 1 } println(screen.joinToString(separator = "\n")) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") println("Test results:") println(part1(testInput)) check(part1(testInput) == 13140) println(part2(testInput)) val input = readInput("Day10") println("Final results:") println(part1(input)) check(part1(input) == 13860) println(part2(input)) }
0
Kotlin
0
2
68d0c8d0bcfb81c183786dfd7e02e6745024e396
2,694
advent-of-code-2022
Apache License 2.0
src/day01/Day01.kt
ankushg
573,188,873
false
{"Kotlin": 7320}
@JvmInline private value class Elf(private val inventory: List<Int>) { val total get() = inventory.sum() } object Day01 : Solution<Int>( dayNumber = "01", part1ExpectedAnswer = 24000, part2ExpectedAnswer = 45000 ) { private fun buildElfList(input: List<String>): List<Elf> { val elves = mutableListOf<Elf>() var currentElfInventory = mutableListOf<Int>() input.forEach { if (it.isBlank()) { elves.add(Elf(currentElfInventory)) currentElfInventory = mutableListOf() } else { currentElfInventory.add(it.toInt()) } } if (currentElfInventory.isNotEmpty()) { elves.add(Elf(currentElfInventory)) } return elves } override fun part1(input: List<String>): Int { val elves = buildElfList(input) return elves.maxOf { it.total } } override fun part2(input: List<String>): Int { val elves = buildElfList(input) // simple stdlib return elves.map { it.total }.sortedDescending().take(3).sum() // // Using MinHeap // val comparator = compareBy<Elf> { it.total } // val top3Heap = PriorityQueue<Elf>(3, comparator) // // elves.take(3).forEach(top3Heap::add) // // elves.drop(3).forEach { newElf -> // if (newElf.total > (top3Heap.peek()?.total ?: Int.MIN_VALUE)) { // top3Heap.poll() // top3Heap.add(newElf) // } // } // // return top3Heap.sumOf { it.total } } } fun main() { Day01.main() }
0
Kotlin
0
0
b4c93b6f12f5677173cb9bacfe5aa4ce4afa5667
1,622
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g1101_1200/s1129_shortest_path_with_alternating_colors/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1129_shortest_path_with_alternating_colors // #Medium #Breadth_First_Search #Graph #Graph_Theory_I_Day_10_Standard_Traversal // #2023_10_02_Time_208_ms_(80.00%)_Space_39.9_MB_(70.00%) import java.util.LinkedList import java.util.Queue @Suppress("NAME_SHADOWING") class Solution { private class Pair(var node: Int, var color: Int) private fun bfs( q: Queue<Int>, vis: Array<BooleanArray>, graph: List<MutableList<Pair>>, blue: Boolean, shortestPaths: IntArray ) { var blue = blue var level = 0 q.add(0) if (blue) { vis[0][1] = true } else { vis[0][0] = true } while (q.isNotEmpty()) { var size = q.size while (size-- > 0) { val curr = q.poll() shortestPaths[curr] = Math.min(level, shortestPaths[curr]) for (nextNode in graph[curr]) { if (nextNode.color == 1 && blue && !vis[nextNode.node][1]) { q.add(nextNode.node) vis[nextNode.node][1] = true } if (!blue && nextNode.color == 0 && !vis[nextNode.node][0]) { q.add(nextNode.node) vis[nextNode.node][0] = true } } } blue = !blue level++ } } fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray { val graph: MutableList<MutableList<Pair>> = ArrayList() for (i in 0 until n) { graph.add(mutableListOf()) } for (edge in redEdges) { val a = edge[0] val b = edge[1] // red -> 0 graph[a].add(Pair(b, 0)) } for (edge in blueEdges) { val u = edge[0] val v = edge[1] // blue -> 1 graph[u].add(Pair(v, 1)) } val shortestPaths = IntArray(n) val q: Queue<Int> = LinkedList() shortestPaths.fill(Int.MAX_VALUE) bfs(q, Array(n) { BooleanArray(2) }, graph, true, shortestPaths) bfs(q, Array(n) { BooleanArray(2) }, graph, false, shortestPaths) for (i in 0 until n) { if (shortestPaths[i] == Int.MAX_VALUE) { shortestPaths[i] = -1 } } return shortestPaths } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,486
LeetCode-in-Kotlin
MIT License
src/Day02.kt
fonglh
573,269,990
false
{"Kotlin": 48950, "Ruby": 1701}
fun main() { fun part1(input: List<String>): Int { var score = 0 input.forEach { var moves = it.split(" ") if (isDraw(moves[0], moves[1])) { score += 3 } if (doesPlayerWin(moves[0], moves[1])) { score += 6 } score += playerShapeScore(moves[1]) } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { var moves = it.split(" ") var opponentMove = moves[0] var desiredOutcome = moves[1] var playerMove = getPlayerMove(opponentMove, desiredOutcome) score += when(desiredOutcome) { "Y" -> 3 "Z" -> 6 else -> 0 } score += playerShapeScore(playerMove) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } // part 1 fun isDraw(opponentMove: String, playerMove: String): Boolean { return (opponentMove == "A" && playerMove == "X") || (opponentMove == "B" && playerMove == "Y") || (opponentMove == "C" && playerMove == "Z") } // part 1 fun doesPlayerWin(opponentMove: String, playerMove: String): Boolean { return (opponentMove == "A" && playerMove == "Y") || (opponentMove == "B" && playerMove == "Z") || (opponentMove == "C" && playerMove == "X") } fun getPlayerMove(opponentMove: String, desiredOutcome: String): String { return when (desiredOutcome) { // lose "X" -> { when(opponentMove) { "A" -> "Z" "B" -> "X" "C" -> "Y" else -> "invalid" } } // draw "Y" -> { when(opponentMove) { "A" -> "X" "B" -> "Y" "C" -> "Z" else -> "invalid" } } // win "Z" -> { when(opponentMove) { "A" -> "Y" "B" -> "Z" "C" -> "X" else -> "invalid" } } else -> { // will never reach here "invalid" } } } fun playerShapeScore(playerMove: String): Int { return when(playerMove) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } }
0
Kotlin
0
0
ef41300d53c604fcd0f4d4c1783cc16916ef879b
2,661
advent-of-code-2022
Apache License 2.0
src/Day06.kt
nguyendanv
573,066,311
false
{"Kotlin": 18026}
fun main() { fun findStart(input: List<String>, uniqueChars: Int): Int { val windows = input[0].windowed(uniqueChars, 1) for (i in windows.indices) { if (windows[i].toSet().size==uniqueChars) return i + uniqueChars } return -1 } fun part1(input: List<String>): Int { return findStart(input, 4) } fun part2(input: List<String>): Int { return findStart(input, 14) } // test if implementation meets criteria from the description, like: val testInput1 = readInput("Day06_test1") val testInput2 = readInput("Day06_test2") val testInput3 = readInput("Day06_test3") val testInput4 = readInput("Day06_test4") val testInput5 = readInput("Day06_test5") check(part1(testInput1)==7) check(part1(testInput2)==5) check(part1(testInput3)==6) check(part1(testInput4)==10) check(part1(testInput5)==11) check(part2(testInput1)==19) check(part2(testInput2)==23) check(part2(testInput3)==23) check(part2(testInput4)==29) check(part2(testInput5)==26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
376512583af723b4035b170db1fa890eb32f2f0f
1,189
advent2022
Apache License 2.0
src/Day19.kt
matusekma
572,617,724
false
{"Kotlin": 119912, "JavaScript": 2024}
class BluePrint( val id: Int, val oreRobotOreCost: Int, val clayRobotOreCost: Int, val obsidianRobotOreCost: Int, val obsidianRobotClayCost: Int, val geodeRobotOreCost: Int, val geodeRobotObsidianCost: Int, ) { val maxOreNeeded = listOf( geodeRobotOreCost, obsidianRobotOreCost, clayRobotOreCost ).max() } data class RobotsState( val bluePrintId: Int, val ore: Int, val clay: Int, val obsidian: Int, val geode: Int, val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int, val timeLeft: Int ) class Day19 { private val seenStates = mutableSetOf<RobotsState>() fun part1(input: List<String>): Int { val bluePrints = input.mapIndexed { i, line -> parseBluePrint(i + 1, line) } var qualityProducts = 0 for (bluePrint in bluePrints) { val currentQuality = searchOptimalExecution( bluePrint, RobotsState( bluePrintId = bluePrint.id, ore = 0, clay = 0, obsidian = 0, geode = 0, oreRobots = 1, clayRobots = 0, obsidianRobots = 0, geodeRobots = 0, timeLeft = 24 ) ) qualityProducts += currentQuality * bluePrint.id println(qualityProducts) println(bluePrint.id) } return qualityProducts } private fun searchOptimalExecution( bluePrint: BluePrint, state: RobotsState ): Int { seenStates.add(state) if (state.timeLeft == 0) { // val nextCurrentResources = currentConfiguration.resources.toMutableMap() // for ((robot, value) in currentConfiguration.robots.entries) { // nextCurrentResources[robot] = nextCurrentResources[robot]!! + value // } return state.geode } // build robot from previous resources - calculate all possibilities or don't build val possibleNextStates = getPossibleRobotBuildStates(bluePrint, state) // collect resources with robots of current config val results = possibleNextStates .map { var ore = it.ore + state.oreRobots var clay = it.clay + state.clayRobots var obsidian = it.obsidian + state.obsidianRobots // throw away resources not needed val maxOreNeeded = bluePrint.maxOreNeeded * (it.timeLeft) - state.oreRobots * (it.timeLeft - 1) if (ore >= maxOreNeeded) { ore = maxOreNeeded } val maxClayNeeded = bluePrint.obsidianRobotClayCost * (it.timeLeft) - state.clayRobots * (it.timeLeft - 1) if (clay >= maxClayNeeded) { clay = maxClayNeeded } val maxObsidianNeeded = bluePrint.geodeRobotObsidianCost * (it.timeLeft) - state.obsidianRobots * (it.timeLeft - 1) if (obsidian >= maxObsidianNeeded) { obsidian = maxObsidianNeeded } it.copy( ore = ore, clay = clay, obsidian = obsidian, geode = it.geode + state.geodeRobots, timeLeft = it.timeLeft - 1 ) } .filter { !seenStates.contains(it) } .map { searchOptimalExecution( bluePrint, it ) } if (results.isNotEmpty()) return results.max() return 0 } private fun getPossibleRobotBuildStates( bluePrint: BluePrint, state: RobotsState ): List<RobotsState> { val possibleNextStates = mutableListOf(state) // add "do nothing" state if (bluePrint.maxOreNeeded > state.oreRobots && bluePrint.oreRobotOreCost <= state.ore) { possibleNextStates.add( state.copy( ore = state.ore - bluePrint.oreRobotOreCost, oreRobots = state.oreRobots + 1 ) ) } //clay if (bluePrint.obsidianRobotClayCost > state.clayRobots && bluePrint.clayRobotOreCost <= state.ore) { possibleNextStates.add( state.copy( ore = state.ore - bluePrint.clayRobotOreCost, clayRobots = state.clayRobots + 1 ) ) } // obsidian if (bluePrint.geodeRobotObsidianCost > state.oreRobots && bluePrint.obsidianRobotOreCost <= state.ore && bluePrint.obsidianRobotClayCost <= state.clay) { possibleNextStates.add( state.copy( ore = state.ore - bluePrint.obsidianRobotOreCost, clay = state.clay - bluePrint.obsidianRobotClayCost, obsidianRobots = state.obsidianRobots + 1 ) ) } // geode if (bluePrint.geodeRobotOreCost <= state.ore && bluePrint.geodeRobotObsidianCost <= state.obsidian) { possibleNextStates.add( state.copy( ore = state.ore - bluePrint.geodeRobotOreCost, obsidian = state.obsidian - bluePrint.geodeRobotObsidianCost, geodeRobots = state.geodeRobots + 1 ) ) } return possibleNextStates } private fun parseBluePrint(id: Int, line: String): BluePrint { val destructuredRegex = "Blueprint .+: Each ore robot costs ([0-9]+) ore\\. Each clay robot costs ([0-9]+) ore\\. Each obsidian robot costs ([0-9]+) ore and ([0-9]+) clay\\. Each geode robot costs ([0-9]+) ore and ([0-9]+) obsidian\\.".toRegex() return destructuredRegex.matchEntire(line) ?.destructured ?.let { (oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost) -> return BluePrint( id, oreRobotOreCost.toInt(), clayRobotOreCost.toInt(), obsidianRobotOreCost.toInt(), obsidianRobotClayCost.toInt(), geodeRobotOreCost.toInt(), geodeRobotObsidianCost.toInt() ) } ?: throw IllegalArgumentException("Bad input '$line'") } fun part2(input: List<String>): Int { val bluePrints = input.mapIndexed { i, line -> parseBluePrint(i + 1, line) } var geodeCountProduct = 1 for (bluePrint in bluePrints.subList(0, 3)) { val currentGeodeCount = searchOptimalExecution( bluePrint, RobotsState( bluePrintId = bluePrint.id, ore = 0, clay = 0, obsidian = 0, geode = 0, oreRobots = 1, clayRobots = 0, obsidianRobots = 0, geodeRobots = 0, timeLeft = 32 ) ) geodeCountProduct *= currentGeodeCount println(geodeCountProduct) println(bluePrint.id) } return geodeCountProduct } } fun main() { val input = readInput("input19_1") println(Day19().part1(input)) //println(Day19().part2(input)) }
0
Kotlin
0
0
744392a4d262112fe2d7819ffb6d5bde70b6d16a
7,697
advent-of-code
Apache License 2.0
calendar/day08/Day8.kt
mpetuska
571,764,215
false
{"Kotlin": 18073}
package day08 import Day import Lines class Day8 : Day() { override fun part1(input: Lines): Any { val grid = input.map { it.split("").filter(String::isNotBlank).map(String::toInt) } val height = grid.size val width = grid[0].size return (1 until height - 1).sumOf { y -> (1 until width - 1).count { x -> val target = grid[y][x] (0 until y).all { yy -> grid[yy][x] < target } || (y + 1 until height).all { yy -> grid[yy][x] < target } || (0 until x).all { xx -> grid[y][xx] < target } || (x + 1 until width).all { xx -> grid[y][xx] < target } } } + width * 2 + height * 2 - 4 } override fun part2(input: Lines): Any { val grid = input.map { it.split("").filter(String::isNotBlank).map(String::toInt) } val height = grid.size val width = grid[0].size return (1 until height - 1).maxOf { y -> (1 until width - 1).maxOf { x -> val target = grid[y][x] val up = (y - 1 downTo 0).indexOfFirst { grid[it][x] >= target } .takeUnless { it < 0 }?.inc() ?: y val left = (x - 1 downTo 0).indexOfFirst { grid[y][it] >= target } .takeUnless { it < 0 }?.inc() ?: x val down = (y + 1 until height).indexOfFirst { grid[it][x] >= target } .takeUnless { it < 0 }?.inc() ?: (height - y - 1) val right = (x + 1 until width).indexOfFirst { grid[y][it] >= target } .takeUnless { it < 0 }?.inc() ?: (width - x - 1) up * down * left * right } } } }
0
Kotlin
0
0
be876f0a565f8c14ffa8d30e4516e1f51bc3c0c5
1,532
advent-of-kotlin-2022
Apache License 2.0
aoc2022/day21.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day21.execute() } object Day21 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input).toLong()}") } private const val ROOT_MONKEY_NAME = "root" const val HUMAN_NAME = "humn" private fun part1(input: List<Monkey>): Long { val monkeyMap: Map<String, Monkey> = input.associateBy { it.id } return monkeyMap[ROOT_MONKEY_NAME]!!.getValue(monkeyMap) } private fun part2(input: List<Monkey>): Double { val monkeyMap: MutableMap<String, Monkey> = input.associateBy { it.id }.toMutableMap() val rootMonkey = monkeyMap[ROOT_MONKEY_NAME]!! val firstMonkey = monkeyMap[rootMonkey.op!!.firstMonkey]!! val secondMonkey = monkeyMap[rootMonkey.op.secondMonkey]!! return if (firstMonkey.containsHuman(monkeyMap)) { firstMonkey.getHumanValue(monkeyMap, secondMonkey.getValue(monkeyMap).toDouble()) } else { secondMonkey.getHumanValue(monkeyMap, firstMonkey.getValue(monkeyMap).toDouble()) } } private fun readInput(): List<Monkey> = InputRetrieval.getFile(2022, 21).readLines().map { Monkey.parse(it) } data class Monkey(val id: String, var value: Int?, val op: Operation?) { fun getValue(monkeyMap: Map<String, Monkey>): Long { return value?.toLong() ?: op!!.solve(monkeyMap) } fun containsHuman(monkeyMap: Map<String, Monkey>): Boolean { return if (this.id == HUMAN_NAME) { true } else if (value != null) { false } else if (op!!.firstMonkey == HUMAN_NAME || op.secondMonkey == HUMAN_NAME) { true } else { return monkeyMap[op.firstMonkey]!!.containsHuman(monkeyMap) || monkeyMap[op.secondMonkey]!!.containsHuman(monkeyMap) } } fun getHumanValue(monkeyMap: Map<String, Monkey>, expectedValue: Double): Double { if (id == HUMAN_NAME) { return expectedValue } val firstMonkey = monkeyMap[this.op!!.firstMonkey]!! val secondMonkey = monkeyMap[this.op.secondMonkey]!! if (firstMonkey.containsHuman(monkeyMap)) { val newExpectedValue = when (op.operator) { '+' -> expectedValue - secondMonkey.getValue(monkeyMap) '*' -> expectedValue / secondMonkey.getValue(monkeyMap) '/' -> expectedValue * secondMonkey.getValue(monkeyMap) '-' -> expectedValue + secondMonkey.getValue(monkeyMap) else -> throw RuntimeException("Impossible!") // Based on the input, this is impossible } return firstMonkey.getHumanValue(monkeyMap, newExpectedValue) } else { val newExpectedValue = when (op.operator) { '+' -> expectedValue - firstMonkey.getValue(monkeyMap) '*' -> expectedValue / firstMonkey.getValue(monkeyMap) '/' -> expectedValue * firstMonkey.getValue(monkeyMap) '-' -> firstMonkey.getValue(monkeyMap) - expectedValue // This is different because math! ;) else -> throw RuntimeException("Impossible!") // Based on the input, this is impossible } return secondMonkey.getHumanValue(monkeyMap, newExpectedValue) } } companion object { fun parse(input: String): Monkey { val id = input.substringBefore(':') val remainder = input.substringAfter(": ") var number: Int? = null var operation: Operation? = null if (remainder.contains(' ')) { // operation val (firstMonkey, op, secondMonkey) = remainder.split(' ') operation = Operation(op.first(), firstMonkey, secondMonkey) } else { number = remainder.toInt() } return Monkey(id, number, operation) } } } data class Operation(val operator: Char, val firstMonkey: String, val secondMonkey: String) { fun solve(monkeyMap: Map<String, Monkey>): Long { val firstMonkeyValue = monkeyMap[firstMonkey]!!.getValue(monkeyMap) val secondMonkeyValue = monkeyMap[secondMonkey]!!.getValue(monkeyMap) return when (operator) { '+' -> firstMonkeyValue + secondMonkeyValue '*' -> firstMonkeyValue * secondMonkeyValue '/' -> firstMonkeyValue / secondMonkeyValue '-' -> firstMonkeyValue - secondMonkeyValue else -> throw RuntimeException("Impossible!") // Based on the input, this is impossible } } } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
4,964
Advent-Of-Code
MIT License
src/main/kotlin/io/hsar/practice3/ProblemE.kt
HSAR
241,918,109
false
null
package io.hsar.practice3 /* https://codeforces.com/contest/1298/problem/E Input: 10 4 5 4 1 5 4 3 7 1 2 5 4 6 2 1 10 8 3 5 Output: 5 4 0 5 3 3 9 0 2 5 */ fun findNumberOfValidMentees(skillsLookup: List<Pair<Int, Int>>, quarrelsLookup: Map<Int, Set<Int>>, skillLevel: Int, index: Int): Int { var mentees = 0 skillsLookup .forEach { (otherIndex, otherSkillLevel) -> if (otherSkillLevel < skillLevel) { if (!quarrelsLookup[index]!!.contains(otherIndex)) // not in quarrel { mentees++ } } else { return mentees } } return mentees } fun main() { val (numberOfProgrammers, numberOfQuarrels) = readLine()!! .split(" ") .map { it.toInt() } .let { splitArray -> splitArray[0] to splitArray[1] } val skillLevels = readLine()!! .split(" ") .map { it.toInt() } val quarrels = (0 until numberOfQuarrels) .map { readLine()!! .split(" ") .map { it.toInt() } } val quarrelsLookup = List(numberOfProgrammers) { index -> index + 1 to mutableSetOf<Int>() } .toMap() // fill in quarrels quarrels.forEach { quarrel -> val personA = quarrel[0] val personB = quarrel[1] quarrelsLookup[personA]!!.add(personB) quarrelsLookup[personB]!!.add(personA) } val skillsLookup = skillLevels .mapIndexed { index, skillLevel -> index + 1 to skillLevel } .sortedBy { (_, skillLevel) -> skillLevel } val results = skillLevels .mapIndexed { index, skillLevel -> findNumberOfValidMentees(skillsLookup, quarrelsLookup, skillLevel, index + 1) } println(results.joinToString(" ")) }
0
Kotlin
0
0
69a1187ffa6e0a61324f88572851b2147d8a1210
1,994
KotlinHeroes
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RectangleArea.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min /** * 223. Rectangle Area * @see <a href="https://leetcode.com/problems/rectangle-area/">Source</a> */ fun interface RectangleArea { // TODO wtf? fun computeArea(ax1: Int, ay1: Int, ax2: Int, ay2: Int, bx1: Int, by1: Int, bx2: Int, by2: Int): Int } class MathAndGeometry : RectangleArea { override fun computeArea(ax1: Int, ay1: Int, ax2: Int, ay2: Int, bx1: Int, by1: Int, bx2: Int, by2: Int): Int { val areaOfA = (ay2 - ay1) * (ax2 - ax1) val areaOfB = (by2 - by1) * (bx2 - bx1) // calculate x overlap val left = max(ax1, bx1) val right = min(ax2, bx2) val xOverlap = right - left // calculate y overlap val top = min(ay2, by2) val bottom = max(ay1, by1) val yOverlap = top - bottom var areaOfOverlap = 0 // if the rectangles overlap each other, then calculate // the area of the overlap if (xOverlap > 0 && yOverlap > 0) { areaOfOverlap = xOverlap * yOverlap } // areaOfOverlap is counted twice when in the summation of // areaOfA and areaOfB, so we need to subtract it from the // total, to get the toal area covered by both the rectangles return areaOfA + areaOfB - areaOfOverlap } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,966
kotlab
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day04.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2021 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.P import se.saidaspen.aoc.util.ints fun main() = Day04.run() object Day04 : Day(2021, 4) { private val numbers = ints(input.lines().take(1)[0]) private val boards = toBoards() override fun part1(): Any { val marked = mutableMapOf<Int, MutableList<P<Int, Int>>>() for (num in numbers) { //mark for ((i, b) in boards.withIndex()) { val e = b.entries.firstOrNull { it.value == num } if (e != null) { val markedList = marked.getOrDefault(i, mutableListOf()) markedList.add(e.key) marked[i] = markedList } } // score for ((i, b) in boards.withIndex()) { var hasWon = false if (marked[i] != null && marked[i]!!.size >= 5) { for (row in 0 until 5) { hasWon = hasWon || marked[i]!!.count { it.first == row } == 5 } for (col in 0 until 5) { hasWon = hasWon || marked[i]!!.count { it.second == col } == 5 } } if (hasWon) { return b.filter { !marked[i]!!.contains(it.key) }.map { it.value }.sum() * num } } } return "NO WINNER" } override fun part2(): Any { val marked = mutableMapOf<Int, MutableList<P<Int, Int>>>() val winners = mutableListOf<P<Int, Int>>() for (num in numbers) { //mark for ((i, b) in boards.withIndex()) { val e = b.entries.firstOrNull { it.value == num } if (e != null) { val markedList = marked.getOrDefault(i, mutableListOf()) markedList.add(e.key) marked[i] = markedList } } for ((i, b) in boards.withIndex()) { var hasWon = false if (marked[i] != null && marked[i]!!.size >= 5 && !winners.map { it.first }.contains(i)) { for (row in 0 until 5) { hasWon = hasWon || marked[i]!!.count { it.first == row } == 5 } for (col in 0 until 5) { hasWon = hasWon || marked[i]!!.count { it.second == col } == 5 } } if (hasWon) { winners.add(P(i, b.filter { !marked[i]!!.contains(it.key) }.map { it.value }.sum() * num)) } } } return winners.last().second } private fun toBoards(): MutableList<MutableMap<P<Int, Int>, Int>> { val boards = mutableListOf<String>() var board = "" val lines = input.lines().drop(2) for (i in lines.indices) { if (lines[i].isEmpty()) { boards.add(board) board = "" } else { board += lines[i] + "\n" } } val tmp = mutableListOf<MutableMap<P<Int, Int>, Int>>() boards.forEach{ b -> val numbers = ints(b) val bMap = mutableMapOf<P<Int, Int>, Int>() for (row in 0 until 5) { for (col in 0 until 5) { bMap[P(row, col)] = numbers[row*5+col] } } assert(bMap.size == 25) tmp.add(bMap) } return tmp } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
3,617
adventofkotlin
MIT License
src/main/kotlin/de/dikodam/calendar/Day08.kt
dikodam
573,126,346
false
{"Kotlin": 26584}
package de.dikodam.calendar import de.dikodam.AbstractDay import de.dikodam.Coordinates2D import de.dikodam.executeTasks import kotlin.time.ExperimentalTime @ExperimentalTime fun main() { Day08().executeTasks() } class Day08 : AbstractDay() { val inputGrid = read2DGrid() override fun task1(): String { val minX = inputGrid.keys.minOf { it.x } val maxX = inputGrid.keys.maxOf { it.x } val minY = inputGrid.keys.minOf { it.y } val maxY = inputGrid.keys.maxOf { it.y } val rows = (minY..maxY).map { x -> inputGrid.filter { (coords, _) -> coords.x == x } .toList() .sortedBy { (coords, _) -> coords.y } } val cols = (minX..maxX).map { y -> inputGrid.filter { (coords, _) -> coords.y == y } .toList() .sortedBy { (coords, _) -> coords.x } } val visibleTrees = mutableSetOf<Coordinates2D>() rows.forEach { row -> var curTreeHeight = 0 row.forEach { (coords, tree) -> if (tree > curTreeHeight) { visibleTrees += coords curTreeHeight = tree } } curTreeHeight = 0 row.reversed().forEach { (coords, tree) -> if (tree > curTreeHeight) { visibleTrees += coords curTreeHeight = tree } } } cols.forEach { col -> var curTreeHeight = 0 col.forEach { (coords, tree) -> if (tree > curTreeHeight) { visibleTrees += coords curTreeHeight = tree } } curTreeHeight = 0 col.reversed().forEach { (coords, tree) -> if (tree > curTreeHeight) { visibleTrees += coords curTreeHeight = tree } } } return visibleTrees.size.toString() } override fun task2(): String { return "" } fun read2DGrid(): Map<Coordinates2D, Int> { val lines = readInputLines() return lines.flatMapIndexed { y, line -> line.mapIndexed { x, c -> Coordinates2D(x, y) to c.toString().toInt() } }.associate { it } } }
0
Kotlin
0
1
3eb9fc6f1b125565d6d999ebd0e0b1043539d192
2,401
aoc2022
MIT License
src/day13/Code.kt
fcolasuonno
221,697,249
false
null
package day13 import java.io.File import kotlin.math.abs private fun Triple<Int, Int, Int>.movements() = listOf( Triple(first - 1, second, third + 1), Triple(first + 1, second, third + 1), Triple(first, second - 1, third + 1), Triple(first, second + 1, third + 1)) private val test = false fun main() { val name = if (test) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed, if (test) Pair(7, 4) else Pair(31, 39))}") println("Part 2 = ${part2(parsed)}") } @UseExperimental(ExperimentalStdlibApi::class) fun parse(input: List<String>) = input.single().toInt().let { magic -> { x: Int, y: Int -> x >= 0 && y >= 0 && (x * x + 3 * x + 2 * x * y + y + y * y + magic).countOneBits() % 2 == 0 } } fun part1(isEmpty: (Int, Int) -> Boolean, dest: Pair<Int, Int>): Int { val seen = mutableSetOf<Pair<Int, Int>>() val explore = sortedSetOf(compareBy<Triple<Int, Int, Int>> { abs(dest.first - it.first) + abs(dest.second - it.second) } .thenBy { it.third }.thenBy { it.first }.thenBy { it.second } , Triple(1, 1, 0)) while (explore.isNotEmpty()) { val newPos = explore.first() if (newPos.first == dest.first && newPos.second == dest.second) { return newPos.third } explore.remove(newPos) seen.add(newPos.first to newPos.second) explore.addAll(newPos.movements().filter { isEmpty(it.first, it.second) && Pair(it.first, it.second) !in seen }) } return 0 } fun part2(isEmpty: (Int, Int) -> Boolean): Int { val seen = mutableSetOf<Pair<Int, Int>>() val explore = sortedSetOf(compareBy<Triple<Int, Int, Int>> { it.third }.thenBy { it.first }.thenBy { it.second } , Triple(1, 1, 0)) while (explore.isNotEmpty()) { val newPos = explore.first() explore.remove(newPos) seen.add(newPos.first to newPos.second) explore.addAll(newPos.movements().filter { isEmpty(it.first, it.second) && Pair(it.first, it.second) !in seen && it.third <= 50 }) } return seen.size }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
2,201
AOC2016
MIT License
src/Day01.kt
carotkut94
572,816,808
false
{"Kotlin": 7508}
fun main() { fun prepare(input:String): List<Long> { return input.split("\n\n").map { it.split("\n") }.map { it.sumOf { item -> item.toLong() } } } fun part1(input: List<Long>): Triple<Long, Long, Long> { var (first, second, third) = arrayOf(Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE) for(e in input){ if(e>first){ third = second second = first first = e }else if (e > second) { third = second second = e }else if (e > third) { third = e } } return Triple(first, second, third) } fun part2(triple: Triple<Long, Long, Long>): Long { return triple.first+triple.second+triple.third } val input = readAsString("Day01") val processedInput = prepare(input) val triple = part1(processedInput) println(triple.first) println(part2(triple)) }
0
Kotlin
0
0
ef3dee8be98abbe7e305e62bfe8c7d2eeff808ad
1,000
aoc-2022
Apache License 2.0
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem031.kt
mddburgess
261,028,925
false
null
package dev.mikeburgess.euler.problems /** * Problem 31 * * In the United Kingdom the currency is made up of pound (£) and pence (p). There are eight coins * in general circulation: * * 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p). * * It is possible to make £2 in the following way: * * 1 × £1 + 1 × 50p + 2 × 20p + 1 × 5p + 1 × 2p + 3 × 1p * * How many different ways can £2 be made using any number of coins? */ class Problem031 : Problem { override fun solve(): Long = listOf(200) .flatMap { (0..it / 200).map { c -> it - 200 * c } } .flatMap { (0..it / 100).map { c -> it - 100 * c } } .flatMap { (0..it / 50).map { c -> it - 50 * c } } .flatMap { (0..it / 20).map { c -> it - 20 * c } } .flatMap { (0..it / 10).map { c -> it - 10 * c } } .flatMap { (0..it / 5).map { c -> it - 5 * c } } .flatMap { (0..it / 2).map { c -> it - 2 * c } } .count().toLong() }
0
Kotlin
0
0
86518be1ac8bde25afcaf82ba5984b81589b7bc9
1,004
project-euler
MIT License
dcp_kotlin/src/main/kotlin/dcp/day262/day262.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day262 // day262.kt // By <NAME>, 2019. typealias Vertex = Int typealias Edge = Pair<Vertex, Vertex> data class UndirectedSimpleGraph(val nodes: Vertex, val adjacencies: Map<Vertex, Set<Vertex>>) { init { // The graph is simple because it uses a set. // Make sure all adjacencies are legal. require(adjacencies.keys.all((0 until nodes)::contains)){"Adjacency list contains non-vertices."} // Make sure undirected. require(adjacencies.all { (u,vs) -> vs.all { v -> (adjacencies[v] ?: error("$v missing adjacency list.")).contains(u) } }) // Make sure no loops. require(adjacencies.none { (u, vs) -> u in vs }){"Adjacency list contains loops."} } fun dfs(start: Vertex): Set<Vertex> { val visited = mutableSetOf<Vertex>() fun aux(v: Vertex): Unit { if (v in visited) return visited.add(v) adjacencies[v]?.forEach { aux(it) } } aux(start) return visited } fun removeEdge(u: Vertex, v: Vertex): UndirectedSimpleGraph = UndirectedSimpleGraph(nodes, adjacencies.filterNot { it.key == u || it.key == v } + Pair(u, (adjacencies[u]?.filterNot { it == v } ?: emptyList()).toSet()) + Pair(v, (adjacencies[v]?.filterNot { it == u } ?: emptyList()).toSet())) fun removeEdge(e: Edge) = removeEdge(e.first, e.second) // The filter here is to only consider lexicographic edges (u,v) where u < v. // This avoids duplicating edges and having (u,v) and (v,u). fun edges(): Set<Edge> = adjacencies.flatMap { (u, vs) -> vs.filter{u < it}.map{ Pair(u, it)} }.toSet() /** * This is a brute force approach that takes O((V+E)E), as it tries to remove an edge and then do a DFS to make * sure the graph is still connected. There is an O(V+E) algorithm as well. */ fun findBridgesBF(): Set<Edge> = edges().filter { e -> removeEdge(e).dfs(e.first).size < nodes }.toSet() }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,052
daily-coding-problem
MIT License
src/Day21.kt
palex65
572,937,600
false
{"Kotlin": 68582}
@file:Suppress("PackageDirectoryMismatch") package day21 import readInput abstract class Monkey(val name: String) { abstract fun getNumber(monkeys: Map<String,Monkey>): Long? open fun getForResult(monkeys: Map<String, Monkey>, res: Long): Long = error("getForResult in $name") } class MonkeyNumber(name: String, private val number: Int): Monkey(name) { override fun getNumber(monkeys: Map<String,Monkey>) = number.toLong() } class Human: Monkey("humn") { override fun getNumber(monkeys: Map<String,Monkey>) = null override fun getForResult(monkeys: Map<String, Monkey>, res: Long) = res } class MonkeyExpr(name: String, val left: String, val op: Char, val right: String): Monkey(name) { override fun getNumber(monkeys: Map<String,Monkey>): Long? { val nLeft = monkeys[left]?.getNumber(monkeys) val nRight = monkeys[right]?.getNumber(monkeys) return if (nLeft==null || nRight==null) null else when (op) { '+' -> nLeft + nRight '-' -> nLeft - nRight '/' -> nLeft / nRight '*' -> nLeft * nRight else -> error("Invalid operator $op") } } override fun getForResult(monkeys: Map<String, Monkey>, res: Long): Long { val l = monkeys[left] val r = monkeys[right] check(l!=null && r!=null) val nLeft = l.getNumber(monkeys) return if (nLeft==null) { val nRight = r.getNumber(monkeys) ?: error("Right null") l.getForResult(monkeys, when(op) { '+' -> res - nRight '-' -> res + nRight '*' -> res / nRight else -> res * nRight } ) } else { r.getForResult(monkeys, when(op) { '+' -> res - nLeft '-' -> nLeft - res '*' -> res / nLeft else -> nLeft / res } ) } } } class Root(val left: String, val right: String): Monkey("root") { override fun getNumber(monkeys: Map<String, Monkey>): Long? { val l = monkeys[left] val r = monkeys[right] check(l!=null && r!=null) val nLeft = l.getNumber(monkeys) return if (nLeft==null) l.getForResult(monkeys,r.getNumber(monkeys)!!) else r.getForResult(monkeys,l.getNumber(monkeys)!!) } } fun String.toMonkey(part2: Boolean): Monkey { val (name,rest) = split(": ") val value = rest.split(' ') if (part2) when (name) { "root" -> return Root(value[0],value[2]) "humn" -> return Human() } return if (value.size==1) MonkeyNumber(name, rest.toInt()) else MonkeyExpr(name,value[0],value[1].first(),value[2]) } fun partN(lines: List<String>, part2: Boolean = false): Long { val monkeys = lines.map { it.toMonkey(part2) }.associateBy { it.name } val root = monkeys["root"] ?: return 0 return root.getNumber(monkeys) ?: 0 } fun part1(lines: List<String>) = partN(lines) fun part2(lines: List<String>) = partN(lines, part2 = true) fun main() { val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) // 268597611536314 println(part2(input)) // 3451534022348 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
3,339
aoc2022
Apache License 2.0
src/Day07.kt
MartinsCode
572,817,581
false
{"Kotlin": 77324}
fun main() { // We need a stateful machine to parse the input. // It has to rebuild a kind of tree with the dir structure // And later on it has to traverse through the directories and calculate things. // Therefore let's keep track of all directories: // directories = mutableListOf("") // root // and of files with full name (including path) as a map (full name to size) // files = mapOf<String, Long>() // when we want to keep track of every file in a subdir, we simply compare the beginning of the name // (and maybe check, whether there is a slash in the file name) class Machine { val rootDir = "" var actualDir = rootDir val directories = mutableListOf("") val files = mutableMapOf<String, Int>() fun changeToDir(input: String) { val actDir = actualDir.split("/").toMutableList() when (input) { ".." -> { actDir.removeLast() } "/" -> { actDir.clear() } else -> { actDir.add(input) } } actualDir = actDir.joinToString("/") actualDir.replace("//", "/") if (!directories.contains(actualDir)) directories.add(actualDir) } fun parseCommand(input: String) { val command = input.split(" ") check(command[0] == "$") check(command[1] == "cd" || command[1] == "ls") { "ls or cd expected, but found ${command[1]}" } // if command == ls, nothing to do :-) since Output assumes, it's from ls if (command[1] == "cd") { changeToDir(command[2]) } } fun parseOutput(input: String) { val strSize = input.split(" ")[0] val name = input.split(" ")[1] if (strSize == "dir") { // we could map this. But why? } else { // seems we have a file val size = strSize.toInt() val fullname = "$actualDir/$name" files[fullname] = size } } fun parseLine(input: String) { if (input.matches("^\\$ .*".toRegex())) { parseCommand(input) } else { parseOutput(input) } } fun parseInput(input: List<String>) { input.forEach { parseLine(it) } } fun sumOfSmallFiles(): Int { return files.values.filter { it < 100_000 }.sum() } fun makeDirSizeMap(): MutableMap<String, Int> { val sizeMap = mutableMapOf<String, Int>() directories.forEach { dirname -> // calculate size and add to map files.forEach { (name, size) -> if (name.startsWith(dirname)) { if (!sizeMap.keys.contains(dirname)) { sizeMap[dirname] = size } else { sizeMap[dirname] = size + sizeMap[dirname]!! } } } } return sizeMap } fun sumOfSmallDirectories(): Int { val sizeMap = makeDirSizeMap() return sizeMap.values.filter { it < 100_000 }.sum() } fun totalSize(): Int { return files.values.sum() } fun sizeOfSmallestAbove(limit: Int): Int { val sizeMap = makeDirSizeMap() return sizeMap.values.filter { it >= limit }.min() } } fun part1(input: List<String>): Int { val machine = Machine() machine.parseInput(input) return machine.sumOfSmallDirectories() } fun part2(input: List<String>): Int { val machine = Machine() machine.parseInput(input) return machine.sizeOfSmallestAbove(30_000_000 - (70_000_000 - machine.totalSize())) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07-TestInput") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07-Input") println(part1(input)) println(part2(input)) check(part2(input) < 43562874) // Answer was too high }
0
Kotlin
0
0
1aedb69d80ae13553b913635fbf1df49c5ad58bd
4,442
AoC-2022-12-01
Apache License 2.0
src/main/kotlin/Day7.kt
dlew
75,886,947
false
null
import java.util.regex.Pattern class Day7 { data class Address(val sequences: List<String>, val hypernet: List<String>) { fun supportsTLS() = containsAbba(sequences) && !containsAbba(hypernet) fun supportsSSL(): Boolean { val sequenceAbas = sequences.map { findAbas(it) }.flatten() val hypernetAbas = hypernet.map { findAbas(it) }.flatten().map { reverseAba(it) } return sequenceAbas.intersect(hypernetAbas).size != 0 } } companion object { private val BRACKETS = Pattern.compile("[\\[\\]]") fun address(input: String) = input.split(BRACKETS) .foldIndexed(Address(emptyList(), emptyList()), { index, address, sequence -> if (index % 2 == 0) Address(address.sequences.plus(sequence), address.hypernet) else Address(address.sequences, address.hypernet.plus(sequence)) }) fun findAbas(input: String) = input.toList() .window(3) .fold(emptyList<String>(), { abas, text -> if (isAba(text)) abas.plusElement(text.joinToString("")) else abas }) fun reverseAba(input: String) = "${input[1]}${input[0]}${input[1]}" fun containsAbba(input: List<String>) = input .fold(false, { hasAbba, text -> if (hasAbba) true else containsAbba(text) }) fun containsAbba(input: String) = input.toList() .window(4) .fold(false, { hasAbba, text -> if (hasAbba) true else isAbba(text) }) private fun isAbba(input: List<Char>) = input[0] == input[3] && input[1] == input[2] && input[0] != input[1] private fun isAba(input: List<Char>) = input[0] == input[2] && input[0] != input[1] } }
0
Kotlin
2
12
527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd
1,613
aoc-2016
MIT License
kotlin/src/com/daily/algothrim/leetcode/MinimumEffortPath.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import kotlin.math.abs /** * 1631. 最小体力消耗路径 * * 你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。 * * 一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。 * * 请你返回从左上角走到右下角的最小 体力消耗值 。 * */ class MinimumEffortPath { companion object { @JvmStatic fun main(args: Array<String>) { println(MinimumEffortPath().solution(arrayOf( intArrayOf(1, 2, 2), intArrayOf(3, 8, 2), intArrayOf(5, 3, 5) ))) } } // 输入:heights = [[1,2,2],[3,8,2],[5,3,5]] // 输出:2 // 解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。 // 这条路径比路径 [1,2,2,2,5] 更优,因为另一条路径差值最大值为 3 。 /** * O(nm log nm) * O(nm) */ fun solution(heights: Array<IntArray>): Int { val rSize = heights.size val cSize = heights[0].size val edges = arrayListOf<Edge>() // 构建边,并统计边的权重 for (i in 0 until rSize) { for (j in 0 until cSize) { val index = i * cSize + j if (i > 0) { edges.add(Edge(abs(heights[i][j] - heights[i - 1][j]), index - cSize, index)) } if (j > 0) { edges.add(Edge(abs(heights[i][j] - heights[i][j - 1]), index - 1, index)) } } } // 排序 edges.sortWith(Comparator { o1, o2 -> o1.len - o2.len }) val unionFound = DisJoinSetUnion(rSize * cSize) var result = 0 for (edge in edges) { // 合并 unionFound.setUnion(edge.x, edge.y) // 判断是否连通 if (unionFound.isConnected(0, rSize * cSize - 1)) { result = edge.len break } } return result } // 并查集 class DisJoinSetUnion(n: Int) { private val parent: IntArray = IntArray(n) private val rank: IntArray = IntArray(n) init { var i = 0 while (i < n) { parent[i] = i rank[i] = 1 i++ } } private fun find(index: Int): Int = if (parent[index] == index) index else { parent[index] = find(parent[index]) find(parent[index]) } fun setUnion(x: Int, y: Int): Boolean { var pX = find(x) var pY = find(y) if (pX == pY) return false if (rank[pX] < rank[pY]) { val temp = pX pX = pY pY = temp } // y 合并到 x rank[pX] += rank[pY] parent[pY] = pX return true } fun isConnected(x: Int, y: Int): Boolean = find(x) == find(y) } data class Edge(val len: Int, val x: Int, val y: Int) }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
3,520
daily_algorithm
Apache License 2.0
src/Utils.kt
ShuffleZZZ
572,630,279
false
{"Kotlin": 29686}
import java.io.File import java.math.BigInteger import java.security.MessageDigest import kotlin.math.absoluteValue import kotlin.math.sign fun Boolean.toInt() = if (this) 1 else 0 fun IntProgression.isRange() = step.sign > 0 operator fun <T> List<List<T>>.get(ind: Pair<Int, Int>) = this[ind.first][ind.second] operator fun <T> List<MutableList<T>>.set(ind: Pair<Int, Int>, value: T) { this[ind.first][ind.second] = value } fun <T> List<List<T>>.indexPairs(predicate: (T) -> Boolean = { true }) = this.indices.flatMap { i -> this.first().indices.map { j -> i to j } }.filter { predicate(this[it]) } operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>) = first + other.first to second + other.second operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>) = first - other.first to second - other.second fun Pair<Int, Int>.diff() = (second - first).absoluteValue operator fun <T, K> Pair<T, K>.compareTo(other: Pair<T, K>) where T : Comparable<T>, K : Comparable<K> = if (first == other.first) second.compareTo(other.second) else first.compareTo(other.first) infix fun Pair<Int, Int>.manhattan(other: Pair<Int, Int>) = (first - other.first).absoluteValue + (second - other.second).absoluteValue /** * Pairs intersect as ranges. */ fun <T> Pair<T, T>.intersect(other: Pair<T, T>) where T : Comparable<T> = if (this.compareTo(other) < 0) second >= other.first else first <= other.second /** * One of pairs fully includes other as range. */ fun <T, K> Pair<T, K>.include(other: Pair<T, K>) where T : Comparable<T>, K : Comparable<K> = first.compareTo(other.first).sign + second.compareTo(other.second).sign in -1..1 /** * Returns list of pairs with indexes of non-diagonal neighbours' shifts in 2D array. */ fun neighbours() = (-1..1).flatMap { i -> (-1..1).filter { j -> (i + j).absoluteValue == 1 }.map { j -> i to j } } /** * Returns list of pairs with indexes of given point non-diagonal neighbours in 2D array. */ fun neighbours(point: Pair<Int, Int>) = neighbours().map { it + point } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() /** * Reads blocks of lines separated by empty line. */ fun readBlocks(name: String) = File("src", "$name.txt") .readText() .trim('\n') .split("\n\n") .map { it.split('\n') } /** * Reads blocks separated by empty line. */ fun readRawBlocks(name: String) = File("src", "$name.txt") .readText() .trim('\n') .split("\n\n") /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0')
0
Kotlin
0
0
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
2,717
advent-of-code-kotlin
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[15]三数之和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* //给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重 //复的三元组。 // // 注意:答案中不可以包含重复的三元组。 // // // // 示例 1: // // //输入:nums = [-1,0,1,2,-1,-4] //输出:[[-1,-1,2],[-1,0,1]] // // // 示例 2: // // //输入:nums = [] //输出:[] // // // 示例 3: // // //输入:nums = [0] //输出:[] // // // // // 提示: // // // 0 <= nums.length <= 3000 // -105 <= nums[i] <= 105 // // Related Topics 数组 双指针 // 👍 3369 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun threeSum(nums: IntArray): List<List<Int>> { //双指针 求三数之和 //先排序 Arrays.sort(nums) var res :MutableList<List<Int>> = LinkedList() for (i in 0 until nums.size){ if(i == 0 || (i >0 && nums[i] != nums [i-1])){ //左右指针 var left = i+1 var right = nums.size -1 while(left < right){ when { nums[left] + nums[right] == 0 - nums[i] -> { res.add(mutableListOf(nums[i],nums[left],nums[right])) //去除重复计算 while(left<right && nums[left] == nums[left+1]) left++ while(left<right && nums[right] == nums[right-1]) right-- //否则都进一步 left++ right-- } nums[left] + nums[right] > 0 - nums[i] -> { //大于 right -- } else -> { //小于 left++ } } } } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,272
MyLeetCode
Apache License 2.0
src/main/kotlin/mirecxp/aoc23/day02/Day02.kt
MirecXP
726,044,224
false
{"Kotlin": 42343}
package mirecxp.aoc23.day02 import java.io.File //https://adventofcode.com/2023/day/2 class Day02(inputPath: String) { private val gameInputs: List<String> = File(inputPath).readLines() data class Game( val id: Long, val draws: List<Draw> ) { fun getMinimumDraw() = Draw( draws.maxOf { it.red }, draws.maxOf { it.green }, draws.maxOf { it.blue } ) } data class Draw(val red: Long, val green: Long, val blue: Long) { fun getPower() = red * green * blue fun isPossible(minDraw: Draw) = red <= minDraw.red && green <= minDraw.green && blue <= minDraw.blue } fun solve() { println("Solving day 2 for ${gameInputs.size} games") var sum = 0L var sumPowers = 0L val games = mutableListOf<Game>() gameInputs.forEach { gameInput -> gameInput.split(":").apply { val id = get(0).split(" ")[1].toLong() val draws = mutableListOf<Draw>() var possibleGame = true get(1).split(";").forEach { singleGame -> var red = 0L var blue = 0L var green = 0L singleGame.split(",").forEach { gems -> gems.trim().split(" ").apply { val num = get(0).toLong() when (val color = get(1)) { "red" -> red = num "green" -> green = num "blue" -> blue = num } } val draw = Draw(red, green, blue) draws.add(draw) if (!draw.isPossible(minDraw = Draw(red = 12, green = 13, blue = 14))) { possibleGame = false } } } if (possibleGame) { sum += id } val game = Game(id, draws) games.add(game) sumPowers += game.getMinimumDraw().getPower() } } println("Sum of possible game IDs: $sum") println("Sum of all powers: $sumPowers") } } fun main(args: Array<String>) { // val problem = Day02("/Users/miro/projects/AoC23/input/day02t.txt") val problem = Day02("/Users/miro/projects/AoC23/input/day02a.txt") problem.solve() }
0
Kotlin
0
0
6518fad9de6fb07f28375e46b50e971d99fce912
2,549
AoC-2023
MIT License
src/main/kotlin/com/leonra/adventofcode/advent2023/day03/Day3.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day03 import com.leonra.adventofcode.shared.readResource import kotlin.math.max import kotlin.math.min /** https://adventofcode.com/2023/day/3 */ private object Day3 { fun partOne(): Int { val schematic = mutableListOf<List<Char>>() readResource("/2023/day03/part1.txt") { schematic.add(it.toCharArray().asList()) } fun isLinkedToPart(inRow: Int, colStart: Int, colEnd: Int): Boolean { val rowRange = max(0, inRow - 1)..min(schematic.size - 1, inRow + 1) val colRange = max(0, colStart - 1)..min(schematic[inRow].size - 1, colEnd + 1) for (row in rowRange) { for (col in colRange) { val cell = schematic[row][col] if (!cell.isDigit() && cell != NOT_A_PART) { return true } } } return false } var sum = 0 for (row in schematic.indices) { var possiblePartNumber = "" var possibleStart = UNDEFINED_START for (col in schematic[row].indices) { val cell = schematic[row][col] if (cell.isDigit()) { possiblePartNumber += cell if (possibleStart == UNDEFINED_START) { possibleStart = col } } if ((!cell.isDigit() || col == schematic[row].lastIndex) && possiblePartNumber.isNotEmpty()) { if (isLinkedToPart(row, possibleStart, col - 1)) { sum += possiblePartNumber.toInt() } possiblePartNumber = "" possibleStart = UNDEFINED_START } } } return sum } fun partTwo(): Int { val schematic = mutableListOf<List<Char>>() readResource("/2023/day03/part1.txt") { schematic.add(it.toCharArray().asList()) } fun getLinkedGear(inRow: Int, colStart: Int, colEnd: Int): Pair<Int, Int>? { val rowRange = max(0, inRow - 1)..min(schematic.size - 1, inRow + 1) val colRange = max(0, colStart - 1)..min(schematic[inRow].size - 1, colEnd + 1) for (row in rowRange) { for (col in colRange) { val cell = schematic[row][col] if (!cell.isDigit() && cell == GEAR) { return row to col } } } return null } val possibleGears = mutableMapOf<Pair<Int, Int>, MutableList<Int>>() for (row in schematic.indices) { var possibleGearNumber = "" var possibleStart = UNDEFINED_START for (col in schematic[row].indices) { val cell = schematic[row][col] if (cell.isDigit()) { possibleGearNumber += cell if (possibleStart == UNDEFINED_START) { possibleStart = col } } if ((!cell.isDigit() || col == schematic[row].lastIndex) && possibleGearNumber.isNotEmpty()) { val linkedGear = getLinkedGear(row, possibleStart, col - 1) if (linkedGear != null) { val possibleRatios = possibleGears[linkedGear] ?: mutableListOf() possibleRatios.add(possibleGearNumber.toInt()) possibleGears[linkedGear] = possibleRatios } possibleGearNumber = "" possibleStart = UNDEFINED_START } } } return possibleGears .filterValues { it.size == 2 } .map { it.value[0] * it.value[1] } .sum() } private const val UNDEFINED_START = Int.MIN_VALUE private const val NOT_A_PART = '.' private const val GEAR = '*' } private fun main() { println("Part 1 sum: ${Day3.partOne()}") println("Part 2 sum: ${Day3.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
4,144
AdventOfCode
Apache License 2.0
src/main/kotlin/day25/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day25 import java.io.File typealias SeaFloor = Array<Array<SeaCucumberType?>> fun main() { val lines = File("src/main/kotlin/day25/input.txt").readLines() val seaFloor: SeaFloor = SeaFloor(lines.size) { i -> lines[i].map { SeaCucumberType.fromSymbol(it) }.toTypedArray() } var iterationCount = 0 var tmpState = seaFloor.copyOf() do { // tmpState.print() val (newState, numberOfMoves) = evolve(tmpState) tmpState = newState iterationCount++ } while (numberOfMoves != 0) println(iterationCount) } fun evolve(seaFloor: SeaFloor): Pair<SeaFloor, Int> { val seaFloorHeight = seaFloor.size val seaFloorWidth = seaFloor[0].size var movesCount = 0 val newState = SeaFloor(seaFloorHeight) { Array(seaFloorWidth) { null } } for (row in seaFloor.indices) { for (col in seaFloor[row].indices) { val seaCucumberType = seaFloor[row][col] if (seaCucumberType == SeaCucumberType.EAST) { if (seaFloor[row][(col + 1) % seaFloorWidth] == null) { newState[row][(col + 1) % seaFloorWidth] = seaCucumberType movesCount++ } else { newState[row][col] = seaCucumberType } } } } for (col in 0 until seaFloorWidth) { for (row in 0 until seaFloorHeight) { val seaCucumberType = seaFloor[row][col] if (seaCucumberType == SeaCucumberType.SOUTH) { if (seaFloor[(row + 1) % seaFloorHeight][col] == SeaCucumberType.SOUTH || newState[(row + 1) % seaFloorHeight][col] != null) { newState[row][col] = seaCucumberType } else { newState[(row + 1) % seaFloorHeight][col] = seaCucumberType movesCount++ } } } } return newState to movesCount } fun SeaFloor.print() { for (row in indices) { for (col in get(row).indices) { print(get(row).get(col)?.symbol ?: '.') } println() } println("========================") } enum class SeaCucumberType(val symbol: Char) { EAST('>'), SOUTH('v'), ; companion object { fun fromSymbol(symbol: Char) = values().firstOrNull { it.symbol == symbol } } }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
2,359
aoc-2021
MIT License
day03/src/main/kotlin/Main.kt
Prozen
160,076,543
false
null
import java.io.File fun main() { val strings = File(ClassLoader.getSystemResource("input.txt").file).readLines() val field = Array(1000) { Array(1000) { 0 } } strings.forEach { val words = it.split(" ") val start = words[2].dropLast(1).split(",").map { it.toInt() } val size = words[3].split("x").map { it.toInt() } (start[0] until start[0] + size[0]).forEach { x -> (start[1] until start[1] + size[1]).forEach { y -> field[x][y] += 1 } } } println(field.sumBy { it.count { it > 1 } }) val map = strings.map { val words = it.split(" ") val start = words[2].dropLast(1).split(",").map { it.toInt() } val size = words[3].split("x").map { it.toInt() } words[0] to (Point(start[0], start[1]) to Point(start[0] + size[0], start[1] + size[1])) } println(map.first { pair -> map.all { pair.first == it.first || doNotOverlap(pair.second.first, pair.second.second, it.second.first, it.second.second) } }.first) } data class Point(val x: Int, val y: Int) fun doNotOverlap(l1: Point, r1: Point, l2: Point, r2: Point) = l1.x >= r2.x || l2.x >= r1.x || l1.y >= r2.y || l2.y >= r1.y
0
Kotlin
0
0
b0e830f53e216dd9f010fb294bef9c5b8c10f4a8
1,269
AdventOfCode2018
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day07.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2017 import se.saidaspen.aoc.util.Day fun main() = Day07.run() object Day07 : Day(2017, 7) { private var nodes: HashSet<String> = HashSet() private var heldBy: HashMap<String, String> = HashMap() private var holding: HashMap<String, List<String>> = HashMap() private var weights: HashMap<String, Int> = HashMap() private var lines: List<String> = input.lines() init { for (line in lines) { val split = line.split("->".toRegex()) val node = split[0].split("\\s".toRegex())[0].trim() val weight = split[0].split("\\s".toRegex())[1].trim().replace("(", "").replace(")", "").toInt() weights[node] = weight val nHolding = if (split.size > 1) split[1].split(",".toRegex()).map { it.trim() }.toList() else listOf() nodes.add(node) holding[node] = nHolding for (n in nHolding) heldBy[n] = node } } override fun part1() = getBaseNode() private fun getBaseNode(): String { for (n in nodes) if (!heldBy.containsKey(n)) return n throw RuntimeException("Unable to find base node") } override fun part2(): String = findUnbalancedNode(getBaseNode()).toString() private fun findUnbalancedNode(node: String): Int { val unbalancedNodes = getUnbalancedNode(node) return when { unbalancedNodes.size > 1 -> throw RuntimeException("Found multiple unbalanced nodes") unbalancedNodes.isNotEmpty() -> findUnbalancedNode(unbalancedNodes[0].first) else -> { val expectedWeight = weigtOf(holding[heldBy[node]]!!.filter { it != node }[0]) val weightOfChildren = weigtOf(node) - weights[node]!! expectedWeight - weightOfChildren } } } private fun getUnbalancedNode(baseNode: String): List<Pair<String, Int>> { var childNodes = holding[baseNode] childNodes = childNodes ?: mutableListOf() val childWeights = mutableMapOf<Int, MutableList<String>>() for (cn in childNodes) { val weight = weigtOf(cn) val tmp = childWeights.remove(weight) ?: mutableListOf() tmp.add(cn) childWeights[weight] = tmp } return childWeights.filter { it.value.size == 1 }.map { Pair(it.value[0], it.key) }.toList() } private fun weigtOf(cn: String): Int { return weights[cn]?.plus(holding[cn]!!.map { weigtOf(it) }.sum())!! } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,530
adventofkotlin
MIT License
src/year2022/day05/Day05.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day05 import arrow.core.identity import io.kotest.matchers.shouldBe import utils.readInput fun main() { val testInput = readInput("05", "test_input") val realInput = readInput("05", "input") val testStart = testInput.takeWhile(String::isNotEmpty) val testMovements = testInput.takeLastWhile(String::isNotEmpty) .let(::parseMovements) val realStart = realInput.takeWhile(String::isNotEmpty) val realMovements = realInput.takeLastWhile(String::isNotEmpty) .let(::parseMovements) testStart.toStackList() .applyMovements(testMovements, List<Char>::asReversed) .joinToString(separator = "") { it.last().toString() } .also(::println) shouldBe "CMZ" realStart.toStackList() .applyMovements(realMovements, List<Char>::asReversed) .joinToString(separator = "") { it.last().toString() } .let(::println) testStart.toStackList() .applyMovements(testMovements) .joinToString(separator = "") { it.last().toString() } .also(::println) shouldBe "MCD" realStart.toStackList() .applyMovements(realMovements) .joinToString(separator = "") { it.last().toString() } .let(::println) } private fun List<String>.toStackList(): List<MutableList<Char>> = buildList { val nthStackSequence = 1..this@toStackList.maxOf { it.length } step 4 val stackSequence = this@toStackList.indices.reversed().asSequence().drop(1) nthStackSequence.mapTo(this) { stackIndex -> stackSequence.map { this@toStackList[it].getOrNull(stackIndex) } .takeWhile{ it != ' ' } .filterNotNull() .toMutableList() } } private val movementRegex = "\\Amove (\\d+) from (\\d+) to (\\d+)\\z".toRegex() private fun parseMovements(input: List<String>): Sequence<Movement> { return input.asSequence() .mapNotNull { movementRegex.find(it) } .map { val (_, quantity, start, end) = it.groupValues Movement(start.toInt() - 1, end.toInt() - 1, quantity.toInt()) } } private fun List<MutableList<Char>>.applyMovements( movements: Sequence<Movement>, transform: List<Char>.() -> List<Char> = ::identity, ) = movements.fold(this) { cargo, movement -> val movingItems = cargo[movement.start].run { subList(size - movement.quantity, size) } cargo[movement.end].addAll(movingItems.transform()) movingItems.clear() cargo } data class Movement( val start: Int, val end: Int, val quantity: Int, )
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,546
Advent-of-Code
Apache License 2.0
src/Day11.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import java.math.BigInteger @OptIn(ExperimentalStdlibApi::class) fun main() { fun String.takeLastInt() = takeLastWhile { it != ' ' }.toInt() fun String.takeLastBigInteger() = takeLastWhile { it != ' ' }.toBigInteger() fun String.evalInt(): Int { val tmp = this.split(' ') return when { tmp.contains("+") -> tmp.first().toInt() + tmp.last().toInt() else -> tmp.first().toInt() * tmp.last().toInt() } } fun String.evalBigInteger(): BigInteger { val tmp = this.split(' ') return when { tmp.contains("+") -> tmp.first().toBigInteger() + tmp.last().toBigInteger() else -> tmp.first().toBigInteger() * tmp.last().toBigInteger() } } fun String.eval(num: Int) = replace("old", num.toString()).evalInt() fun String.eval(num: BigInteger) = replace("old", num.toString()).evalBigInteger() fun part1(input: List<String>): Int { val monkeys = input .chunked(7) .map { it.drop(1) } val items = monkeys.map { it[0].substringAfter(": ") .split(", ") .map(String::toInt) .toMutableList() } val operation = monkeys.map { it[1].substringAfter("= ") } val test = monkeys.map { it[2].takeLastInt() } val go = monkeys.map { it[3].takeLastInt() to it[4].takeLastInt() } val n = monkeys.size val inspects = MutableList(n) { 0 } repeat(20) { (0..<n).forEach { i -> items[i].forEach { item -> inspects[i]++ val newItem = operation[i].eval(item) / 3 when (newItem % test[i] == 0) { true -> items[go[i].first].add(newItem) else -> items[go[i].second].add(newItem) } } items[i].clear() } } val (a, b) = inspects.sorted().takeLast(2) return a * b } fun part2(input: List<String>): BigInteger { val monkeys = input .chunked(7) .map { it.drop(1) } val items = monkeys.map { it[0].substringAfter(": ") .split(", ") .map(String::toBigInteger) .toMutableList() } val operation = monkeys.map { it[1].substringAfter("= ") } val test = monkeys.map { it[2].takeLastBigInteger() } val go = monkeys.map { it[3].takeLastInt() to it[4].takeLastInt() } val mod = test.reduce { acc, int -> acc * int } val n = monkeys.size val inspects = MutableList(n) { 0.toBigInteger() } repeat(10000) { (0..<n).forEach { i -> items[i] .forEach { item -> inspects[i]++ val newItem = operation[i].eval(item) % mod when (newItem % test[i] == 0.toBigInteger()) { true -> items[go[i].first].add(newItem) else -> items[go[i].second].add(newItem) } } items[i].clear() } } val (a, b) = inspects.sorted().takeLast(2) return a * b } val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158.toBigInteger()) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
3,685
aoc2022
Apache License 2.0
src/main/java/com/barneyb/aoc/aoc2022/day09/RopeBridge.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2022.day09 import com.barneyb.aoc.util.Solver import com.barneyb.aoc.util.toInt import com.barneyb.aoc.util.toSlice import com.barneyb.util.Dir import com.barneyb.util.Vec2 import kotlin.math.abs fun main() { Solver.execute( ::parse, ::partOne, ::partTwo, // 2140 is too low ) } internal fun parse(input: String) = input.toSlice() .trim() .lines() .flatMap { val d = Dir.parse(it[0]) buildList { for (i in 1..it.drop(2).toInt()) { add(d) } } } internal fun partOne(steps: List<Dir>) = positionsVisited(steps, 2) internal fun partTwo(steps: List<Dir>) = positionsVisited(steps, 10) internal fun positionsVisited(steps: List<Dir>, knots: Int): Int { val rope = Array<Vec2>(knots) { Vec2.origin() } val visited = HashSet<Vec2>() visited.add(rope.last()) for (step in steps) { rope[0] = rope[0].move(step) for (i in 1 until rope.size) { val dx = rope[i - 1].x - rope[i].x val dy = rope[i - 1].y - rope[i].y if (abs(dx) == 2) { if (abs(dy) == 2) { rope[i] += Vec2(dx / 2, dy / 2) } else { rope[i] += Vec2(dx / 2, dy) } } else if (abs(dy) == 2) { rope[i] += Vec2(dx, dy / 2) } } visited.add(rope.last()) // println() // for (y in -4..0) { // for (x in 0..5) { // val v = Vec2(x, y) // var found = false // for ((i, k) in rope.withIndex()) { // if (k != v) continue // found = true // if (i == 0) print("H") // else print(i) // break // } // if (!found) print(".") // } // println() // } } return visited.size }
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
2,046
aoc-2022
MIT License
src/Day02.kt
yturkkan-figure
487,361,256
false
{"Kotlin": 5549}
fun main() { fun part1(input: List<String>): Int { var depth = 0 var horizontal = 0 for (line in input) { val (direction, distance) = line.split(' ') when (direction) { "forward" -> horizontal += distance.toInt() "down" -> depth += distance.toInt() "up" -> depth -= distance.toInt() } } return depth * horizontal } fun part2(input: List<String>): Int { var depth = 0 var horizontal = 0 var aim = 0 for (line in input) { val (command, distance) = line.split(' ') when (command) { "forward" -> { horizontal += distance.toInt() depth += aim * distance.toInt() } "down" -> aim += distance.toInt() "up" -> aim -= distance.toInt() } } return depth * horizontal } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 150) check(part2(testInput) == 900) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cd79f4b6ac78b06cfb9b5ee381ae7427895a68c0
1,271
kotlin-aoc-2021
Apache License 2.0
src/Day07.kt
haitekki
572,959,197
false
{"Kotlin": 24688}
fun main() { fun initFileSystem (input: String): Directory { val root = Directory( parentDirectory = null, name = "root" ) var current: Directory = root for (line in input.lines()) { val splittedLine = line.split(" ") when (splittedLine[0]) { "$" -> { when (splittedLine[1]) { "cd" -> { when (splittedLine[2]) { "/" -> current = root ".." -> current = current.parentDirectory!! else -> { val newDir = current.getDirectoryWithName(splittedLine[2]) if (newDir != null) current = newDir } } } } } "dir" -> { val newDir = current.getDirectoryWithName(splittedLine[1]) if (newDir == null) { current.directories.add( Directory( parentDirectory = current, name = splittedLine[1] ) ) } } else -> { val newFile = current.getFileWithName(splittedLine[1]) if (newFile == null) { current.files.add( File( name = splittedLine[1], size = splittedLine[0].toLong() ) ) } } } } return root } fun part1(input: String): Long { val root = initFileSystem(input) val sizeList = root.getSizeList(mutableListOf()) return sizeList.filter { it <= 100000L }.sum() } fun part2(input:String): Long { val root = initFileSystem(input) val neededSpace = 30000000L - (70000000L - root.getTotalSize()) val sizeList = root.getSizeList(mutableListOf()) for (dirSize in sizeList.sorted()) { if (dirSize >= neededSpace) return dirSize } return 0 } val testInput = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent() println(part1(testInput)) println(part2(testInput)) val input = readInput("Day07") println(part1(input)) println(part2(input)) } class Directory ( val parentDirectory: Directory?, val name: String, val directories: MutableList<Directory> = mutableListOf(), val files: MutableList<File> = mutableListOf() ) { fun getSizeList(sizeList : MutableList<Long>): MutableList<Long> { val tSize = directories.map{ it.getSizeList(sizeList).last() }.sum() + files.map{ it.size }.sum() sizeList.add(tSize) return sizeList } fun getTotalSize(): Long { return directories.map{ it.getTotalSize() }.sum() + files.map{ it.size }.sum() } fun getDirectoryWithName(name: String): Directory? { for (directory in directories) { if (directory.name == name) { return directory } } return null } fun getFileWithName(name: String): File? { for (file in files) { if (file.name == name) { return file } } return null } } data class File ( val name: String, val size: Long )
0
Kotlin
0
0
b7262133f9115f6456aa77d9c0a1e9d6c891ea0f
4,246
aoc2022
Apache License 2.0
src/main/kotlin/com/ikueb/advent18/Day18.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 import com.ikueb.advent18.model.* object Day18 { fun getResourceValue(input: List<String>, iterations: Int): Int { val state: Area = input.mapIndexed { y, line -> InputLine(line.mapIndexed { x, value -> Acre(Point(x, y), Content.parse(value)) }.toSet(), "") } val seen = mutableMapOf<Int, Int>() var matched: Int? do { state.step() matched = seen.put(state.render().hashCode(), seen.size) } while (matched == null && seen.size < iterations) if (seen.size < iterations) { val current = seen[state.render().hashCode()]!! repeat(((iterations - matched!!) % (current - matched)) - 1) { state.step() } } return state.getTokens().groupBy { it.content } .let { it[Content.TREES]!!.size * it[Content.LUMBERYARD]!!.size } } } private typealias Area = InputMap<Acre> private fun Area.step() = getTokens() .associateBy { it.point } .mapValues { (_, acre) -> acre.next(this) } .forEach { point, content -> get(point)?.content = content } private fun Area.near(acre: Acre, min: Int, target: Content) = acre.point.adjacent.count { get(it)?.content == target } >= min private fun Area.get(point: Point) = if (point.y in 0..(size - 1)) { this[point.y].tokens().firstOrNull { it.atColumn(point.x) } } else null private data class Acre( override var point: Point, var content: Content) : InputToken(point) { override fun isActive() = true override fun toString() = content.output.toString() fun next(state: Area) = when (content) { Content.OPEN -> if (state.near(this, 3, Content.TREES)) Content.TREES else content Content.TREES -> if (state.near(this, 3, Content.LUMBERYARD)) Content.LUMBERYARD else content Content.LUMBERYARD -> if (state.near(this, 1, Content.LUMBERYARD) && state.near(this, 1, Content.TREES)) Content.LUMBERYARD else Content.OPEN } } private enum class Content(val output: Char) { OPEN('.'), TREES('|'), LUMBERYARD('#'); companion object { fun parse(value: Char) = values().find { it.output == value } ?: throw IllegalArgumentException("Unknown content.") } }
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
2,466
advent18
Apache License 2.0
src/main/kotlin/aoc/year2023/Day01.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2023 import aoc.Puzzle /** * [Day 1 - Advent of Code 2023](https://adventofcode.com/2023/day/1) */ object Day01 : Puzzle<Int, Int> { private val digitMap = mapOf( "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, "1" to 1, "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9, ) override fun solvePartOne(input: String): Int { fun getCalibrationValue(line: String): Int { val firstDigit = line.find(Char::isDigit)!!.digitToInt() val lastDigit = line.findLast(Char::isDigit)!!.digitToInt() return (firstDigit * 10) + lastDigit } return input.lineSequence().sumOf(::getCalibrationValue) } override fun solvePartTwo(input: String): Int { fun getCalibrationValue(line: String): Int { val firstDigit = digitMap.mapKeys { line.indexOf(it.key) }.filterKeys { it >= 0 }.minBy { it.key }.value val lastDigit = digitMap.mapKeys { line.lastIndexOf(it.key) }.filterKeys { it >= 0 }.maxBy { it.key }.value return (firstDigit * 10) + lastDigit } return input.lineSequence().sumOf(::getCalibrationValue) } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,398
advent-of-code
Apache License 2.0
src/main/kotlin/g2301_2400/s2360_longest_cycle_in_a_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2360_longest_cycle_in_a_graph // #Hard #Depth_First_Search #Graph #Topological_Sort // #2023_07_02_Time_517_ms_(80.00%)_Space_59.3_MB_(100.00%) class Solution { fun longestCycle(edges: IntArray): Int { val n = edges.size val vis = BooleanArray(n) val dfsvis = BooleanArray(n) val path = IntArray(n) var maxLength = -1 for (i in 0 until n) { if (!vis[i]) { path[i] = 1 maxLength = Math.max(maxLength, dfs(i, 1, path, vis, dfsvis, edges)) } } return maxLength } private fun dfs( node: Int, pathLength: Int, path: IntArray, vis: BooleanArray, dfsvis: BooleanArray, edges: IntArray ): Int { vis[node] = true dfsvis[node] = true var length = -1 if (edges[node] != -1 && !vis[edges[node]]) { path[edges[node]] = pathLength + 1 length = dfs(edges[node], pathLength + 1, path, vis, dfsvis, edges) } else if (edges[node] != -1 && dfsvis[edges[node]]) { length = pathLength - path[edges[node]] + 1 } dfsvis[node] = false return length } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,240
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/simonorono/aoc2015/solutions/Day13.kt
simonorono
662,846,819
false
{"Kotlin": 28492}
package com.simonorono.aoc2015.solutions import com.simonorono.aoc2015.lib.Day object Day13 : Day(13) { private val REGEX = """(.+) would (.+) (\d+) happiness units by sitting next to (.+).""".toRegex() private val happinessMap: HashMap<String, HashMap<String, Int>> = hashMapOf() init { for (line in getInput().lines()) { val match = REGEX.matchEntire(line) val (_, who, what, howMuch, neighbor) = match?.groupValues!! var mod = howMuch.toInt() if (what == "lose") { mod = -mod } if (happinessMap.contains(who)) { happinessMap[who]!![neighbor] = mod } else { happinessMap[who] = hashMapOf(neighbor to mod) } } } private fun getNeighbors(index: Int, max: Int): Pair<Int, Int> { return when (index) { 0 -> 1 to max max -> 0 to max - 1 else -> index - 1 to index + 1 } } private fun calculateHappiness(list: Array<String>): Int { var happiness = 0 for (i in list.indices) { val (leftIdx, rightIdx) = getNeighbors(i, list.size - 1) val guest = list[i] val left = list[leftIdx] val right = list[rightIdx] happiness += (happinessMap[guest]!![left]!! + happinessMap[guest]!![right]!!) } return happiness } override fun part1(): String { var max = 0 for (permutation in calculatePermutations(happinessMap.keys.toTypedArray())) { val happiness = calculateHappiness(permutation) if (happiness > max) { max = happiness } } return max.toString() } override fun part2(): String { happinessMap["Me"] = hashMapOf() for (key in happinessMap.keys) { happinessMap["Me"]!![key] = 0 happinessMap[key]!!["Me"] = 0 } var max = 0 for (permutation in calculatePermutations(happinessMap.keys.toTypedArray())) { val happiness = calculateHappiness(permutation) if (happiness > max) { max = happiness } } return max.toString() } }
0
Kotlin
0
0
0fec1d4db5b68ea8ee05b20c535df1b7f5570056
2,309
aoc2015
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxNumberOfApples.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import java.util.Queue import kotlin.math.max import kotlin.math.min private const val BASKET_SIZE = 5000 /** * How Many Apples Can You Put into the Basket. * You have some apples, where arr[i] is the weight of the i-th apple. * You also have a basket that can carry up to 5000 units of weight. * Return the maximum number of apples you can put in the basket. */ fun interface MaxNumberOfApples { operator fun invoke(arr: IntArray): Int } /** * Time Complexity: O(NlogN). * Space Complexity: O(1). */ class MaxNumberOfApplesSort : MaxNumberOfApples { override operator fun invoke(arr: IntArray): Int { arr.sort() var apples = 0 var units = 0 var i = 0 while (i < arr.size && units + arr[i] <= BASKET_SIZE) { apples++ units += arr[i] i++ } return apples } } /** * Time Complexity: O(NlogN). * Space Complexity: O(1). */ class MaxNumberOfApplesMinHeap : MaxNumberOfApples { override operator fun invoke(arr: IntArray): Int { val heap: Queue<Int> = PriorityQueue() var apples = 0 var units = 0 for (weight in arr) { heap.add(weight) } while (heap.isNotEmpty() && units + heap.peek() <= BASKET_SIZE) { units += heap.remove() apples++ } return apples } } /** * Time Complexity: O(N + W). , where N is the length of arr and W is the largest element in arr. * This is because we iterate through arr and bucket once and the lengths are N and W accordingly. * Space Complexity: O(W). This is because we initialize an array bucket with the size of max(arr). */ class MaxNumberOfApplesBucketSort : MaxNumberOfApples { override operator fun invoke(arr: IntArray): Int { // initialize the bucket to store all elements var size = -1 for (weight in arr) { size = max(size, weight) } val bucket = IntArray(size + 1) for (weight in arr) { bucket[weight]++ } var apples = 0 var units = 0 for (i in 0 until size + 1) { // if we have apples of i units of weight if (bucket[i] != 0) { // we need to make sure that: // 1. we do not take more apples than those provided // 2. we do not exceed 5000 units of weight val take = min(bucket[i], (BASKET_SIZE - units) / i) if (take == 0) { break } units += take * i apples += take } } return apples } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,345
kotlab
Apache License 2.0
src/Day04.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
fun main() { fun List<String>.parseList(): List<List<Set<Int>>> = this.map { line -> line.split(',').map { region -> region.split('-').map(String::toInt).let { (begin, end) -> (begin..end).toSet() } } } fun part1(input: List<String>): Int = input.parseList() .count { (first, second) -> (first subtract second).isEmpty() || (second subtract first).isEmpty()} fun part2(input: List<String>): Int = input.parseList() .count { (first, second) -> (first intersect second).isNotEmpty()} // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val part1 = part1(testInput) check(part1 == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
847
aoc-2022-demo
Apache License 2.0
src/chapter3/section2/ex30_OrderCheck.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter3.section2 import edu.princeton.cs.algs4.Queue /** * 有序性检查 * 编写一个递归的方法isOrdered(),接受一个结点Node和min、max两个键作为参数。 * 如果以该结点为根的子树中所有结点都在min和max之间,min和max的确分别是树中最小和最大的结点 * 且二叉查找树的有序性对树中的所有键都成立,返回true,否则返回false */ fun <K : Comparable<K>> isOrdered(node: BinarySearchTree.Node<K, *>, min: K, max: K): Boolean { val queue = Queue<BinarySearchTree.Node<K, *>>() collectAllNode(node, queue) var lastNode = queue.dequeue() if (lastNode.key != min) return false while (!queue.isEmpty) { val nextNode = queue.dequeue() if (lastNode.key >= nextNode.key) return false lastNode = nextNode } return lastNode.key == max } /** * 从小到大将所有结点依次加入队列中 */ fun <K : Comparable<K>> collectAllNode(node: BinarySearchTree.Node<K, *>, queue: Queue<BinarySearchTree.Node<K, *>>) { if (node.left != null) { collectAllNode(node.left!!, queue) } queue.enqueue(node) if (node.right != null) { collectAllNode(node.right!!, queue) } } fun main() { val charArray = "EASYQUESTION".toCharArray() val bst = BinarySearchTree<Char, Int>() for (i in charArray.indices) { bst.put(charArray[i], i) } println(isOrdered(bst.root!!, 'A', 'Y')) println(isOrdered(bst.root!!, 'A', 'S')) println(isOrdered(bst.root!!, 'E', 'Y')) println(isOrdered(bst.root!!, 'A', 'Z')) val node = BinarySearchTree.Node(5, 0) node.left = BinarySearchTree.Node(2, 0) node.left!!.left = BinarySearchTree.Node(1, 0) node.left!!.right = BinarySearchTree.Node(5, 0) //放开下面注释返回true // node.left!!.right = BinarySearchTree.Node(4, 0) node.right = BinarySearchTree.Node(8, 0) node.right!!.left = BinarySearchTree.Node(7, 0) node.right!!.right = BinarySearchTree.Node(9, 0) println(isOrdered(node, 1, 9)) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,060
Algorithms-4th-Edition-in-Kotlin
MIT License
src/day20/Day20.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day20 import readInput fun main() { val day = 20 val testInput = readInput("day$day/testInput") // check(part1(testInput) == 3L) // check(part2(testInput) == 1623178306L) val input = readInput("day$day/input") // println(part1B(input)) println(part2(input)) } data class MarkedNumber(val number: Long, var isMarked: Boolean = false, val orderNum: Int = -1) fun part1(input: List<String>): Long { val markedNumbers: MutableList<MarkedNumber> = input.map { it.toLong() }.map { MarkedNumber(it) }.toMutableList() fun getNextNotMarkedIndex(): Int = markedNumbers.indexOfFirst { !it.isMarked } var index = getNextNotMarkedIndex() while (index != -1) { val number = markedNumbers[index].number var newIndex = index + number newIndex %= (markedNumbers.size - 1) if (newIndex <= 0) { newIndex += markedNumbers.size - 1 } val intNewIndex = newIndex.toInt() if (intNewIndex > index) { for (i in index..intNewIndex) { if (i == intNewIndex) { markedNumbers[i] = MarkedNumber(number, true) } else { markedNumbers[i] = markedNumbers[i + 1] } } } else { for (i in index downTo intNewIndex) { if (i == intNewIndex) { markedNumbers[i] = MarkedNumber(number, true) } else { markedNumbers[i] = markedNumbers[i - 1] } } } index = getNextNotMarkedIndex() } println(markedNumbers.map { it.number }) val zeroIndex = markedNumbers.indexOfFirst { it.number == 0L } println("zeroIndex: $zeroIndex") val x = markedNumbers[(zeroIndex + 1000) % markedNumbers.size].number val y = markedNumbers[(zeroIndex + 2000) % markedNumbers.size].number val z = markedNumbers[(zeroIndex + 3000) % markedNumbers.size].number return x + y + z } fun part1B(input: List<String>): Long { val markedNumbers: MutableList<MarkedNumber> = input.map { it.toLong() } .mapIndexed { index, num -> MarkedNumber(num, orderNum = index) } .toMutableList() var orderNum = 0 while (orderNum != markedNumbers.size) { val index = markedNumbers.indexOfFirst { it.orderNum == orderNum } val number = markedNumbers[index].number var newIndex = index + number newIndex %= (markedNumbers.size - 1) if (newIndex <= 0) { newIndex += markedNumbers.size - 1 } val intNewIndex = newIndex.toInt() if (intNewIndex > index) { for (i in index..intNewIndex) { if (i == intNewIndex) { markedNumbers[i] = MarkedNumber(number, orderNum = orderNum) } else { markedNumbers[i] = markedNumbers[i + 1] } } } else { for (i in index downTo intNewIndex) { if (i == intNewIndex) { markedNumbers[i] = MarkedNumber(number, orderNum = orderNum) } else { markedNumbers[i] = markedNumbers[i - 1] } } } orderNum++ } println(markedNumbers.map { it.number }) val zeroIndex = markedNumbers.indexOfFirst { it.number == 0L } println("zeroIndex: $zeroIndex") val x = markedNumbers[(zeroIndex + 1000) % markedNumbers.size].number val y = markedNumbers[(zeroIndex + 2000) % markedNumbers.size].number val z = markedNumbers[(zeroIndex + 3000) % markedNumbers.size].number return x + y + z } fun part2(input: List<String>): Long { val decryptionKey = 811589153L val markedNumbers = input.map { it.toInt() * decryptionKey } .mapIndexed { i, num -> MarkedNumber(num, orderNum = i) } .toMutableList() println("Initial:") println(markedNumbers.map { it.number }) repeat(10) { round -> var orderNum = 0 while (orderNum != markedNumbers.size) { val index = markedNumbers.indexOfFirst { it.orderNum == orderNum } val number = markedNumbers[index].number var newIndex: Long = index + number newIndex %= (markedNumbers.size - 1) if (newIndex <= 0) { newIndex += markedNumbers.size - 1 } val intNewIndex = newIndex.toInt() if (intNewIndex > index) { for (i in index..intNewIndex) { if (i == intNewIndex) { markedNumbers[i] = MarkedNumber(number, orderNum = orderNum) } else { markedNumbers[i] = markedNumbers[i + 1] } } } else { for (i in index downTo intNewIndex) { if (i == intNewIndex) { markedNumbers[i] = MarkedNumber(number, orderNum = orderNum) } else { markedNumbers[i] = markedNumbers[i - 1] } } } orderNum++ } println("round: ${round + 1}") println(markedNumbers.map { it.number }) } val zeroIndex = markedNumbers.indexOfFirst { it.number == 0L } println("zeroIndex: $zeroIndex") val x = markedNumbers[(zeroIndex + 1000) % markedNumbers.size].number val y = markedNumbers[(zeroIndex + 2000) % markedNumbers.size].number val z = markedNumbers[(zeroIndex + 3000) % markedNumbers.size].number println("x: $x") println("y: $y") println("z: $z") return x + y + z }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
5,731
advent-of-code-2022
Apache License 2.0
src/Day19.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import ResourceType.* val inputRegex = "^Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.$".toRegex() data class RobotConfig( val oreCost: Int, val clayCost: Int, val obsCost: Pair<Int, Int>, val geodeCost: Pair<Int, Int> ) data class Resources(val ore: Resource, val clay: Resource, val obs: Resource, val geode: Resource) { fun tick() { ore.tick() clay.tick() obs.tick() geode.tick() } fun withOre(ore: Resource): Resources { return Resources( ore, clay.copy(), obs.copy(), geode.copy() ) } fun withOreAndClay(ore: Resource, clay: Resource): Resources = Resources( ore, clay, obs.copy(), geode.copy() ) fun copy(): Resources = Resources(ore.copy(), clay.copy(), obs.copy(), geode.copy()) } enum class ResourceType { ORE { override fun buildRobot(config: RobotConfig, r: Resources): Resources = r.withOre(r.ore.build(config.oreCost)) override fun canBuild(config: RobotConfig, r: Resources): Boolean { return r.ore.value >= config.oreCost } }, CLAY { override fun buildRobot(config: RobotConfig, r: Resources): Resources = r.withOreAndClay(r.ore - config.clayCost, r.clay.build()) override fun canBuild(config: RobotConfig, r: Resources): Boolean { return r.ore.value >= config.clayCost } }, OBS { override fun buildRobot(config: RobotConfig, r: Resources): Resources = Resources( r.ore - config.obsCost.first, r.clay - config.obsCost.second, r.obs.build(), r.geode.copy() ) override fun canBuild(config: RobotConfig, r: Resources): Boolean { return r.ore.value >= config.obsCost.first && r.clay.value >= config.obsCost.second } }, GEODE{ override fun buildRobot(config: RobotConfig, r: Resources): Resources = Resources( r.ore - config.geodeCost.first, r.clay.copy(), r.obs - config.geodeCost.second, r.geode.build() ) override fun canBuild(config: RobotConfig, r: Resources): Boolean { return r.ore.value >= config.geodeCost.first && r.obs.value >= config.geodeCost.second } }; abstract fun buildRobot(config: RobotConfig, r: Resources): Resources abstract fun canBuild(config: RobotConfig, r: Resources): Boolean } data class Resource(var value: Int = 0, val gain: Int = 0) { fun tick() { value += gain } fun hasGain(): Boolean = gain > 0 fun build(cost: Int = 0) = Resource(value - cost, gain + 1) operator fun minus(value: Int): Resource = Resource(this.value - value, gain) override fun toString(): String { return "$value[$gain]" } } var cap = 0 fun main() { fun maxGeode(time: Int, config: RobotConfig, r: Resources, buildOrder: List<Pair<ResourceType, Int>> = emptyList()): Pair<Int,List<Pair<ResourceType, Int>>> { if (time < 2) { if (time == 1) r.tick() return r.geode.value to buildOrder } val capIdle = r.geode.value + r.geode.gain * time if (capIdle > cap) { cap = capIdle } if (capIdle + (time * (time - 1)) / 2 < cap) { return r.geode.value to buildOrder } val toBuild = mutableListOf(ORE, CLAY) if (r.clay.hasGain()) { toBuild.add(OBS) } if (r.obs.hasGain()) toBuild.add(GEODE) var maxGeode: Pair<Int,List<Pair<ResourceType, Int>>> = 0 to emptyList() var timeLeft = time while (toBuild.isNotEmpty() && timeLeft > 0) { val toBuildIterator = toBuild.iterator() while(toBuildIterator.hasNext()) { val type = toBuildIterator.next() if (type.canBuild(config, r)) { if (type == GEODE) { val a = 1 } val rCopy = r.copy() rCopy.tick() val withBuilt = maxGeode(timeLeft - 1, config, type.buildRobot(config, rCopy), buildOrder /*+ (type to timeLeft)*/) if (withBuilt.first > maxGeode.first) { maxGeode = withBuilt } toBuildIterator.remove() } } timeLeft-- r.tick() } return maxGeode } fun part1(input: List<String>): Int { var output = 0 input.forEach { cap = 0 val match = inputRegex.matchEntire(it) ?: throw IllegalArgumentException("Invalid regex for input string $it") val (number, oreCost, clayCost, obsOreCost, obsClayCost, geodeOreCost, geodeObsCost) = match.destructured val config = RobotConfig( oreCost.toInt(), clayCost.toInt(), obsOreCost.toInt() to obsClayCost.toInt(), geodeOreCost.toInt() to geodeObsCost.toInt() ) val maxGeode = maxGeode( 24, config, Resources( Resource(0, 1), Resource(), Resource(), Resource() ) ) output += number.toInt() * maxGeode.first } return output } fun part2(input: List<String>): Int { var output = 1 input.take(if (input.size > 3) 3 else 2).forEach { cap = 0 val match = inputRegex.matchEntire(it) ?: throw IllegalArgumentException("Invalid regex for input string $it") val (number, oreCost, clayCost, obsOreCost, obsClayCost, geodeOreCost, geodeObsCost) = match.destructured val config = RobotConfig( oreCost.toInt(), clayCost.toInt(), obsOreCost.toInt() to obsClayCost.toInt(), geodeOreCost.toInt() to geodeObsCost.toInt() ) val maxGeode = maxGeode( 32, config, Resources( Resource(0, 1), Resource(), Resource(), Resource() ) ) println("Build order $maxGeode") output *= maxGeode.first } return output } // test if implementation meets criteria from the description, like: val testInput = readInput("Day19_test") println("test1: " + part1(testInput)) check(part1(testInput) == 33) check(part2(testInput) == 62*56) val input = readInput("Day19") val part1Result = part1(input) println(part1Result) check(part1Result == 1650) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
7,022
advent-of-code-2022
Apache License 2.0
src/main/kotlin/icfp2019/Brain.kt
teemobean
193,117,049
true
{"JavaScript": 797310, "Kotlin": 129405, "CSS": 9434, "HTML": 5859, "Shell": 70}
package icfp2019 import icfp2019.core.DistanceEstimate import icfp2019.core.Strategy import icfp2019.core.applyAction import icfp2019.model.Action import icfp2019.model.GameState import icfp2019.model.Problem import icfp2019.model.RobotId fun strategySequence( initialGameState: GameState, strategy: Strategy, robotId: RobotId, initialAction: Action = Action.DoNothing ): Sequence<Pair<GameState, Action>> { return generateSequence( seed = initialGameState to initialAction, nextFunction = { (gameState, _) -> if (gameState.isGameComplete()) null else { val nextAction = strategy.compute(gameState)(robotId, gameState) val nextState = applyAction(gameState, robotId, nextAction) nextState to nextAction } } ).drop(1) // skip the initial state } data class BrainScore( val robotId: RobotId, val gameState: GameState, val action: Action, val distanceEstimate: DistanceEstimate, val strategy: Strategy ) fun Sequence<Pair<GameState, Action>>.score( robotId: RobotId, strategy: Strategy ): BrainScore { // grab the first and last game state in this simulation path val (initial) = map { it to it.first } .reduce { (initial, _), (_, final) -> initial to final } // return the initial game state, if this path is the winner // we can use this to avoid duplicate action evaluation // DISABLE THIS return BrainScore( robotId, initial.first, initial.second, DistanceEstimate(0), strategy ) } fun brainStep( initialGameState: GameState, strategy: Strategy, maximumSteps: Int ): Pair<GameState, Map<RobotId, Action>> { // one time step consists of advancing each worker wrapper by N moves // this will determine the order in which to advance robots by running // all robot states through all strategies, picking the the winning // robot/state pair and resuming until the stack of robots is empty // the list of robots can change over time steps, get a fresh copy each iteration var gameState = initialGameState val actions = mutableMapOf<RobotId, Action>() val workingSet = gameState.allRobotIds.toMutableSet() while (!gameState.isGameComplete() && workingSet.isNotEmpty()) { // pick the minimum across all robot/strategy pairs val winner = workingSet .map { robotId -> strategySequence(gameState, strategy, robotId) .take(maximumSteps) .score(robotId, strategy) } val winner0 = winner.minBy { it.distanceEstimate }!! // we have a winner, remove it from the working set for this time step workingSet.remove(winner0.robotId) // record the winning action and update the running state actions[winner0.robotId] = winner0.action gameState = winner0.gameState } return gameState to actions } fun brain( problem: Problem, strategy: Strategy, maximumSteps: Int ): Sequence<Solution> = generateSequence( seed = GameState(problem) to mapOf<RobotId, List<Action>>(), nextFunction = { (gameState, actions) -> if (gameState.isGameComplete()) { null } else { val (newState, newActions) = brainStep(gameState, strategy, maximumSteps) val mergedActions = actions.toMutableMap() newActions.forEach { (robotId, action) -> mergedActions.merge(robotId, listOf(action)) { left, right -> left.plus(right) } } newState to mergedActions.toMap() } } ).map { (_, actions) -> Solution(problem, actions) }
13
JavaScript
12
0
a1060c109dfaa244f3451f11812ba8228d192e7d
3,814
icfp-2019
The Unlicense
api/src/main/kotlin/dev/kosmx/needle/util/KMP.kt
KosmX
651,103,285
false
{"Kotlin": 73311}
package dev.kosmx.needle.util /** * O(n+m) pattern matching with Knuth-Morris-Pratt algo * * @param T has to be comparable (== or .equals has to work as data-classes) */ class Word<T>(val word: Array<T>, private val comparator: (T, T) -> Boolean = { a, b -> a == b }) { init { require(word.isNotEmpty()) { "Matcher can't match empty word" } } private val pattern = Pattern() fun matcher() = Matcher(pattern) inner class Matcher internal constructor (private val pattern: Pattern) { val word: Array<T> get() = this@Word.word private var pos = -1 /** * Matcher check next entry * @return true if full match present */ fun checkNextChar(char: T): Boolean { pos++ findLoop@ while (pos >= 0) { if (comparator(char, word[pos]) ) { break@findLoop } else { pos = pattern.table[pos] } } if (pos + 1 == word.size) { pos = pattern.table[pos + 1] return true } return false } } inner class Pattern internal constructor() { internal val table: IntArray = IntArray(word.size + 1) //https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm init { table[0] = -1 var cnd = 0 for (i in word.indices.drop(1)) { if (comparator(word[i], word[cnd])) { table[i] = table[cnd] } else { table[i] = cnd while (cnd >= 0 && !comparator(word[cnd], word[i])) { cnd = table[cnd] } } cnd++ } table[word.size] = cnd } } } fun <T> Word<T>.match(iterable: Iterable<T>) = match(iterable.asSequence()) fun <T> Word<T>.match(sequence: Sequence<T>): Int = match(sequence.iterator()) fun <T> Word<T>.match(sequence: Iterator<T>): Int { val m = matcher() var pos = 0 sequence.forEach { if (m.checkNextChar(it)) { return@match pos - word.size + 1 } pos++ } return -1 }
20
Kotlin
2
60
b8d3ed169a9d9cdee4bcebea015a27b1f6740f84
2,346
jneedle
MIT License
src/main/kotlin/adventofcode/year2022/Day07NoSpaceLeftOnDevice.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2022 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day07NoSpaceLeftOnDevice(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val files by lazy { input.lines().fold(emptyList<String>() to emptySet<File>()) { (currentPath, files), line -> val (size, name) = line.split(" ") when { line == "$ cd .." -> currentPath.dropLast(1) to files line.startsWith("$ cd ") -> currentPath + listOf(line.split(" ").last()) to files line.startsWith("dir") -> currentPath to files + File(name, currentPath.joinToString("/"), 0) line.first().isDigit() -> currentPath to files + File(name, currentPath.joinToString("/"), size.toInt()) else -> currentPath to files } } .second } private val directories by lazy { files .map(File::path) .toSet() .map { directory -> directory to files.filter { file -> file.path.startsWith(directory) }.sumOf { file -> file.size } } } override fun partOne() = directories .filter { (_, size) -> size <= 100000 } .sumOf { (_, size) -> size } override fun partTwo() = directories .filter { (_, size) -> size >= REQUIRED_SPACE - (TOTAL_DISK_SPACE - directories.maxOf { (_, size) -> size }) } .minBy { (_, size) -> size } .second companion object { private const val TOTAL_DISK_SPACE = 70000000 private const val REQUIRED_SPACE = 30000000 private data class File( val name: String, val path: String, val size: Int ) } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,723
AdventOfCode
MIT License
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/Backtracking.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* Use this technique to build a solution incrementally and follow the approach that if the current solution can’t lead to a valid solution, abandon it and backtrack (or go back) to try another solution. */ //1. Combination Sum fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { val result = mutableListOf<List<Int>>() val currentCombination = mutableListOf<Int>() fun backtrack(startIndex: Int, remainingTarget: Int) { if (remainingTarget < 0) { return } if (remainingTarget == 0) { result.add(ArrayList(currentCombination)) return } for (i in startIndex until candidates.size) { currentCombination.add(candidates[i]) backtrack(i, remainingTarget - candidates[i]) currentCombination.removeAt(currentCombination.size - 1) } } backtrack(0, target) return result } fun main() { // Example usage val candidates = intArrayOf(2, 3, 6, 7) val target = 7 val result = combinationSum(candidates, target) println("Combinations for target $target: $result") } //2. Sudoku Solver fun solveSudoku(board: Array<CharArray>) { fun isValid(row: Int, col: Int, num: Char): Boolean { // Check if the number is not present in the current row, column, and 3x3 subgrid for (i in 0 until 9) { if (board[row][i] == num || board[i][col] == num || board[row - row % 3 + i / 3][col - col % 3 + i % 3] == num) { return false } } return true } fun solve(): Boolean { for (i in 0 until 9) { for (j in 0 until 9) { if (board[i][j] == '.') { for (num in '1'..'9') { if (isValid(i, j, num)) { board[i][j] = num if (solve()) { return true } board[i][j] = '.' // Backtrack } } return false // No valid number for the current cell } } } return true // All cells are filled } solve() } fun printSudoku(board: Array<CharArray>) { for (i in 0 until 9) { for (j in 0 until 9) { print("${board[i][j]} ") } println() } } fun main() { // Example usage val sudokuBoard = arrayOf( charArrayOf('5', '3', '.', '.', '7', '.', '.', '.', '.'), charArrayOf('6', '.', '.', '1', '9', '5', '.', '.', '.'), charArrayOf('.', '9', '8', '.', '.', '.', '.', '6', '.'), charArrayOf('8', '.', '.', '.', '6', '.', '.', '.', '3'), charArrayOf('4', '.', '.', '8', '.', '3', '.', '.', '1'), charArrayOf('7', '.', '.', '.', '2', '.', '.', '.', '6'), charArrayOf('.', '6', '.', '.', '.', '.', '2', '8', '.'), charArrayOf('.', '.', '.', '4', '1', '9', '.', '.', '5'), charArrayOf('.', '.', '.', '.', '8', '.', '.', '7', '9') ) println("Sudoku Board:") printSudoku(sudokuBoard) solveSudoku(sudokuBoard) println("\nSolved Sudoku Board:") printSudoku(sudokuBoard) }
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
3,271
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindPeakElement.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode fun interface FindPeakElementStrategy { operator fun invoke(nums: IntArray): Int } class FindPeakElementLinear : FindPeakElementStrategy { override operator fun invoke(nums: IntArray): Int { return helper(nums, 0, nums.lastIndex) } private fun helper(num: IntArray, start: Int, end: Int): Int { return when { num.isEmpty() -> { 0 } start == end -> { start } start + 1 == end -> { if (num[start] > num[end]) start else end } else -> { val m = (start + end) / 2 if (num[m] > num[m - 1] && num[m] > num[m + 1]) { m } else if (num[m - 1] > num[m] && num[m] > num[m + 1]) { helper(num, start, m - 1) } else { helper(num, m + 1, end) } } } } } class FindPeakElementRecursiveBinarySearch : FindPeakElementStrategy { override operator fun invoke(nums: IntArray): Int { return search(nums, 0, nums.lastIndex) } private fun search(nums: IntArray, l: Int, r: Int): Int { if (nums.isEmpty()) return 0 if (l == r) return l val mid = (l + r) / 2 return if (nums[mid] > nums[mid + 1]) search(nums, l, mid) else search(nums, mid + 1, r) } } class FindPeakElementIterativeBinarySearch : FindPeakElementStrategy { override operator fun invoke(nums: IntArray): Int { var l = 0 var r: Int = nums.lastIndex while (l < r) { val mid = (l + r) / 2 if (nums[mid] > nums[mid + 1]) r = mid else l = mid + 1 } return l } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,401
kotlab
Apache License 2.0
src/Day03.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
fun main() { fun part1(input: List<String>): Int { var sum = 0; for (line in input) { var set = mutableSetOf<Char>(); var s1 = line.substring(0, line.length/2); var s2 = line.substring(line.length/2); for (c in s1) { set.add(c); } for (c in s2) { if (set.contains(c)) { sum += if (c in 'a'..'z') c.code - 'a'.code + 1; else c.code - 'A'.code + 27; break; } } } return sum; } fun part2(input: List<String>): Int { var sum = 0; for (i in 0..input.size-1 step 3) { var set1 = mutableSetOf<Char>(); var set2 = mutableSetOf<Char>(); var set3 = mutableSetOf<Char>(); for (c in input[i]) { set1.add(c); } for (c in input[i+1]) { set2.add(c); } for (c in input[i+2]) { set3.add(c); } for (c in set1) { if (set2.contains(c) && set3.contains(c)) { sum += if (c in 'a'..'z') c.code - 'a'.code + 1; else c.code - 'A'.code + 27; break; } } } return sum; } val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
1,480
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/days/Day12.kt
vovarova
572,952,098
false
{"Kotlin": 103799}
package days import java.util.* class Day12() : Day(12) { class HeightMap(input: List<String>) { val heightMap: Array<Array<Char>> val start: Cell val end: Cell val acells: List<Cell> init { val rows = input.size val columns = input[0].length val aCells = mutableListOf<Cell>() heightMap = Array(rows) { Array(columns) { 'a' } } var startIntermediate = Cell(0, 0) var endIntermediate = Cell(0, 0) for (i in 0 until rows) { for (j in 0 until columns) { if (input[i][j] == 'S') { startIntermediate = Cell(i, j) } else if (input[i][j] == 'E') { endIntermediate = Cell(i, j) } else if (input[i][j] == 'a') { aCells.add(Cell(i, j)) } heightMap[i][j] = input[i][j] } } acells = aCells start = startIntermediate end = endIntermediate } fun startPath(): Path = Path(listOf(start)) fun startPathWithAllA(): List<Path> { return (acells + start).map { Path(listOf(it)) } } inner class Cell(val row: Int, val column: Int) { fun up(): Cell = Cell(row + 1, column) fun down(): Cell = Cell(row - 1, column) fun left(): Cell = Cell(row, column - 1) fun right(): Cell = Cell(row, column + 1) fun equalsCell(other: Cell): Boolean { return this.row == other.row && this.column == other.column } fun isValidCell(): Boolean { return row >= 0 && row < heightMap.size && column >= 0 && column < heightMap[row].size } fun toPair(): Pair<Int, Int> = Pair(row, column) fun getValue(): Char { return if (equalsCell(start)) { 'a' } else if (equalsCell(end)) { 'z' } else { heightMap[row][column] } } } inner class Path(val cells: List<Cell>) { fun isFinished(): Boolean = cells.last().equalsCell(end) fun head(): Cell = cells.last() fun addCell(cell: Cell): Path = Path(cells + cell) fun possiblePath(): List<Path> { val last = cells.last() return listOf(last.up(), last.down(), last.left(), last.right()) .filter { it.isValidCell() }.filter { it.getValue().code <= last.getValue().code + 1 } .map { this.addCell(it) } } } } fun breadthForSearch(startPath: List<HeightMap.Path>): HeightMap.Path { val fifoQueue = LinkedList<HeightMap.Path>() fifoQueue.addAll(startPath) val visitedCells: MutableSet<Pair<Int, Int>> = mutableSetOf() while (fifoQueue.isNotEmpty()) { val poll = fifoQueue.poll() val possiblePath = poll.possiblePath() .filter { visitedCells.add(it.head().toPair()) } fifoQueue.addAll(possiblePath) val finished = possiblePath.find { it.isFinished() } if (finished != null) { return finished } } return startPath.last() } fun deepForSearch(startPath: List<HeightMap.Path>, lastCell: HeightMap.Cell): Int { val lifoQueue = LinkedList<HeightMap.Path>() lifoQueue.addAll(startPath) val visitedCells: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() while (lifoQueue.isNotEmpty()) { val poll = lifoQueue.pollLast() val possiblePath = poll.possiblePath() .filter { visitedCells.getOrDefault(it.head().toPair(), Int.MAX_VALUE) > it.cells.size } .also { it.forEach { visitedCells.put(it.head().toPair(), it.cells.size) } }.filter { !lastCell.equalsCell(it.head()) } lifoQueue.addAll(possiblePath) } return visitedCells[lastCell.toPair()]!! - 1 } override fun partOne(): Any { return breadthForSearch(listOf(HeightMap(inputList).startPath())).cells.size - 1 } override fun partTwo(): Any { return breadthForSearch(HeightMap(inputList).startPathWithAllA()).cells.size - 1 } fun partTwoDeepForSarch(): Any { val heightMap = HeightMap(inputList) return deepForSearch(heightMap.startPathWithAllA(), heightMap.end) } }
0
Kotlin
0
0
e34e353c7733549146653341e4b1a5e9195fece6
4,774
adventofcode_2022
Creative Commons Zero v1.0 Universal
src/Day03.kt
seana-zr
725,858,211
false
{"Kotlin": 28265}
import java.util.regex.Pattern import kotlin.math.max import kotlin.math.min fun main() { // [start, end) fun extractNumbersWithIndices(line: String): List<Triple<Int, Int, Int>> { val pattern = Pattern.compile("\\d+") val matcher = pattern.matcher(line) val matches = mutableListOf<Triple<Int, Int, Int>>() while (matcher.find()) { val start = matcher.start() val end = matcher.end() val number = matcher.group().toInt() matches.add(Triple(number, start, end)) } return matches } fun isPartNumber(row: Int, startCol: Int, endCol: Int, input: List<String>): Boolean { val startRowBound = max(0, row - 1) val endRowBound = min(input.size - 1, row + 1) val startColBound = max(0, startCol - 1) val endColBound = min(input.first().length - 1, endCol) print("row $row startCol $startCol endCol $endCol \t") print("rows [$startRowBound,$endRowBound]\tcols [$startColBound,$endColBound]\t") for (r in startRowBound .. endRowBound) { for (c in startColBound .. endColBound) { if (r == row && startCol <= c && c < endCol) continue if (input[r][c] != '.' && !input[r][c].isDigit()) { println("${input[r][c]} at ($r, $c)") return true } } } println("no") return false } fun part1(input: List<String>): Int { var result = 0 input.forEachIndexed { row, s -> for ((n, start, end) in extractNumbersWithIndices(s)) { print("$n: \t") if (isPartNumber(row, start, end, input)) { result += n } } } println(result) return result } fun extractGearCandidateIndices(line: String): List<Int> { val pattern = Pattern.compile("\\*") val matcher = pattern.matcher(line) val matches = mutableListOf<Int>() while (matcher.find()) { val start = matcher.start() matches.add(start) } return matches } // 0 if not gear fun gearRatio(row: Int, col: Int, input: List<String>): Int { val startRowBound = max(0, row - 1) val endRowBound = min(input.size - 1, row + 1) val startColBound = max(0, col - 1) val endColBound = min(input.first().length - 1, col + 1) print("rows [$startRowBound,$endRowBound]\tcols [$startColBound,$endColBound]\t") val numbers = mutableListOf<Int>() println() for (r in startRowBound .. endRowBound) { for ((n, start, endExclusive) in extractNumbersWithIndices(input[r])) { val end = endExclusive - 1 println("$n $start $end") if (start in startColBound..endColBound || end in startColBound..endColBound ) { numbers.add(n) } } } print("$numbers \t") if (numbers.size != 2) { return 0 } return numbers.first() * numbers.last() } fun part2(input: List<String>): Long { var result: Long = 0 input.forEachIndexed { row, s -> for (col in extractGearCandidateIndices(s)) { print("candidate ($row, $col) \t") result += gearRatio(row, col, input) println(result) } } println("RESULT: $result") return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part2(testInput) == 467835.toLong()) val input = readInput("Day03") // part1(input).println() part2(input).println() }
0
Kotlin
0
0
da17a5de6e782e06accd3a3cbeeeeb4f1844e427
3,888
advent-of-code-kotlin-template
Apache License 2.0
src/2022/Day08.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.lang.Integer.max import java.util.* fun main() { Day08().solve() } class Day08 { val input1 = """ 30373 25512 65332 33549 35390 """.trimIndent() data class Tree( val height: Int, var maxLeft: Int = -1, var maxRight: Int = -1, var maxTop: Int = -1, var maxBottom: Int = -1) { fun visible(): Boolean { return height > maxLeft || height > maxRight || height > maxTop || height > maxBottom } } fun scenic(t: Int, x: Int, y: Int, trees: MutableList<Tree>): Int { val tree = trees[t] val xt = t%y val yt = t/y // left var ld = 0 for (i in xt-1 downTo 0) { ++ld val left = trees[x*yt + i] if (left.height >= tree.height) { break } } // right var rd = 0 for (i in xt+1 until x) { ++rd val right = trees[x*yt + i] if (right.height >= tree.height) { break } } //top var td = 0 for (j in yt-1 downTo 0) { ++td val top = trees[x*j + xt] if (top.height >= tree.height) { break } } //bottom var bd = 0 for (j in yt+1 until y) { ++bd val bottom = trees[x*j + xt] if (bottom.height >= tree.height) { break } } println("$t ${ld * rd * td * bd} $ld * $rd * $td * $bd") return ld * rd * td * bd } fun solve() { val f = File("src/2022/inputs/day08.in") val s = Scanner(f) // val s = Scanner(input1) val trees = mutableListOf<Tree>() var y0 = 0 while (s.hasNextLine()) { val line = s.nextLine().trim() if (!line.isEmpty()) { trees.addAll(line.map { Tree(it - '0') }) ++y0 } println("$trees") } val y = y0 val x = trees.size/y // left for (j in 0 until y) { for (i in 1 until x) { val tree = trees[j*x + i] val left = trees[j*x + i-1] tree.maxLeft = max(left.height, left.maxLeft) } } // right for (j in 0 until y) { for (i in x-2 downTo 0) { val tree = trees[j*x + i] val right = trees[j*x + i+1] tree.maxRight = max(right.height, right.maxRight) } } //top for (i in 0 until x) { for (j in 1 until y) { val tree = trees[j*x + i] val top = trees[(j-1)*x + i] tree.maxTop = max(top.height, top.maxTop) } } //bottom for (i in 0 until x) { for (j in y-2 downTo 0) { val tree = trees[j*x + i] val bottom = trees[(j+1)*x + i] tree.maxBottom = max(bottom.height, bottom.maxBottom) } } val maxs = trees.indices.maxOf { scenic(it, x, y, trees) } println("$maxs $x $y ${trees.sumOf { if (it.visible()) 1L else 0L}}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
3,387
advent-of-code
Apache License 2.0
src/main/kotlin/adventofcode2022/solution/day_3.kt
dangerground
579,293,233
false
{"Kotlin": 51472}
package adventofcode2022.solution import adventofcode2022.util.readDay private const val DAY_NUM = 3 fun main() { Day3(DAY_NUM.toString()).solve() } class Day3(private val num: String) { private val inputText = readDay(num) fun solve() { println("Day $num Solution") println("* Part 1: ${solution1()}") println("* Part 2: ${solution2()}") } fun solution1(): Long { return inputText.lines().map { val first = it.substring(0, it.length / 2) val second = it.substring(it.length / 2) val item = findMatching(first, second) return@map item.priority() }.sum().toLong() } private fun findMatching(second: String, first: String): String { val x = second.replace(Regex("[^$first]+"), "") val y = first.replace(Regex("[^$x]"), "") return y } fun solution2(): Long { return inputText.lines().chunked(3).map { val first = it[0] val second = it[1] val third = it[2] val item = findMatching(first, findMatching(second, third)) return@map item.priority() }.sum().toLong() } private fun String.priority(): Int { return if (this[0].isUpperCase()) { this[0].code - 38 } else { this[0].code - 96 } } }
0
Kotlin
0
0
f1094ba3ead165adaadce6cffd5f3e78d6505724
1,380
adventofcode-2022
MIT License
src/main/kotlin/day10/Day10TheStarsAlign.kt
Zordid
160,908,640
false
null
package day10 import shared.extractAllInts import shared.minToMaxRange import shared.readPuzzle data class Light(val x: Int, val y: Int, val vx: Int, val vy: Int) { fun posAt(time: Int) = x + vx * time to y + vy * time } fun part1and2(puzzle: List<List<Int>>): Int { val lights = puzzle.map { Light(it[0], it[1], it[2], it[3]) } val solutionTime = (0..Int.MAX_VALUE).first { time -> lights.heightAt(time) < lights.heightAt(time + 1) } lights.at(solutionTime).printLights() return solutionTime } fun List<Light>.at(time: Int) = map { it.posAt(time) } fun List<Light>.heightAt(time: Int) = at(time).map { it.second }.minToMaxRange()!!.let { it.last - it.first } fun List<Pair<Int, Int>>.printLights() { val xRange = map { it.first }.minToMaxRange()!! val yRange = map { it.second }.minToMaxRange()!! for (y in yRange) { for (x in xRange) { print(if (contains(x to y)) "#" else '.') } println() } } fun main() { val puzzle = readPuzzle(10) { it.extractAllInts().toList() } println(part1and2(puzzle)) }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
1,096
adventofcode-kotlin-2018
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/Dota2Senate.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * In the world of Dota2, there are two parties: the Radiant and the Dire. * * The Dota2 senate consists of senators coming from two parties. * Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. * In each round, each senator can exercise one of the two rights: * * Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds. * Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, * he can announce the victory and decide on the change in the game. * Given a string senate representing each senator's party belonging. * The character 'R' and 'D' represent the Radiant party and the Dire party. * Then if there are n senators, the size of the given string will be n. * * The round-based procedure starts from the first senator to the last senator in the given order. * This procedure will last until the end of voting. * All the senators who have lost their rights will be skipped during the procedure. * * Suppose every senator is smart enough and will play the best strategy for his own party. * Predict which party will finally announce the victory and change the Dota2 game. * The output should be "Radiant" or "Dire". * * * * Example 1: * * Input: senate = "RD" * Output: "Radiant" * Explanation: * The first senator comes from Radiant and he can just ban the next senator's right in round 1. * And the second senator can't exercise any rights anymore since his right has been banned. * And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. * Example 2: * * Input: senate = "RDD" * Output: "Dire" * Explanation: * The first senator comes from Radiant and he can just ban the next senator's right in round 1. * And the second senator can't exercise any rights anymore since his right has been banned. * And the third senator comes from Dire and he can ban the first senator's right in round 1. * And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. * * * Constraints: * * n == senate.length * 1 <= n <= 10^4 * senate[i] is either 'R' or 'D'. * @see <a href="https://leetcode.com/problems/dota2-senate/">LeetCode</a> */ fun predictPartyVictory(senate: String): String { val totalSenators = senate.length val radiantSenators = mutableListOf<Int>() val direSenators = mutableListOf<Int>() senate.forEachIndexed { index, senator -> when (senator) { 'R' -> radiantSenators.add(index) 'D' -> direSenators.add(index) } } while (radiantSenators.isNotEmpty() && direSenators.isNotEmpty()) { val radiantSenator = radiantSenators.removeAt(0) val direSenator = direSenators.removeAt(0) if (radiantSenator < direSenator) { radiantSenators.add(radiantSenator + totalSenators) } else { direSenators.add(direSenator + totalSenators) } } return when { radiantSenators.size > direSenators.size -> "Radiant" else -> "Dire" } }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
3,236
leetcode-75
Apache License 2.0
src/main/kotlin/year2021/day-15.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.Grid2d import lib.Position import lib.TraversalAStar import lib.aoc.Day import lib.aoc.Part fun main() { Day(15, 2021, PartA15(), PartB15()).run() } open class PartA15 : Part() { protected lateinit var cave: Grid2d<Int> protected lateinit var end: Position protected lateinit var limits: List<Iterable<Int>> override fun parse(text: String) { cave = Grid2d(text.split("\n").map { line -> line.map { it.digitToInt() } }) end = Position.at(cave.size[0] - 1, cave.size[1] - 1) limits = cave.limits } override fun compute(): String { val moves = Position.moves() val traversal = TraversalAStar({ pos, _ -> pos.neighbours(moves, limits).map { it to riskAt(it) } }, ::heuristic) traversal.startFrom(Position.at(0, 0)).goTo(end) return traversal.distance(end).toInt().toString() } private fun heuristic(pos: Position) = pos.manhattanDistance(end).toFloat() protected open fun riskAt(pos: Position) = cave[pos].toFloat() override val exampleAnswer: String get() = "40" } class PartB15 : PartA15() { override fun parse(text: String) { super.parse(text) val blockSizeX = cave.size[0] val blockSizeY = cave.size[1] limits = listOf(0..<blockSizeX * 5, 0..<blockSizeY * 5) end = Position.at(cave.size[0] * 5 - 1, cave.size[1] * 5 - 1) } override fun riskAt(pos: Position): Float { val blockSizeX = cave.size[0] val blockSizeY = cave.size[1] val blockX = pos[0] / blockSizeX val blockY = pos[1] / blockSizeY val x = pos[0] % blockSizeX val y = pos[1] % blockSizeY return wrap(cave[Position.at(x, y)] + blockX + blockY).toFloat() } private fun wrap(x: Int): Int = (x - 1).mod(9) + 1 override val exampleAnswer: String get() = "315" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
1,983
Advent-Of-Code-Kotlin
MIT License
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day18.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.days.Day class Day18 : Day(title = "Settlers of The North Pole") { private companion object Configuration { private const val OPEN_GROUND = '.' private const val TREE = '|' private const val LUMBERYARD = '#' private const val FIRST_MINUTES = 10 private const val SECOND_MINUTES = 1_000_000_000 } override fun first(input: Sequence<String>): Any = input.solve(FIRST_MINUTES) override fun second(input: Sequence<String>): Any = input.solve(SECOND_MINUTES) private fun Sequence<String>.solve(minutes: Int) = this .parse() .step(minutes) .countScores() .let { scores -> (scores[TREE] ?: 0) * (scores[LUMBERYARD] ?: 0) } private fun Sequence<String>.parse(): Grid = this .toList() .let { g -> Grid(g.first().length, g.size, g.joinToString("") { it }) } private tailrec fun Grid.step( limit: Int, seen: Map<String, Int> = mapOf(), step: Int = 0 ): Grid = when { //Limit reached, return the current grid step == limit -> this //We've seen this grid before, this means that for every "step - seen[grid]" minutes //we will iterate over the same grids. Figure out how many steps are left to get to //the limit and skip all iterations which are redundant. grid in seen -> (0 until (limit - step) % (step - seen[grid]!!)) .fold(this) { g, _ -> g.nextGrid() } //Calculate next grid, update "seen" with the current grid else -> nextGrid().step(limit, seen + (grid to step), step + 1) } class Grid(private val width: Int, private val height: Int, val grid: String) { fun countScores(): Map<Char, Int> = grid.groupingBy { it }.eachCount() private fun toIndex(x: Int, y: Int) = y * width + x fun nextGrid(): Grid = Grid( width, height, //Iterate over the current grid and for every character calculate it's new value. grid.withIndex().joinToString("") { (index, c) -> c.nextState(index.neighborValues()).toString() } ) private fun Int.neighborValues(): Map<Char, Int> = this .neighbors() .groupingBy { it } .eachCount() .withDefault { 0 } private fun Char.nextState(ns: Map<Char, Int>): Char = when (this) { OPEN_GROUND -> if (ns.getValue(TREE) >= 3) TREE else OPEN_GROUND TREE -> if (ns.getValue(LUMBERYARD) >= 3) LUMBERYARD else TREE LUMBERYARD -> if (ns.getValue(TREE) >= 1 && ns.getValue(LUMBERYARD) >= 1) LUMBERYARD else OPEN_GROUND else -> throw IllegalStateException() } private fun Int.neighbors(): List<Char> { val result = mutableListOf<Char>() val x = this % width val y = this / width if (y > 0) result += grid[toIndex(x, y - 1)] if (y + 1 < height) result += grid[toIndex(x, y + 1)] if (x > 0) { result += grid[toIndex(x - 1, y)] if (y > 0) result += grid[toIndex(x - 1, y - 1)] if (y + 1 < height) result += grid[toIndex(x - 1, y + 1)] } if (x + 1 < width) { result += grid[toIndex(x + 1, y)] if (y > 0) result += grid[toIndex(x + 1, y - 1)] if (y + 1 < height) result += grid[toIndex(x + 1, y + 1)] } return result } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
3,672
AdventOfCode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SuperEggDrop.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode fun interface SuperEggDrop { operator fun invoke(eggs: Int, floors: Int): Int } class SuperEggDropDPBinarySearch : SuperEggDrop { private var memo: MutableMap<Int, Int?> = HashMap() override operator fun invoke(eggs: Int, floors: Int): Int { return calculate(eggs, floors) } private fun calculate(eggs: Int, floors: Int): Int { if (!memo.containsKey(floors * HUNDRED + eggs)) { val ans: Int when { floors == 0 -> ans = 0 eggs == 1 -> ans = floors else -> { var lo = 1 var hi = floors while (lo + 1 < hi) { val x = (lo + hi) / 2 val t1 = calculate(eggs - 1, x - 1) val t2 = calculate(eggs, floors - x) when { t1 < t2 -> lo = x t1 > t2 -> hi = x else -> { hi = x lo = hi } } } ans = 1 + calculate(eggs - 1, lo - 1).coerceAtLeast(calculate(eggs, floors - lo)) .coerceAtMost(calculate(eggs - 1, hi - 1).coerceAtLeast(calculate(eggs, floors - hi))) } } memo[floors * HUNDRED + eggs] = ans } return memo[floors * HUNDRED + eggs]!! } companion object { private const val HUNDRED = 100 } } class SuperEggDropDPOptimalityCriterion : SuperEggDrop { override operator fun invoke(eggs: Int, floors: Int): Int { // Right now, dp[i] represents dp(1, i) // Right now, dp[i] represents dp(1, i) var dp = IntArray(floors + 1) for (i in 0..floors) dp[i] = i for (i in 2..eggs) { // Now, we will develop dp2[i] = dp(k, i) val dp2 = IntArray(floors + 1) var x = 1 for (j in 1..floors) { // Let's find dp2[n] = dp(k, n) // Increase our optimal x while we can make our answer better. // Notice max(dp[x-1], dp2[n-x]) > max(dp[x], dp2[n-x-1]) // is simply max(T1(x-1), T2(x-1)) > max(T1(x), T2(x)). while (x < j && dp[x - 1].coerceAtLeast(dp2[j - x]) > dp[x].coerceAtLeast(dp2[j - x - 1])) { x++ } // The final answer happens at this x. dp2[j] = 1 + dp[x - 1].coerceAtLeast(dp2[j - x]) } dp = dp2 } return dp[floors] } } class SuperEggDropMathematical : SuperEggDrop { override operator fun invoke(eggs: Int, floors: Int): Int { var lo = 1 var hi: Int = floors while (lo < hi) { val mi = (lo + hi) / 2 if (calculate(mi, eggs, floors) < floors) lo = mi + 1 else hi = mi } return lo } private fun calculate(x: Int, eggs: Int, floors: Int): Int { var ans = 0 var res = 1 for (i in 1..eggs) { res *= x - i + 1 res /= i ans += res if (ans >= floors) break } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,955
kotlab
Apache License 2.0
src/main/kotlin/aoc/year2023/Day13.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2023 import aoc.Puzzle import aoc.utils.transposed import kotlin.math.min /** * [Day 13 - Advent of Code 2023](https://adventofcode.com/2023/day/13) */ object Day13 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int = solve(input, ::getLineOfReflection) override fun solvePartTwo(input: String): Int = solve(input, ::getLineOfReflectionWithOneChange) private fun solve(input: String, process: (List<List<Char>>) -> Int?) = input.split(Regex("(\\r?\\n){2}")) .map { it.lines().map(String::toList) } .sumOf { rows -> process(rows.transposed()) ?: (process(rows)!! * 100) } private fun getLineOfReflection(input: List<List<Char>>): Int? = (1..input.lastIndex).firstNotNullOfOrNull { index -> val size = min(index, input.size - index) val firstHalf = input.take(index).takeLast(size) val secondHalf = input.drop(index).take(size).asReversed() index.takeIf { firstHalf == secondHalf } } private fun getLineOfReflectionWithOneChange(input: List<List<Char>>): Int? = (1..input.lastIndex).firstNotNullOfOrNull { index -> val size = min(index, input.size - index) val firstHalf = input.take(index).takeLast(size) val secondHalf = input.drop(index).take(size).asReversed() val changesNeeded = firstHalf.zip(secondHalf).sumOf { (a, b) -> a.zip(b).count { (a, b) -> a != b } } index.takeIf { changesNeeded == 1 } } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,521
advent-of-code
Apache License 2.0
kotlin/310.Minimum Height Trees(最小高度树).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.</p> <p><b>Format</b><br /> The graph contains <code>n</code> nodes which are labeled from <code>0</code> to <code>n - 1</code>. You will be given the number <code>n</code> and a list of undirected <code>edges</code> (each edge is a pair of labels).</p> <p>You can assume that no duplicate edges will appear in <code>edges</code>. Since all edges are undirected, <code>[0, 1]</code> is the same as <code>[1, 0]</code> and thus will not appear together in <code>edges</code>.</p> <p><b>Example 1 :</b></p> <pre> <strong>Input:</strong> <code>n = 4</code>, <code>edges = [[1, 0], [1, 2], [1, 3]]</code> 0 | 1 / \ 2 3 <strong>Output:</strong> <code>[1]</code> </pre> <p><b>Example 2 :</b></p> <pre> <strong>Input:</strong> <code>n = 6</code>, <code>edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]</code> 0 1 2 \ | / 3 | 4 | 5 <strong>Output:</strong> <code>[3, 4]</code></pre> <p><b>Note</b>:</p> <ul> <li>According to the <a href="https://en.wikipedia.org/wiki/Tree_(graph_theory)" target="_blank">definition of tree on Wikipedia</a>: &ldquo;a tree is an undirected graph in which any two vertices are connected by <i>exactly</i> one path. In other words, any connected graph without simple cycles is a tree.&rdquo;</li> <li>The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</li> </ul> <p>对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。</p> <p><strong>格式</strong></p> <p>该图包含&nbsp;<code>n</code>&nbsp;个节点,标记为&nbsp;<code>0</code>&nbsp;到&nbsp;<code>n - 1</code>。给定数字&nbsp;<code>n</code>&nbsp;和一个无向边&nbsp;<code>edges</code>&nbsp;列表(每一个边都是一对标签)。</p> <p>你可以假设没有重复的边会出现在&nbsp;<code>edges</code>&nbsp;中。由于所有的边都是无向边, <code>[0, 1]</code>和&nbsp;<code>[1, 0]</code>&nbsp;是相同的,因此不会同时出现在&nbsp;<code>edges</code>&nbsp;里。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> <code>n = 4</code>, <code>edges = [[1, 0], [1, 2], [1, 3]]</code> 0 | 1 / \ 2 3 <strong>输出:</strong> <code>[1]</code> </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> <code>n = 6</code>, <code>edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]</code> 0 1 2 \ | / 3 | 4 | 5 <strong>输出:</strong> <code>[3, 4]</code></pre> <p><strong>说明</strong>:</p> <ul> <li>&nbsp;根据<a href="https://baike.baidu.com/item/%E6%A0%91/2699484?fromtitle=%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84+%E6%A0%91&amp;fromid=12062173&amp;fr=aladdin" target="_blank">树的定义</a>,树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。</li> <li>树的高度是指根节点和叶子节点之间最长向下路径上边的数量。</li> </ul> <p>对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。</p> <p><strong>格式</strong></p> <p>该图包含&nbsp;<code>n</code>&nbsp;个节点,标记为&nbsp;<code>0</code>&nbsp;到&nbsp;<code>n - 1</code>。给定数字&nbsp;<code>n</code>&nbsp;和一个无向边&nbsp;<code>edges</code>&nbsp;列表(每一个边都是一对标签)。</p> <p>你可以假设没有重复的边会出现在&nbsp;<code>edges</code>&nbsp;中。由于所有的边都是无向边, <code>[0, 1]</code>和&nbsp;<code>[1, 0]</code>&nbsp;是相同的,因此不会同时出现在&nbsp;<code>edges</code>&nbsp;里。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入:</strong> <code>n = 4</code>, <code>edges = [[1, 0], [1, 2], [1, 3]]</code> 0 | 1 / \ 2 3 <strong>输出:</strong> <code>[1]</code> </pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> <code>n = 6</code>, <code>edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]</code> 0 1 2 \ | / 3 | 4 | 5 <strong>输出:</strong> <code>[3, 4]</code></pre> <p><strong>说明</strong>:</p> <ul> <li>&nbsp;根据<a href="https://baike.baidu.com/item/%E6%A0%91/2699484?fromtitle=%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84+%E6%A0%91&amp;fromid=12062173&amp;fr=aladdin" target="_blank">树的定义</a>,树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。</li> <li>树的高度是指根节点和叶子节点之间最长向下路径上边的数量。</li> </ul> **/ class Solution { fun findMinHeightTrees(n: Int, edges: Array<IntArray>): List<Int> { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
5,622
leetcode
MIT License
src/main/kotlin/com/marcdenning/adventofcode/day17/Day17a.kt
marcdenning
317,730,735
false
{"Kotlin": 87536}
package com.marcdenning.adventofcode.day17 import java.io.File const val ACTIVE = '#' const val INACTIVE = '.' fun main(args: Array<String>) { val numberOfBootCycles = args[1].toInt() var pocketDimension = arrayOf(File(args[0]).readLines().map { it.toCharArray() }.toTypedArray()) for (i in 1..numberOfBootCycles) { pocketDimension = conductBootCycle(pocketDimension) } println( "Number of active cubes after $numberOfBootCycles boot cycles: ${ countCubesWithState( pocketDimension, ACTIVE ) }" ) } /** * Execute a single boot cycle. Each cube simultaneously changes state according to rules: * * 1. If a cube is active and exactly 2 or 3 of its neighbors are also active, the cube remains active. Otherwise, the cube becomes inactive. * 2. If a cube is inactive but exactly 3 of its neighbors are active, the cube becomes active. Otherwise, the cube remains inactive. * * @return new matrix of cube states, will grow continuously */ fun conductBootCycle(pocketDimension: Array<Array<CharArray>>): Array<Array<CharArray>> { val expandedPocketDimension = Array(pocketDimension.size + 2) { Array(pocketDimension[0].size + 2) { CharArray(pocketDimension[0][0].size + 2) { INACTIVE } } } // Copy existing dimension map into expanded map pocketDimension.forEachIndexed { planeIndex, plane -> plane.forEachIndexed { rowIndex, row -> row.forEachIndexed { charIndex, char -> expandedPocketDimension[planeIndex + 1][rowIndex + 1][charIndex + 1] = char } } } // Apply active/inactive rules expandedPocketDimension.forEachIndexed { planeIndex, plane -> plane.forEachIndexed { rowIndex, row -> row.forEachIndexed { charIndex, char -> val countOfActiveAdjacentCubes = countCubesWithState( getAdjacentCubes(expandedPocketDimension, Coordinates(charIndex, rowIndex, planeIndex)), ACTIVE ) if (char == ACTIVE && countOfActiveAdjacentCubes !in 2..3) { expandedPocketDimension[planeIndex][rowIndex][charIndex] = INACTIVE } else if (char == INACTIVE && countOfActiveAdjacentCubes == 3) { expandedPocketDimension[planeIndex][rowIndex][charIndex] = ACTIVE } } } } // Trim completely inactive edges return expandedPocketDimension } /** * Get all cubes adjacent to given coordinates. This is 26 cubes, with each coordinate value offset by 1. * * @return matrix of adjascent cubes, including target coordinates as space character */ fun getAdjacentCubes(pocketDimension: Array<Array<CharArray>>, coordinates: Coordinates): Array<Array<CharArray>> { val adjacentCubes = Array(3) { Array(3) { CharArray(3) { INACTIVE } } } for (z in -1..1) { for (y in -1..1) { for (x in -1..1) { if (z == 0 && y == 0 && x == 0) { adjacentCubes[1][1][1] = ' ' } else if (coordinates.z + z !in pocketDimension.indices || coordinates.y + y !in pocketDimension[coordinates.z + z].indices || coordinates.x + x !in pocketDimension[coordinates.z + z][coordinates.y + y].indices ) { adjacentCubes[z + 1][y + 1][x + 1] = INACTIVE } else { adjacentCubes[z + 1][y + 1][x + 1] = pocketDimension[coordinates.z + z][coordinates.y + y][coordinates.x + x] } } } } return adjacentCubes } fun countCubesWithState(pocketDimension: Array<Array<CharArray>>, cubeState: Char) = pocketDimension.map { plane -> plane.map { row -> row.map { cube -> if (cube == cubeState) 1 else 0 }.sum() }.sum() }.sum() data class Coordinates( val x: Int, val y: Int, val z: Int )
0
Kotlin
0
0
b227acb3876726e5eed3dcdbf6c73475cc86cbc1
4,008
advent-of-code-2020
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SmallestMissingValueSubtree.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 /** * 2003. Smallest Missing Genetic Value in Each Subtree * @see <a href="https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/">Source</a> */ fun interface SmallestMissingValueSubtree { operator fun invoke(parents: IntArray, nums: IntArray): IntArray } class SmallestMissingValueSubtreeStrict : SmallestMissingValueSubtree { var m: HashMap<Int, List<Int>> = HashMap() lateinit var arr: IntArray var miss = 1 var set: HashSet<Int> = HashSet() override operator fun invoke(parents: IntArray, nums: IntArray): IntArray { val n: Int = parents.size val res = IntArray(n) for (i in 0 until n) { res[i] = 1 } var oneIndex = -1 for (i in 0 until n) { if (nums[i] == 1) { oneIndex = i break } } // 1 not found if (oneIndex == -1) { return res } val graph: MutableMap<Int, MutableSet<Int>> = HashMap() for (i in 1 until n) { val children = graph.getOrDefault(parents[i], HashSet()) children.add(i) graph[parents[i]] = children } val visited: MutableSet<Int> = HashSet() var parentIter = oneIndex var miss = 1 while (parentIter >= 0) { dfs(parentIter, graph, visited, nums) while (visited.contains(miss)) { miss++ } res[parentIter] = miss parentIter = parents[parentIter] } return res } private fun dfs(ind: Int, graph: Map<Int, Set<Int>>, visited: MutableSet<Int>, nums: IntArray) { if (!visited.contains(nums[ind])) { val children = graph[ind] ?: HashSet() for (p in children) { dfs(p, graph, visited, nums) } visited.add(nums[ind]) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,569
kotlab
Apache License 2.0
src/Day10.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Long { val program = parseInstructions(input) return execute(program) } fun part2(input: List<String>): String { val program = parseInstructions(input) return execute2(program) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") assertEquals(13140, part1(testInput)) val expectedImage = """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """ .trimIndent() assertEquals(expectedImage, part2(testInput)) val input = readInput("Day10") println(part1(input)) println(part2(input)) } private fun parseInstructions(input: List<String>): List<Instruction> = input.flatMap { val instruction = it.split(" ").first() when (instruction) { "addx" -> listOf(NoopInstruction, AddInstruction(it.split(" ").last().toInt())) else -> listOf(NoopInstruction) } } private fun execute(instructions: List<Instruction>): Long { var cycle = 1 var registerX: Long = 1 var sumOfSignalStrength: Long = 0 for (instruction in instructions) { if ((cycle - 20) % 40 == 0) { sumOfSignalStrength += cycle * registerX } when (instruction) { is NoopInstruction -> {} is AddInstruction -> { registerX += instruction.amount } } cycle++ } return sumOfSignalStrength } private fun execute2(instructions: List<Instruction>): String { var cycle = 1 var registerX: Long = 1 val crt = StringBuilder() for (instruction in instructions) { if ((cycle - 1) in (registerX - 1..registerX + 1)) { crt.append("#") } else { crt.append(".") } if (cycle % 40 == 0) { registerX += 40 crt.appendLine() } when (instruction) { is NoopInstruction -> {} is AddInstruction -> { registerX += instruction.amount } } cycle++ } return crt.toString().trim() } private sealed interface Instruction private class AddInstruction(val amount: Int) : Instruction private object NoopInstruction : Instruction
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
2,368
aoc2022
Apache License 2.0
src/Day03.kt
jbotuck
573,028,687
false
{"Kotlin": 42401}
fun main() { val lines = readInput("Day03") println("part 1 ${lines.sumOf { part1(it) }}") println("part 2 ${lines.chunked(3).sumOf { part2(it) }}") } private fun Char.priority() = if (isUpperCase()) code % 'A'.code + 27 else code % 'a'.code + 1 private fun part1(line: String) = line .chunked(line.length / 2) .map { it.toSet() } .reduce { a, b -> a.intersect(b) } .first() .priority() fun part2(group: List<String>) = group .map { it.toSet() } .reduce { a, b -> a.intersect(b) } .first() .priority()
0
Kotlin
0
0
d5adefbcc04f37950143f384ff0efcd0bbb0d051
556
aoc2022
Apache License 2.0
src/main/kotlin/g0801_0900/s0827_making_a_large_island/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0827_making_a_large_island // #Hard #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #2023_03_25_Time_985_ms_(100.00%)_Space_92.1_MB_(33.33%) class Solution { private lateinit var p: IntArray private lateinit var s: IntArray private fun makeSet(x: Int, y: Int, rl: Int) { val a = x * rl + y p[a] = a s[a] = 1 } private fun comb(x1: Int, y1: Int, x2: Int, y2: Int, rl: Int) { var a = find(x1 * rl + y1) var b = find(x2 * rl + y2) if (a == b) { return } if (s[a] < s[b]) { val t = a a = b b = t } p[b] = a s[a] += s[b] } private fun find(a: Int): Int { if (p[a] == a) { return a } p[a] = find(p[a]) return p[a] } fun largestIsland(grid: Array<IntArray>): Int { val rl = grid.size val cl = grid[0].size p = IntArray(rl * cl) s = IntArray(rl * cl) for (i in 0 until rl) { for (j in 0 until cl) { if (grid[i][j] == 0) { continue } makeSet(i, j, rl) if (i > 0 && grid[i - 1][j] == 1) { comb(i, j, i - 1, j, rl) } if (j > 0 && grid[i][j - 1] == 1) { comb(i, j, i, j - 1, rl) } } } var m = 0 var t: Int val sz: HashMap<Int, Int> = HashMap() for (i in 0 until rl) { for (j in 0 until cl) { if (grid[i][j] == 0) { // find root, check if same and combine size t = 1 if (i > 0 && grid[i - 1][j] == 1) { sz[find((i - 1) * rl + j)] = s[find((i - 1) * rl + j)] } if (j > 0 && grid[i][j - 1] == 1) { sz[find(i * rl + j - 1)] = s[find(i * rl + j - 1)] } if (i < rl - 1 && grid[i + 1][j] == 1) { sz[find((i + 1) * rl + j)] = s[find((i + 1) * rl + j)] } if (j < cl - 1 && grid[i][j + 1] == 1) { sz[find(i * rl + j + 1)] = s[find(i * rl + j + 1)] } for (`val` in sz.values) { t += `val` } m = m.coerceAtLeast(t) sz.clear() } else { m = m.coerceAtLeast(s[i * rl + j]) } } } return m } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,719
LeetCode-in-Kotlin
MIT License
day10/app/src/main/kotlin/day10/App.kt
Devastus
433,728,008
false
{"Nim": 26335, "C": 14182, "Zig": 9701, "Kotlin": 3712, "Go": 2893, "JavaScript": 2704}
package day10 import java.io.File import java.util.ArrayDeque val INPUT = "input.txt" fun old() { val scoreMap = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val chars: CharSequence = "([{<)]}>" val charMap = mapOf('(' to 0, ')' to 4, '[' to 1, ']' to 5, '{' to 2, '}' to 6, '<' to 3, '>' to 7) var syntaxScore = 0 var complScores = ArrayList<Long>() var stack = ArrayDeque<Int>() File(INPUT).forEachLine { stack.clear() var complScore: Long = 0 var discard = false for (char in it) { var value = charMap.getValue(char) when (value) { in 0..3 -> { stack.push(value) print(char) } in 4..7 -> { var eval = stack.pop() if (eval - (value - 4) != 0) { syntaxScore += scoreMap.getValue(char) discard = true print("\u001b[31m" + char + "\u001b[0m") break; } else { print(char) } } } } if (!discard) { val len = stack.size for (i in 0..(len - 1)) { val value = (stack.pop() + 4) val char = chars[value] complScore = (complScore * 5) + (value - 3).toLong() print("\u001b[32m" + char + "\u001b[0m") } complScores.add(complScore) } print('\n') } complScores.sort() println("Syntax score: ${syntaxScore}") println("Mid score: ${complScores[(complScores.size / 2.0).toInt()]}") } fun new() { val scoreMap = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val pairs = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val pairKeys = pairs.keys var syntaxScore = 0 var complScores = mutableListOf<Long>() var stack = mutableListOf<Char>() File(INPUT).forEachLine { line -> stack.clear() for (char in line) { if (char in pairKeys) { stack.add(char) } else if (char == pairs[stack.lastOrNull()]) { stack.removeLast() } else { syntaxScore += scoreMap[char]!!; stack.clear(); break } } if (stack.size > 0) complScores.add(stack.reversed().map { pairKeys.indexOf(it) + 1 }.fold(0L) { acc, x -> acc * 5 + x}) } println("Syntax score: ${syntaxScore}, Mid score: ${complScores.sorted()[(complScores.size / 2.0).toInt()]}") } fun main() { old() println("===================================") new() }
0
Nim
0
0
69f6c228b5d0ca7ecd47a6b0b0703a1d88df2a4a
2,769
aoc-2021
MIT License
src/day8/Day8.kt
quinlam
573,215,899
false
{"Kotlin": 31932}
package day8 import utils.ArrayMovement import utils.Day /** * Actual answers after submitting; * part1: 1179 * part2: 172224 */ class Day8 : Day<Int, Array<Array<Int>>>( testPart1Result = 21, testPart2Result = 8, ) { /** * Part1 can be done easily in O(n) but then i don't get to reuse any code... */ override fun part1Answer(input: Array<Array<Int>>): Int { return createVisibilityArray(input, true, this::isVisibleFromEdge) .flatten() .count { it != 0 } } override fun part2Answer(input: Array<Array<Int>>): Int { return createVisibilityArray(input, false, this::visibilityScore) .flatten() .max() } private fun createVisibilityArray( input: Array<Array<Int>>, findEdge: Boolean, function: (List<Int>) -> Int ): Array<Array<Int>> { val visible = Array(input.size) { Array(input[0].size) { 0 } } for (row in input.indices) { for (column in input[row].indices) { val treeSize = input[row][column] val values = ArrayMovement.values() .map { move(input, treeSize, row, column, it, findEdge) } visible[row][column] = function(values) } } return visible } private fun move(input: Array<Array<Int>>, treeSize: Int, row: Int, column: Int, movement: ArrayMovement, findEdge: Boolean): Int { val i = row + movement.horizontal val j = column + movement.vertical if (input.getOrNull(i)?.getOrNull(j) == null) { return findEdge.compareTo(false) } if (treeSize > input[i][j]) { return move(input, treeSize, i, j, movement, findEdge) + findEdge.compareTo(true) } return findEdge.compareTo(true) } private fun isVisibleFromEdge(values: List<Int>): Int { return values.max() } private fun visibilityScore(values: List<Int>): Int { return values.reduce { acc, i -> acc * i} } override fun modifyInput(input: List<String>): Array<Array<Int>> { return input.map { it.toCharArray() .map { char -> char.digitToInt() } .toTypedArray() }.toTypedArray() } }
0
Kotlin
0
0
d304bff86dfecd0a99aed5536d4424e34973e7b1
2,304
advent-of-code-2022
Apache License 2.0
src/Day04.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
fun main() { fun part1and2(input: List<String>): Pair<Int, Int> { val pattern = """(-?\d+)-(-?\d+),(-?\d+)-(-?\d+)""".toRegex() var answer1 = 0 var answer2 = 0 for (line in input) { val match = pattern.find(line) val (r1Min, r1Max, r2Min, r2Max) = match!!.destructured val r1 = r1Min.toInt() .. r1Max.toInt() val r2 = r2Min.toInt() .. r2Max.toInt() if ((r1.first in r2 || r1.last in r2) || (r2.first in r1 || r2.last in r1)) { answer2++ if ((r1.first in r2 && r1.last in r2) || (r2.first in r1 && r2.last in r1)) answer1++ } } return Pair(answer1, answer2) } val testInput = readInput("Day04_test") check(part1and2(testInput).first == 2) val input = readInput("Day04") println(part1and2(input).first) check(part1and2(testInput).second == 4) println(part1and2(input).second) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
1,026
AdventOfCode-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day15.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2021 import com.dvdmunckhof.aoc.common.Grid import com.dvdmunckhof.aoc.common.Point class Day15(private val input: List<List<Int>>) { fun solvePart1(): Int { return solve(Grid(input)) } fun solvePart2(): Int { val multipliedH = input.map { row -> repeatList(row, 5) { level, i -> incrementLevel(level, i) } } val multipliedV = repeatList(multipliedH, 5) { row, i -> row.map { level -> incrementLevel(level, i) } } return solve(Grid(multipliedV)) } private fun <R> repeatList(list: List<R>, n: Int, transform: (R, Int) -> R): List<R> { val result = list.toMutableList() for (i in 1 until n) { result += list.map { r -> transform(r, i) } } return result } private fun incrementLevel(level: Int, i: Int): Int = (level + i - 1).mod(9) + 1 private fun solve(riskGrid: Grid<Int>): Int { val pathGrid = Grid(riskGrid.width, riskGrid.height, Int.MAX_VALUE) val startPoint = Point(0, 0) var changed = true while (changed) { changed = false for (p in pathGrid.points()) { if (p == startPoint) { pathGrid[p] = 0 continue } val points = pathGrid.adjacent(p, false) val value = points.minOf { pathGrid[it] } + riskGrid[p] if (value != pathGrid[p]) { changed = true pathGrid[p] = value } } } return pathGrid.rows.last().last() } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
1,633
advent-of-code
Apache License 2.0
advent-of-code-2021/src/main/kotlin/Day3.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
//Day 3: Binary Diagnostic //https://adventofcode.com/2021/day/3 import java.io.File import kotlin.math.pow fun main() { val list = File("src/main/resources/Day3.txt").readLines() getPowerConsumption(list) getLifeSupportRating(list) } fun getPowerConsumption(list: List<String>) { val bits = getBitArrayForList(list) val gammaRate = mutableListOf<Char>() val epsilonRate = mutableListOf<Char>() bits.forEach { binary -> val (most, least) = getMostAndLeastCommmon(binary) gammaRate.add(most) epsilonRate.add(least) } println(binaryToDecimal(gammaRate.joinToString("")) * binaryToDecimal(epsilonRate.joinToString(""))) } fun getLifeSupportRating(list: List<String>) { println(getRating(list, "oxygen") * getRating(list, "c02")) } fun getRating(list: List<String>, rating: String): Int { val mutableList = list.toMutableList() for (i in 0 until list.first().length) { if (mutableList.size == 1) break val bits = getBitArrayForList(mutableList) val numbers = getBitCount(bits[i]) if (numbers['0']!! > numbers['1']!!) { mutableList.removeIf { it[i] == if (rating == "oxygen") '1' else '0' } } else if (numbers['1']!! > numbers['0']!!) { mutableList.removeIf { it[i] == if (rating == "oxygen") '0' else '1' } } else { mutableList.removeIf { it[i] == if (rating == "oxygen") '0' else '1' } } } return binaryToDecimal(mutableList.first()) } fun getBitArrayForList(list: List<String>): Array<String> { val bits = Array(list.first().length) { "" } list.forEach { binary -> binary.toList().forEachIndexed { index, char -> bits[index] = bits[index] + char } } return bits } fun getMostAndLeastCommmon(binary: String): Pair<Char, Char> { val numbers = getBitCount(binary) return if (numbers['0']!! > numbers['1']!!) { '0' to '1' } else { '1' to '0' } } fun getBitCount(string: String): Map<Char, Int> { return string.toList().groupingBy { it }.eachCount() } fun binaryToDecimal(binary: String): Int { return binary.toInt(2) }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
2,184
advent-of-code
Apache License 2.0
src/day23/Parser.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day23 import readInput import java.io.File import java.lang.IllegalArgumentException import kotlin.math.sign data class Point (val x: Int, val y: Int) { val adjacent: List<Point> get () { val list = mutableListOf<Point> () for (x in -1 .. 1) { for (y in -1 .. 1) { if (x == 0 && y == 0) { continue } list.add (Point (x, y)) } } return list } fun subtract (other: Point): Point = Point (x - other.x, y - other.y) fun add (other: Point): Point = Point (x + other.x, y + other.y) fun add (dx: Int, dy: Int): Point = Point (x + dx, y + dy) } enum class Direction (val dx: Int, val dy: Int, val symbol: Char) { N (0, -1, '↑'), NE (1, -1, '↗'), E (1, 0, '→'), SE (1, 1, '↘'), S (0, 1, '↓'), SW (-1, 1, '↙'), W (-1, 0, '←'), NW (-1, -1, '↖'); companion object { fun fromPoint (point: Point): Direction { val dx = point.x.sign val dy = point.y.sign Direction.values ().forEach { if (it.dx == dx && it.dy == dy) { return it } } throw Exception () } } } enum class Thing (val encoded: Char) { ELF ('#'), GROUND ('.'); companion object { private val map = mutableMapOf<Char, Thing> ().apply { Thing.values ().forEach { this[it.encoded] = it } }.toMap () fun decode (encoded: Char): Thing = map[encoded] ?: throw IllegalArgumentException ("Invalid encoding: $encoded") } } class Grid (val data: Map<Point, Thing>) { val firstElf: Point get () = elves[0] val xmin: Int get () = elves.fold (firstElf.x) { acc, point -> Math.min (acc, point.x) } val xmax: Int get () = elves.fold (firstElf.x) { acc, point -> Math.max (acc, point.x) } val ymin: Int get () = elves.fold (firstElf.y) { acc, point -> Math.min (acc, point.y) } val ymax: Int get () = elves.fold (firstElf.y) { acc, point -> Math.max (acc, point.y) } val elves = mutableListOf<Point> ().apply { data.forEach { (point, thing) -> if (thing == Thing.ELF) { add (point) } } } private fun hasAdjacencies (point: Point): Boolean { point.adjacent.forEach { if (elves.contains (point.add (it))) { return true } } return false } val proposed = mutableListOf<Pair<Point, Point>> () val validMoves: List<Pair<Point, Point>> get () { val map = mutableMapOf<Point, Int> () proposed.forEach { (_, to) -> if (map.containsKey (to)) { map[to] = map[to]!! + 1 } else { map[to] = 1 } } return proposed.filter { (_, to) -> map[to] == 1 } } private fun rotateDirections () { checkDirections.add (checkDirections.removeAt (0)) return } private val checkDirections = mutableListOf<List<Direction>> ( listOf (Direction.N, Direction.NE, Direction.NW), listOf (Direction.S, Direction.SE, Direction.SW), listOf (Direction.W, Direction.NW, Direction.SW), listOf (Direction.E, Direction.NE, Direction.SE) ) private fun check (point: Point): Point? { checkDirections.forEach { dirs -> if (isEmpty (point, dirs)) { return point.add (dirs[0].dx, dirs[0].dy) } } return null } private fun isEmpty (point: Point, dirs: List<Direction>): Boolean { for (dir in dirs) { if (elves.contains (point.add (dir.dx, dir.dy))) { return false } } return true } fun round1 () { elves.forEach { elf -> if (hasAdjacencies (elf)) { val maybe = check (elf) if (maybe != null) { proposed.add (Pair (elf, maybe)) } } } rotateDirections() return } /** * */ fun round2 () { val moves = validMoves elves.removeAll (moves.map { it.first }) elves.addAll (moves.map { it.second }) proposed.clear() return } fun round () { round1() round2() return } fun dumpProposed () { val valid = validMoves proposed.forEach { pair -> val (from, to) = pair val delta = to.subtract (from) val isValid = valid.contains (pair) } return } val emptyTiles: Int get () { var total = 0 for (y in ymin .. ymax) { for (x in xmin .. xmax) { val point = Point (x, y) if (! elves.contains (point)) { total ++ } } } return total } fun dumpMoves () { val valid = validMoves proposed.forEach { println ("$it - ${valid.contains (it)}") } return } fun dump () = println (toString()) override fun toString (): String { val valid = validMoves.map { it.first } return StringBuffer ().apply { for (y in ymin - 1 .. ymax + 1) { append (String.format ("%3d: ", y)) for (x in xmin - 1 .. xmax + 1) { val point = Point (x, y) if (elves.contains (point)) { val move = proposed.firstOrNull { (from, _) -> from == point } if (move != null) { val dir = Direction.fromPoint (move.second.subtract (move.first)) append (dir.symbol) } else { append ('#') } } else { append (Thing.GROUND.encoded) } } append ("\n") } }.toString () } companion object { fun parse (input: String): Grid { val map = mutableMapOf<Point, Thing> () input.trim ().split ("\n").forEachIndexed { y, row -> row.forEachIndexed { x, t -> map.put (Point (x, y), Thing.decode (t)) } } return Grid (map) } } } fun loadGrid (example: Boolean): Grid { val input = readInput(23, example) return Grid.parse (input) } fun main (args: Array<String>) { val example = false val grid = loadGrid (example) // val input = File ("src/day23/day23-small.txt").readText() // val grid = Grid.parse (input) grid.dump () // while (true) { repeat (10) { grid.round1 () grid.dump () if (grid.validMoves.isEmpty()) { // break } grid.round2 () grid.dump () println (" ======== ") } println ("part1=${grid.emptyTiles}") return }
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
7,356
advent_of_code_2022
Apache License 2.0
src/day05/Day05.kt
AbolfaZlRezaEe
574,383,383
false
null
package day05 import readInput import java.util.* fun main() { fun part01(lines: List<String>): String { // Separate input and instructions val columns = hashMapOf<Int, LinkedList<Char>>() val instructions = lines.filter { line -> line.startsWith("move") } val input = lines.filter { line -> !line.contains("""[a-z]""".toRegex()) && line.isNotEmpty() } // parse the input input.forEach { line -> var columnCounter = 1 line.forEachIndexed { index, char -> if (char.isLetter() && line.toCharArray()[index - 1] == '[' && line.toCharArray()[index + 1] == ']' ) { // placing the blocks into lists val list = if (columns.contains(index)) { columns[index]!!.apply { add(char) } } else { LinkedList<Char>().apply { add(char) } } columns[index] = list } else if (char.isDigit()) { // placing column number into the list columns[index]?.apply { columns[columnCounter] = this if (columnCounter != index) columns.remove(index) columnCounter++ } } } } // Do the instructions instructions.forEach { instruction -> // index 0: amount of crates, 1: from column?, 2: to column? val instructionSteps = instruction.split(" ") .filter { word -> word.contains("[0-9]".toRegex()) } .map { word -> word.toInt() } val originColumn = columns[instructionSteps[1]]!! val destinationColumn = columns[instructionSteps[2]]!! for (amount in 1..instructionSteps[0]) { destinationColumn.addFirst(originColumn.pop()) // Remove first, Insert first } } // Get the first char of every list for creating the final message var finalMessage = "" columns.forEach { finalMessage += it.value.first } return finalMessage } fun part02(lines: List<String>): String { // Separate input and instructions val columns = hashMapOf<Int, LinkedList<Char>>() val instructions = lines.filter { line -> line.startsWith("move") } val input = lines.filter { line -> !line.contains("""[a-z]""".toRegex()) && line.isNotEmpty() } // parse the input input.forEach { line -> var columnCounter = 1 line.forEachIndexed { index, char -> if (char.isLetter() && line.toCharArray()[index - 1] == '[' && line.toCharArray()[index + 1] == ']' ) { // placing the blocks into lists val list = if (columns.contains(index)) { columns[index]!!.apply { add(char) } } else { LinkedList<Char>().apply { add(char) } } columns[index] = list } else if (char.isDigit()) { // placing column number into the list columns[index]?.apply { columns[columnCounter] = this if (columnCounter != index) columns.remove(index) columnCounter++ } } } } // Do the instructions instructions.forEach { instruction -> // index 0: amount of crates, 1: from column?, 2: to column? val instructionSteps = instruction.split(" ") .filter { word -> word.contains("[0-9]".toRegex()) } .map { word -> word.toInt() } val originColumn = columns[instructionSteps[1]]!! val destinationColumn = columns[instructionSteps[2]]!! val cratesForMoving = LinkedList<Char>() for (amount in 1..instructionSteps[0]) { cratesForMoving.addFirst(originColumn.pop()) } cratesForMoving.forEach { destinationColumn.addFirst(it) } } // Get the first char of every list for creating the final message var finalMessage = "" columns.forEach { finalMessage += it.value.first } return finalMessage } check(part01(readInput(targetDirectory = "day05", name = "Day05FakeData")) == "CMZ") check(part02(readInput(targetDirectory = "day05", name = "Day05FakeData")) == "MCD") val part01Answer = part01(readInput(targetDirectory = "day05", name = "Day05RealData")) val part02Answer = part02(readInput(targetDirectory = "day05", name = "Day05RealData")) println("The final message in part01 is-> $part01Answer") println("The final message in part02 is-> $part02Answer") }
0
Kotlin
0
0
798ff23eaa9f4baf25593368b62c2f671dc2a010
4,970
AOC-With-Me
Apache License 2.0
src/main/kotlin/aoc2023/Day12.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2023 import AoCDay // https://adventofcode.com/2023/day/12 object Day12 : AoCDay<Int>( title = "Hot Springs", part1ExampleAnswer = 21, part1Answer = 7286, part2ExampleAnswer = null, part2Answer = null, ) { private fun parseRow(row: String): Pair<String, List<Int>> { val (springs, d) = row.split(' ', limit = 2) val damaged = d.split(',').map(String::toInt) return Pair(springs, damaged) } private fun countArrangements(springs: String, damaged: List<Int>): Int { val len = springs.length val damagedSum = damaged.sum() return (0..<(1 shl len)).count { combination -> if (combination.countOneBits() != damagedSum) return@count false val combinationAsString = buildString(len) { for (i in 0..<len) append(if (combination and (1 shl i) == 0) '.' else '#') } var ok = true for ((i, c) in springs.withIndex()) { when (c) { '.', '#' -> if (combinationAsString[i] != c) { ok = false break } } } ok && (combinationAsString.split('.').filterNot(String::isBlank).map(String::length) == damaged) } } override fun part1(input: String) = input .lineSequence() .map(::parseRow) .sumOf { (springs, damaged) -> countArrangements(springs, damaged) } // TODO, brute-forcing won't work override fun part2(input: String) = 0 }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
1,572
advent-of-code-kotlin
MIT License
src/main/aoc2021/Day8.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 class Day8(input: List<String>) { val parsed = input.map { it.split(" | ") } fun solvePart1(): Int { return parsed.sumOf { line -> line.last().split(" ").count { it.length in listOf(2, 3, 4, 7) } } } /** * Remove the first entry that matches the given condition and return it. */ private fun <E> MutableList<E>.removeFirst(function: (E) -> Boolean): E { return removeAt(indexOfFirst { function(it) }) } /* Segment positions: 1111 2 3 2 3 4444 5 6 5 6 7777 */ private fun processOne(input: List<String>): Int { val pattern = input.first().split(" ") val remainingPatterns = pattern.map { it.toSet() }.toMutableList() val segmentPositionToWire = mutableMapOf<Int, Char>() val digitToWires = mutableMapOf<Int, Set<Char>>() // First identify the patterns that can only be one digit digitToWires[1] = remainingPatterns.removeFirst { it.size == 2 } digitToWires[4] = remainingPatterns.removeFirst { it.size == 4 } digitToWires[7] = remainingPatterns.removeFirst { it.size == 3 } digitToWires[8] = remainingPatterns.removeFirst { it.size == 7 } // Segment position 1 is the wire that's present in digit 7 but not in digit 1 segmentPositionToWire[1] = (digitToWires[7]!! - digitToWires[1]!!).single() // The digit 6 has 6 segments, and it lacks one segment that digit 1 has. digitToWires[6] = remainingPatterns.removeFirst { it.size == 6 && !it.containsAll(digitToWires[1]!!) } // Segment position 3 is the wire that's missing from digit 6 segmentPositionToWire[3] = (digitToWires[8]!! - digitToWires[6]!!).single() // Segment position 6 is the wire left after segment position 3 is removed from digit 1 segmentPositionToWire[6] = (digitToWires[1]!! - setOf(segmentPositionToWire[3]!!)).single() // The digit 5 has 5 segments, and it lacks segment position 3 digitToWires[5] = remainingPatterns.removeFirst { it.size == 5 && !it.contains(segmentPositionToWire[3]) } // Starting with all segments, and subtracting all from 5 leaves segment position 3 and 5. // Subtracting all segments from 1 leaves only segment position 5 segmentPositionToWire[5] = (digitToWires[8]!! - digitToWires[5]!! - digitToWires[1]!!).single() // Digit 9 has 6 segments and lacks segment 5 digitToWires[9] = remainingPatterns.removeFirst { it.size == 6 && !it.contains(segmentPositionToWire[5]) } // Digit 2 has 5 segments and lacks segment 6 digitToWires[2] = remainingPatterns.removeFirst { it.size == 5 && !it.contains(segmentPositionToWire[6]) } // Digit 3 has 5 segments and lacks segment 5 digitToWires[3] = remainingPatterns.removeFirst { it.size == 5 && !it.contains(segmentPositionToWire[5]) } // Now only digit 0 remains digitToWires[0] = remainingPatterns.single() // Segment position 4 is the wire that's missing from digit 0 segmentPositionToWire[4] = (digitToWires[8]!! - digitToWires[0]!!).single() // Starting with all segments, and subtracting all from 2 leaves segment position 2 and 6. // Subtracting all segments from 1 leaves only segment position 2 segmentPositionToWire[2] = (digitToWires[8]!! - digitToWires[2]!! - digitToWires[1]!!).single() // Segment position 7 is the only thing that remains segmentPositionToWire[7] = (digitToWires[8]!! - segmentPositionToWire.values.toSet()).single() // All segments and digits identified, map from wires to digits val wiresToDigits = digitToWires.map { (k, v) -> v to k }.toMap() return input.last() .split(" ") .map { wiresToDigits[it.toSet()]!! } .joinToString("") .toInt() } fun solvePart2(): Int { return parsed.sumOf { processOne(it) } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
4,142
aoc
MIT License
src/main/kotlin/de/pgebert/aoc/days/Day18.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day import kotlin.math.abs class Day18(input: String? = null) : Day(18, "Lavaduct Lagoo", input) { data class Vector(val x: Long, val y: Long) { fun plus(other: Vector) = Vector(x + other.x, y + other.y) fun multiply(multiplier: Long) = Vector(x * multiplier, y * multiplier) } override fun partOne(): Long { val plan = inputList.map { line -> val (direction, steps) = line.split(" ") direction.toVector().multiply(steps.toLong()) } return countPointsInside(plan) } override fun partTwo(): Long { val colorRegex = "#(.{5})(.)".toRegex() val plan = inputList.map { line -> val (steps, direction) = colorRegex.find(line)!!.destructured direction.toVector().multiply(steps.toLong(radix = 16)) } return countPointsInside(plan) } private fun countPointsInside(plan: List<Vector>) = pickTheorem(shoelaceFormula(cornerPositions(plan)), perimeter(plan)) private fun cornerPositions(plan: List<Vector>) = plan.scan(Vector(0, 0)) { acc, shiftVector -> acc.plus(shiftVector) } // number of coordinates (vertices // points) on the edge of the polygon private fun perimeter(plan: List<Vector>) = plan.sumOf { abs(it.x) + abs(it.y) } // number of coordinates inside private fun shoelaceFormula(corners: List<Vector>) = corners.zipWithNext { a, b -> a.x * b.y - a.y * b.x }.sum() / 2 // area (== count('#')) by number of coordinates on perimeter and number of coordinates inside private fun pickTheorem(area: Long, perimeter: Long) = area + perimeter / 2 + 1 private fun String.toVector(): Vector = when (this) { "0", "R" -> Vector(1, 0) "2", "L" -> Vector(-1, 0) "3", "U" -> Vector(0, -1) "1", "D" -> Vector(0, 1) else -> throw IllegalArgumentException("Invalid direction") } }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
1,984
advent-of-code-2023
MIT License
src/Day06.kt
realpacific
573,561,400
false
{"Kotlin": 59236}
fun main() { fun numberOfCharacterBeforeSeeingTheFirstDistinctSequence(input: String, distinctCount: Int): Int { val charactersSeen = mutableListOf<Char>() input.forEachIndexed { currentIndex, character -> if (charactersSeen.size == distinctCount) { return currentIndex } val index = charactersSeen.indexOf(character) if (index == -1) { charactersSeen.add(character) // all characters are distinct till now return@forEachIndexed } // remove all characters till only the distinct characters exists even after adding [character] repeat(index + 1) { charactersSeen.removeAt(0) } charactersSeen.add(character) } throw RuntimeException() } fun part1(input: String): Int { return numberOfCharacterBeforeSeeingTheFirstDistinctSequence(input, 4) } fun part2(input: String): Int { return numberOfCharacterBeforeSeeingTheFirstDistinctSequence(input, 14) } assert(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) assert(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) assert(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) assert(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) assert(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) assert(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) assert(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) assert(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) assert(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) assert(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part1(input.first())) println(part2(input.first())) }
0
Kotlin
0
0
f365d78d381ac3d864cc402c6eb9c0017ce76b8d
1,797
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day08/day08.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package main.day08 import utils.readFile import utils.readLines import utils.separator import kotlin.math.max fun main() { val test = readLines( """30373 25512 65332 33549 35390""" ) val input = readFile("day08") class Grid(val lines: Array<IntArray>) { fun width() = lines[0].size fun height() = lines.size fun get(x: Int, y: Int) = lines[x][y] fun visible(x: Int, y: Int): Boolean { val treeHeight = get(x, y) var bottom = true var top = true var left = true var right = true for (i in 0 until x) { val tree = get(i, y) if (tree >= treeHeight) { top = false break } } for (i in x + 1 until height()) { if (get(i, y) >= treeHeight) { bottom = false break } } for (i in y + 1 until width()) { if (get(x, i) >= treeHeight) { right = false break } } for (i in 0 until y) { if (get(x, i) >= treeHeight) { left = false break } } return top || bottom || left || right } fun scenic(x: Int, y: Int): Int { val treeHeight = get(x, y) var bottom = 0 var top = 0 var left = 0 var right = 0 for (i in x + 1 until height()) { bottom += 1 if (get(i, y) >= treeHeight) { break } } for (i in x - 1 downTo 0 ) { top += 1 if (get(i, y) >= treeHeight) { break } } for (i in y + 1 until width()) { right += 1 if (get(x, i) >= treeHeight) { break } } for (i in y - 1 downTo 0 ) { left += 1 if (get(x, i) >= treeHeight) { break } } return bottom * left * right * top } } fun parseGrid(input: List<String>): Grid { return Grid(input.map { line -> line.toList().map { it - '0' }.toIntArray() }.toTypedArray()) } fun calcVisible(grid: Grid): Int { val height = grid.height() val width = grid.width() var result = (height * 2) + (width * 2) - 4 for (x in 1 until height - 1) { for (y in 1 until width - 1) { if (grid.visible(x, y)) { result += 1 } } } return result } fun calcMaxScenic(grid: Grid): Int { val height = grid.height() val width = grid.width() var result = 0 for (x in 1 until height - 1) { for (y in 1 until width - 1) { result = max(result, grid.scenic(x, y)) } } return result } fun part1() { val testResult = calcVisible(parseGrid(test)) println("Part 1 Answer = $testResult") check(testResult == 21) val result = calcVisible(parseGrid(input)) println("Part 1 Answer = $result") check(result == 1851) } fun part2() { val testResult = calcMaxScenic(parseGrid(test)) println("Part 2 Answer = $testResult") check(testResult == 8) val result = calcMaxScenic(parseGrid(input)) println("Part 1 Answer = $result") check(result == 574080) } println("Day - 08") separator() part1() separator() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
3,184
aoc-2022-in-kotlin
Apache License 2.0
Coding Challenges/Advent of Code/2021/Day 9/part1.kt
Alphabeater
435,048,407
false
{"Kotlin": 69566, "Python": 5974}
import java.io.File import java.util.Scanner fun setMapDimensions(file: File): Pair<Int, Int> { val scanner = Scanner(file) var row = 0 var col = 0 var bool = false while (scanner.hasNextLine()) { val line = scanner.nextLine() if (!bool) { col = line.length bool = true } row++ } return Pair(row, col) } fun main() { val file = File("src/input.txt") val (row, col) = setMapDimensions(file) val map = Array(row) { Array(col) { Pair(0, true) } } //[value, isLowPoint?] val scanner = Scanner(file) var i = 0 while (scanner.hasNextLine()) { val line = scanner.nextLine() for ((j, digit) in line.withIndex()) { map[i][j] = map[i][j].copy(first = digit.digitToInt()) } i++ } for (i in 0 until row) { //iterate through every matrix element and compare it to the closest 4 neighbors (up, down, left, right) for (j in 0 until col) { if (i > 0) if (map[i][j].first >= map[i - 1][j].first) map[i][j] = map[i][j].copy(second = false) if (i < row - 1) if (map[i][j].first >= map[i + 1][j].first) map[i][j] = map[i][j].copy(second = false) if (j > 0) if (map[i][j].first >= map[i][j - 1].first) map[i][j] = map[i][j].copy(second = false) if (j < col - 1) if (map[i][j].first >= map[i][j + 1].first) map[i][j] = map[i][j].copy(second = false) } } var sum = 0 for (i in 0 until row) { for (j in 0 until col) { if (map[i][j].second) sum += map[i][j].first + 1 } } println(sum) }
0
Kotlin
0
0
05c8d4614e025ed2f26fef2e5b1581630201adf0
1,644
Archive
MIT License
app/src/main/kotlin/day14/Day14.kt
W3D3
572,447,546
false
{"Kotlin": 159335}
package day14 import common.InputRepo import common.readSessionCookie import common.solve import util.splitIntoPair fun main(args: Array<String>) { val day = 14 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay14Part1, ::solveDay14Part2) } data class Pos(val x: Int, val y: Int) data class Path(val a: Pos, val b: Pos) { private var fixedX: Boolean = false private var fixedAxis: Int = 0 private var points: IntRange = 0..0 init { if (a.x == b.x) { fixedX = true fixedAxis = a.x points = if (a.y < b.y) { a.y..b.y } else { b.y..a.y } } else if (a.y == b.y) { fixedX = false fixedAxis = a.y points = if (a.x < b.x) { a.x..b.x } else { b.x..a.x } } else { throw IllegalArgumentException("Invalid path") } } fun getPositions(): List<Pos> { return if (fixedX) { points.map { Pos(fixedAxis, it) } } else { points.map { Pos(it, fixedAxis) } } } } fun solveDay14Part1(input: List<String>): Int { val takenPositions = parseInput(input) val sandOrigin = Pos(500, 0) val floorLevel = takenPositions.maxOf { it.y } return simulateSand(takenPositions, sandOrigin, floorLevel, fallThrough = true) } fun solveDay14Part2(input: List<String>): Int { val takenPositions = parseInput(input) val sandOrigin = Pos(500, 0) val floorLevel = takenPositions.maxOf { it.y } + 2 return simulateSand(takenPositions, sandOrigin, floorLevel, fallThrough = false) + 1 // add one for source } fun printCave(source: Pos, current: Pos, points: Set<Pos>, depth: Int) { for (y in 0..depth) { for (x in 400..520) { if (points.contains(Pos(x, y))) { print("#") } else if (current.x == x && current.y == y) { print("o") } else if (source.x == x && source.y == y) { print("+") } else { print(".") } } println() } println() } fun simulateSingleSandBlock(points: Set<Pos>, sandOrigin: Pos, floorLevel: Int, fallThrough: Boolean): Pos? { var currentSandPos = sandOrigin var nextSandPos = moveSand(currentSandPos, points) while (nextSandPos != currentSandPos) { currentSandPos = nextSandPos nextSandPos = moveSand(currentSandPos, points) if (nextSandPos.y > floorLevel) { // freefall detected break } if (!fallThrough && nextSandPos.y == floorLevel) { // cant go through floor return currentSandPos } if (nextSandPos == currentSandPos) { // we settled return currentSandPos } if (nextSandPos == sandOrigin) { return null } } return null } fun moveSand(currentSandPos: Pos, points: Set<Pos>): Pos { val down = Pos(currentSandPos.x, currentSandPos.y + 1) val downLeft = Pos(currentSandPos.x - 1, currentSandPos.y + 1) val downRight = Pos(currentSandPos.x + 1, currentSandPos.y + 1) return if (down !in points) { down } else if (downLeft !in points) { downLeft } else if (downRight !in points) { downRight } else { currentSandPos } } private fun simulateSand( takenPositions: MutableSet<Pos>, sandOrigin: Pos, floorLevel: Int, fallThrough: Boolean ): Int { var cnt = 0 do { val block = simulateSingleSandBlock(takenPositions, sandOrigin, floorLevel, fallThrough) if (block != null) { cnt++ if (cnt % 1000 == 0) { printCave(sandOrigin, block, takenPositions, depth = floorLevel + 1) } takenPositions.add(block) } } while (block != null) printCave(sandOrigin, sandOrigin, takenPositions, floorLevel + 1) return cnt } private fun parseInput(input: List<String>): MutableSet<Pos> { val takenPositions = input.flatMap { it.split(" -> ").map { val p = it.trim().splitIntoPair(",") Pos(p.first.toInt(), p.second.toInt()) }.zipWithNext { a, b -> Path(a, b) } }.flatMap { it.getPositions().toSet() }.toMutableSet() return takenPositions }
0
Kotlin
0
0
34437876bf5c391aa064e42f5c984c7014a9f46d
4,470
AdventOfCode2022
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/OddEvenLinkedList.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
import commonclasses.ListNode /** * Given the head of a singly linked list, * group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. * * The first node is considered odd, and the second node is even, and so on. * * Note that the relative order inside both the even and odd groups should remain as it was in the input. * * You must solve the problem in O(1) extra space complexity and O(n) time complexity. * * * * Example 1: * * * Input: head = [1,2,3,4,5] * Output: [1,3,5,2,4] * Example 2: * * * Input: head = [2,1,3,5,6,4,7] * Output: [2,3,6,7,1,5,4] * * * Constraints: * * The number of nodes in the linked list is in the range [0, 10^4]. * -10^6 <= Node.val <= 10^6 * @see <a href="https://leetcode.com/problems/odd-even-linked-list/">LeetCode</a> * * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ fun oddEvenList(head: ListNode?): ListNode? { if (head?.next == null) return head var odd = head var even = head.next val evenHead = even while (even?.next != null) { odd?.next = even.next odd = odd?.next even.next = odd?.next even = even.next } odd?.next = evenHead return head }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,370
leetcode-75
Apache License 2.0
src/main/kotlin/aoc2022/Day18.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.parser.followedBy import aoc.parser.number import aoc.parser.seq import aoc.parser.zeroOrMore import java.util.* typealias CubeSet = MutableMap<Int, MutableMap<Int, MutableSet<Int>>> class Day18() { data class Cube(val x: Int, val y: Int, val z: Int) val cube = seq(number() followedBy ",", number() followedBy ",", number() followedBy "\n", ::Cube) val parser = zeroOrMore(cube) private fun cubesMapOf(parsed: Iterable<Cube>): CubeSet = parsed.fold(mutableMapOf()) { acc, e -> acc.add(e); acc} private fun CubeSet.add( cube: Cube ) { val yMap = getOrPut(cube.x) { -> mutableMapOf() } val zSet = yMap.getOrPut(cube.y) { -> mutableSetOf() } zSet.add(cube.z) } sealed class Dir3(val x:Int, val y:Int, val z:Int) { object Left: Dir3(-1, 0, 0) object Right: Dir3(1, 0, 0) object Back: Dir3(0, -1, 0) object Front: Dir3(0, 1, 0) object Down: Dir3(0, 0, -1) object Up: Dir3(0, 0, 1) } val dirs3 = listOf(Dir3.Left, Dir3.Right, Dir3.Back, Dir3.Front, Dir3.Down, Dir3.Up) operator fun Cube.plus(dir: Dir3) = Cube(this.x + dir.x, this.y + dir.y, this.z + dir.z) operator fun CubeSet.contains(cube: Cube) = this.contains(cube.x, cube.y, cube.z) fun CubeSet.contains(x:Int, y: Int, z: Int) = this[x]?.get(y)?.contains(z) == true private fun surfaceArea( parsed: List<Cube>, cubes: CubeSet ) = parsed.sumOf { cube -> dirs3.count { dir -> (cube + dir) !in cubes } } fun part1(input: String): Int { val parsed = parser.parse(input) val cubes = cubesMapOf(parsed) val result = surfaceArea(parsed, cubes) return result } private fun surfaceAreaExterior( parsed: List<Cube>, exterior: Set<Cube> ) = parsed.sumOf { cube -> dirs3.count { dir -> (cube + dir) in exterior } } fun part2(input: String): Int { val parsed = parser.parse(input) val cubes = cubesMapOf(parsed) val minX = parsed.minOfOrNull(Cube::x)!! - 1 val maxX = parsed.maxOfOrNull(Cube::x)!! + 1 val minY = parsed.minOfOrNull(Cube::y)!! - 1 val maxY = parsed.maxOfOrNull(Cube::y)!! + 1 val minZ = parsed.minOfOrNull(Cube::z)!! - 1 val maxZ = parsed.maxOfOrNull(Cube::z)!! + 1 val queue: Queue<Cube> = LinkedList() val exterior = mutableSetOf<Cube>() val start = Cube(minX, minY, minZ) assert(start !in cubes) queue.add(start) while(queue.isNotEmpty()) { val current = queue.remove() exterior.add(current) dirs3.forEach { dir -> val newCube = current + dir if ((newCube.x in minX..maxX) && (newCube.y in minY..maxY) && (newCube.z in minZ..maxZ) && (newCube !in exterior) && (newCube !in cubes)) { exterior.add(newCube) queue.add(newCube) } } } return surfaceAreaExterior(parsed, exterior) } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
3,251
aoc-kotlin
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions59.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.PriorityQueue fun test59() { val initials = intArrayOf(4, 5, 8, 2) val kthLargest = KthLargest(initials, 3) printlnResult(kthLargest) kthLargest.add(3) printlnResult(kthLargest) kthLargest.add(5) printlnResult(kthLargest) } /** * Questions 59: Find the kth number in a number stream. */ private class KthLargest(nums: IntArray, val k: Int) { private val priorityQueue = PriorityQueue<Int> { a, b -> b - a } init { nums.forEach { add(it) } } fun add(num: Int) { if (priorityQueue.size < k) priorityQueue.enqueue(num) else if (num > priorityQueue.peak) { priorityQueue.dequeue() priorityQueue.enqueue(num) } } fun kth(): Int = priorityQueue.peak } private fun printlnResult(kthLargest: KthLargest) = println("The ${kthLargest.k}th number is: ${kthLargest.kth()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
994
Algorithm
Apache License 2.0
src/main/kotlin/leetcode/kotlin/binarysearch/69. Sqrt(x).kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.binarysearch /** * I understand that square root finding is complex problem and it require a through study for some mathematics algorithms, * But as question does not need exact decimal points and aproximation, we can stick to this descrition and write simple algorithms. * PS: Though I understand we need to know all these algorithms mentioned in best answers, but this question actually doesn't demand it. */ /** * Seems like all 3 solutions are constant time complexity, can someone correct if I'm wrong ? * Solution 1 (Brute Force): O(sqrt(x)) ≈ O(46340)=O(1) * Solution 2 (Newtons Method): O(lg(x)) ≈ O(32)=O(1) * Solution 3 (Binary Search): O(lg(x)) ≈ O(32)=O(1) */ // brute force private fun mySqrt(x: Int): Int { var i = 1 while (i <= x / i) { if (i > x / i) break i++ } return i - 1 } // newton's method private fun mySqrt2(x: Int): Int { if (x == 0) return 0 var i = x.toLong() while (i > x / i) i = (i + x / i) / 2 return i.toInt() } // binary search private fun mySqrt3(x: Int): Int { var l = 1 var r = x var mid = 0 while (l < r) { mid = l + (r - l) / 2 if (mid < x / mid) l = mid + 1 else r = mid } return if (l == x / l) l else l - 1 }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
1,291
kotlinmaster
Apache License 2.0
src/main/adventofcode/Day12Solver.kt
eduardofandrade
317,942,586
false
null
package adventofcode import adventofcode.Day12Solver.Action.* import java.io.InputStream import java.util.stream.Collectors import kotlin.math.abs class Day12Solver(stream: InputStream) : Solver { private val processedInput: List<ShipMove> init { processedInput = processInput(stream) } private fun processInput(stream: InputStream): List<ShipMove> { return stream.bufferedReader().readLines().stream() .map { m -> val moveLetter = m.substring(0..0) val moveUnits = m.substring(1).toInt() ShipMove(Action.valueOf(moveLetter), moveUnits) }.collect(Collectors.toList()) } override fun getPartOneSolution(): Long { return getSolution(Ship()) } override fun getPartTwoSolution(): Long { return getSolution(ShipWithWayPoint()) } private fun getSolution(ship: Ship): Long { processedInput.forEach { m -> ship.applyMove(m) } return abs(ship.eastWest) + abs(ship.northSouth) } private open class Ship(var eastWest: Long = 0, var northSouth: Long = 0) { private var direction: Direction = Direction.EAST open fun applyMove(shipMove: ShipMove) { when (shipMove.action) { F -> applyMove(ShipMove(shipMove.action.fromDirection(direction), shipMove.units)) L -> direction = direction.rotate(-shipMove.units) R -> direction = direction.rotate(shipMove.units) N -> northSouth += shipMove.units S -> northSouth -= shipMove.units E -> eastWest += shipMove.units W -> eastWest -= shipMove.units } } } private class ShipWithWayPoint : Ship() { var waypoint: Waypoint = Waypoint() override fun applyMove(shipMove: ShipMove) { when (shipMove.action) { F -> { super.applyMove(ShipMove(E, waypoint.eastWest.toInt() * shipMove.units)) super.applyMove(ShipMove(N, waypoint.northSouth.toInt() * shipMove.units)) } L -> waypoint = waypoint.rotate(-shipMove.units) R -> waypoint = waypoint.rotate(shipMove.units) N -> waypoint.northSouth += shipMove.units S -> waypoint.northSouth -= shipMove.units E -> waypoint.eastWest += shipMove.units W -> waypoint.eastWest -= shipMove.units } } } private class Waypoint(var eastWest: Long = 10, var northSouth: Long = 1) { fun rotate(degrees: Int): Waypoint { return when { degrees == 0 -> this degrees > 0 -> Waypoint(northSouth, -eastWest).rotate(degrees - 90) else -> Waypoint(-this.northSouth, eastWest).rotate(degrees + 90) } } } private enum class Action { N, S, E, W, L, R, F; fun fromDirection(direction: Direction): Action { return when (direction) { Direction.NORTH -> N Direction.SOUTH -> S Direction.EAST -> E Direction.WEST -> W } } } private class ShipMove(var action: Action, var units: Int) private enum class Direction { NORTH, SOUTH, EAST, WEST; fun rotate(degrees: Int): Direction { val pos = if (degrees > 0) { listOf(NORTH, EAST, SOUTH, WEST) } else { listOf(NORTH, WEST, SOUTH, EAST) } return pos[(pos.indexOf(this) + (abs(degrees) / 90)) % 4] } } }
0
Kotlin
0
0
147553654412ae1da4b803328e9fc13700280c17
3,786
adventofcode2020
MIT License
src/test/kotlin/adventofcode/day12/Day12.kt
jwcarman
573,183,719
false
{"Kotlin": 183494}
/* * Copyright (c) 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 adventofcode.day12 import adventofcode.util.graph.Graph import adventofcode.util.graph.SparseGraph import adventofcode.util.readAsString import adventofcode.util.table.Table import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day12 { @Test fun example1() { assertEquals(31, calculatePart1(readAsString("day12-example.txt"))) } @Test fun part1() { assertEquals(497, calculatePart1(readAsString("day12.txt"))) } @Test fun example2() { assertEquals(29, calculatePart2(readAsString("day12-example.txt"))) } @Test fun part2() { assertEquals(492, calculatePart2(readAsString("day12.txt"))) } private fun buildGraph(input: String, isEdge: (Table<Char>.Cell, Table<Char>.Cell) -> Boolean): Graph<Table<Char>.Cell, Unit> { val table = Table(input.lines().map { it.toCharArray().toList() }) val graph = SparseGraph<Table<Char>.Cell, Unit>() table.cells().forEach { graph.addVertex(it) } table.cells().forEach { from -> from.neighbors() .filter { to -> isEdge(from, to) } .forEach { graph.addEdge(from, it, Unit, 1.0) } } return graph } private fun calculatePart1(input: String): Int { val graph = buildGraph(input) { from, to -> checkNeighborFromStart(from, to) } val start = graph.vertices().first { it.value() == 'S' } val end = graph.vertices().first { it.value() == 'E' } val shortestPaths = graph.shortestPaths(start) return shortestPaths.pathTo(end).size } private fun calculatePart2(input: String): Int { val graph = buildGraph(input) { from, to -> checkNeighborFromEnd(from, to) } val end = graph.vertices().first { it.value() == 'E' } val shortestPaths = graph.shortestPaths(end) val closest = graph.vertices() .filter { normalize(it.value()) == 'a' } .minBy { shortestPaths.distanceTo(it) } return shortestPaths.pathTo(closest).size } private fun normalize(height: Char): Char { if (height == 'E') { return 'z' } if (height == 'S') { return 'a' } return height } private fun checkNeighborFromStart(src: Table<Char>.Cell, neighbor: Table<Char>.Cell): Boolean { val srcHeight = normalize(src.value()) val neighborHeight = normalize(neighbor.value()) return neighborHeight <= srcHeight + 1 } private fun checkNeighborFromEnd(src: Table<Char>.Cell, neighbor: Table<Char>.Cell): Boolean { val srcHeight = normalize(src.value()) val neighborHeight = normalize(neighbor.value()) return neighborHeight >= srcHeight - 1 } }
0
Kotlin
0
0
d6be890aa20c4b9478a23fced3bcbabbc60c32e0
3,391
adventofcode2022
Apache License 2.0
csp-sudoku/src/main/kotlin/com/tsovedenski/csp/sudoku/Sudoku.kt
RedShuhart
152,120,429
false
null
package com.tsovedenski.csp.sudoku import com.tsovedenski.csp.* import kotlin.math.roundToInt import kotlin.math.sqrt /** * Created by <NAME> on 15/10/2018. * * listOf( * "12xx5xxx9", * "x3x9xx4x8", * ... * ) */ data class Sudoku (val grid: List<String>, val placeholder: Char = 'x') : Solvable<String, Int> { private val size = grid.size private val variables = (0 until size) .flatMap { x -> (0 until size).map { y -> "$x$y" } } private val domain = (1..9).toList() private val constraints: List<Constraint<String, Int>> = listOf( rows(size).map<List<String>, Constraint<String, Int>>(::AllDiffConstraint), cols(size).map<List<String>, Constraint<String, Int>>(::AllDiffConstraint), blocks(size).map<List<String>, Constraint<String, Int>>(::AllDiffConstraint) ).flatten() private val known: Map<String, List<Int>> = grid .asSequence() .zip(generateSequence(0) { it + 1 }) .flatMap { (row, ir) -> row.asSequence().mapIndexed { ic, c -> Triple(c, ir, ic) } } .filter { (c, _, _) -> c != placeholder } .associate { (c, ir, ic) -> "$ir$ic" to listOf(c.toInt() - 48) } override fun toProblem(): Problem<String, Int> { val domains = variables.withDomain(domain).toMutableMap() known.forEach { c, v -> domains.merge(c, v) { _, x -> x} } return Problem(domains, constraints) } companion object { // [[00, 01,.., 08], [10, 11,.., 18], ...] private val rows: (Int) -> List<List<String>> = { size -> (0 until size).map { r -> (0 until size).map { c -> "$r$c" } } } // [[00, 10,.., 80], [01, 11,.., 81], ...] private val cols: (Int) -> List<List<String>> = { size -> (0 until size).map { r -> (0 until size).map { c -> "$c$r" } } } // [[00, 01, 02, 10, 11, 12, 20, 21, 22], ...] private val blocks: (Int) -> List<List<String>> = { size -> val sq = sqrt(size.toDouble()).roundToInt() val ns = (0 until size).asSequence() ns .flatMap { a -> ns.map { b -> a to b }.windowed(sq, size) } .windowed(sq, sq) .map { it.flatten() } .flatMap { ls -> (0 until size step sq) .asSequence() .map { i -> ls .map { (a, b) -> a to b + i } .map { (r, c) -> "$r$c" } } } .toList() } } }
0
Kotlin
1
4
29d59ec7ff4f0893c0d1ec895118f961dd221c7f
2,731
csp-framework
MIT License
atcoder/arc158/e_slow.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc158 fun main() { readLn() val top = readInts() val bottom = readInts() val inf = Long.MAX_VALUE / 4 data class Score(val score: Long, val improve: Long) fun solve(from: Int, to: Int): Modular1 { if (from + 1 == to) { return (top[from] + bottom[from]).toModular() * 3.toModularUnsafe() } val mid = (from + to) / 2 var result = solve(from, mid) + solve(mid, to) val (scoresLeft, scoresRight) = List(2) { mode -> var bestUpTop = 0L var bestUpBottom = inf var bestDownTop = inf var bestDownBottom = 0L val scores = mutableListOf<Score>() val range = if (mode == 1) mid until to else mid - 1 downTo from for (i in range) { val newBestUpTop = minOf(bestUpTop, bestUpBottom + bottom[i]) + top[i] val newBestUpBottom = minOf(bestUpBottom, bestUpTop + top[i]) + bottom[i] val newBestDownTop = minOf(bestDownTop, bestDownBottom + bottom[i]) + top[i] val newBestDownBottom = minOf(bestDownBottom, bestDownTop + top[i]) + bottom[i] scores.add(Score(newBestUpTop, - newBestDownTop + newBestUpTop)) scores.add(Score(newBestUpBottom, - newBestDownBottom + newBestUpBottom)) bestUpTop = newBestUpTop; bestUpBottom = newBestUpBottom bestDownTop = newBestDownTop; bestDownBottom = newBestDownBottom } scores.sortedBy { it.improve } } val s1 = scoresLeft.map { it.score.toModular() }.fold(0.toModularUnsafe(), Modular1::plus) val s2 = scoresRight.map { it.score.toModular() }.fold(0.toModularUnsafe(), Modular1::plus) var sc = s1 * (scoresRight.size).toModularUnsafe() + s2 * (scoresLeft.size).toModularUnsafe() var j = scoresRight.size var sumJ = 0.toModularUnsafe() for (i in scoresLeft.indices) { while (j >= 1 && scoresLeft[i].improve + scoresRight[j - 1].improve > 0) { j-- sumJ += scoresRight[j].improve.toModular() } sc -= scoresLeft[i].improve.toModular() * (scoresRight.size - j).toModularUnsafe() sc -= sumJ } result += sc * 2.toModularUnsafe() return result } println(solve(0, top.size)) } private val bufferedReader = java.io.BufferedReader(java.io.InputStreamReader(System.`in`)) private fun readLn() = bufferedReader.readLine() private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun readLongs() = readStrings().map { it.toLong() } private class Modular1(val x: Int) { companion object { const val M = 998244353; val MOD_BIG_INTEGER = M.toBigInteger() } inline operator fun plus(that: Modular1) = Modular1((x + that.x).let { if (it >= M) it - M else it }) inline operator fun minus(that: Modular1) = Modular1((x - that.x).let { if (it < 0) it + M else it }) inline operator fun times(that: Modular1) = Modular1((x.toLong() * that.x % M).toInt()) inline operator fun div(that: Modular1) = times(that.inverse()) inline fun inverse() = Modular1(x.toBigInteger().modInverse(MOD_BIG_INTEGER).toInt()) override fun toString() = x.toString() } private fun Int.toModularUnsafe() = Modular1(this) private fun Int.toModular() = Modular1(if (this >= 0) { if (this < Modular1.M) this else this % Modular1.M } else { Modular1.M - 1 - inv() % Modular1.M }) private fun Long.toModular() = Modular1((if (this >= 0) { if (this < Modular1.M) this else this % Modular1.M } else { Modular1.M - 1 - inv() % Modular1.M }).toInt()) private fun java.math.BigInteger.toModular() = Modular1(mod(Modular1.MOD_BIG_INTEGER).toInt()) private fun String.toModular() = Modular1(fold(0L) { acc, c -> (c - '0' + 10 * acc) % Modular1.M }.toInt()) private class ModularArray1(val data: IntArray) { operator fun get(index: Int) = data[index].toModularUnsafe() operator fun set(index: Int, value: Modular1) { data[index] = value.x } } private inline fun ModularArray(n: Int, init: (Int) -> Modular1) = ModularArray1(IntArray(n) { init(it).x }) private val factorials = mutableListOf(1.toModularUnsafe()) private fun factorial(n: Int): Modular1 { while (n >= factorials.size) factorials.add(factorials.last() * factorials.size.toModularUnsafe()) return factorials[n] } private fun cnk(n: Int, k: Int) = factorial(n) / factorial(k) / factorial(n - k)
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
4,167
competitions
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxConsecutiveAnswers.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min private const val SYMBOL_T = 'T' private const val SYMBOL_F = 'F' /** * 2024. Maximize the Confusion of an Exam * @see <a href="https://leetcode.com/problems/maximize-the-confusion-of-an-exam/">Source</a> */ fun interface MaxConsecutiveAnswers { operator fun invoke(answerKey: String, k: Int): Int } /** * Approach 1: Binary Search + Fixed Size Sliding Window */ class MaxConsecutiveAnswersBS : MaxConsecutiveAnswers { override operator fun invoke(answerKey: String, k: Int): Int { val n: Int = answerKey.length var left = k var right = n while (left < right) { val mid = (left + right + 1) / 2 if (isValid(answerKey, mid, k)) { left = mid } else { right = mid - 1 } } return left } private fun isValid(answerKey: String, size: Int, k: Int): Boolean { val n = answerKey.length val counter: MutableMap<Char, Int> = HashMap() for (i in 0 until size) { val c = answerKey[i] counter[c] = counter.getOrDefault(c, 0) + 1 } if (min(counter.getOrDefault(SYMBOL_T, 0), counter.getOrDefault(SYMBOL_F, 0)) <= k) { return true } for (i in size until n) { val c1 = answerKey[i] counter[c1] = counter.getOrDefault(c1, 0) + 1 val c2 = answerKey[i - size] counter[c2] = counter.getOrDefault(c2, 0) - 1 if (min(counter.getOrDefault(SYMBOL_T, 0), counter.getOrDefault(SYMBOL_F, 0)) <= k) { return true } } return false } } /** * Approach 2: Sliding Window */ class MaxConsecutiveAnswersSlidingWindow : MaxConsecutiveAnswers { override operator fun invoke(answerKey: String, k: Int): Int { var maxSize = k val count: MutableMap<Char, Int> = HashMap() for (i in 0 until k) { count[answerKey[i]] = count.getOrDefault(answerKey[i], 0) + 1 } var left = 0 for (right in k until answerKey.length) { count[answerKey[right]] = count.getOrDefault(answerKey[right], 0) + 1 while (min(count.getOrDefault(SYMBOL_T, 0), count.getOrDefault(SYMBOL_F, 0)) > k) { count[answerKey[left]] = count[answerKey[left]]!! - 1 left++ } maxSize = max(maxSize, right - left + 1) } return maxSize } } /** * Approach 3: Advanced Sliding Window */ class MaxConsecutiveAnswersSlidingWindow2 : MaxConsecutiveAnswers { override operator fun invoke(answerKey: String, k: Int): Int { var maxSize = 0 val count: MutableMap<Char, Int> = HashMap() for (right in answerKey.indices) { count[answerKey[right]] = count.getOrDefault(answerKey[right], 0) + 1 val minor = min(count.getOrDefault(SYMBOL_T, 0), count.getOrDefault(SYMBOL_F, 0)) if (minor <= k) { maxSize++ } else { count[answerKey[right.minus(maxSize)]] = count[answerKey[right.minus(maxSize)]]!! - 1 } } return maxSize } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,880
kotlab
Apache License 2.0
src/main/kotlin/com/colinodell/advent2021/Day23.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 import java.util.* import kotlin.Comparator import kotlin.collections.HashSet import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min // Adapted from https://github.com/schovanec/AdventOfCode/blob/master/2021/Day23/Program.cs class Day23(input: List<String>) { companion object { internal const val hallwayLength = 11 internal val amphipodTypes = charArrayOf('A', 'B', 'C', 'D') internal val roomPositions = arrayOf(2, 4, 6, 8) } private val initialState = parse(input) private val goalState = initialState.copy(rooms = initialState.rooms.toCharArray().sorted().joinToString("")) fun solve(): Int { return solve(initialState, goalState) } private fun parse(input: List<String>): State { val hall = ".".repeat(hallwayLength) val rooms = mutableListOf("", "", "", "") for (line in input) { if (line.any { amphipodTypes.contains(it) }) { val values = line.filter { amphipodTypes.contains(it) } for (i in rooms.indices) { rooms[i] = rooms[i] + values[i] } } } return State(hall, rooms.joinToString(""), rooms[0].length); } private fun solve(start: State, goal: State): Int { val bestCostPerState = mutableMapOf(start to 0) val visited = HashSet<State>() val queue = PriorityQueue<Move>(1, Comparator.comparingInt { it.cost }) queue.add(Move(start, 0)) while (!queue.isEmpty()) { val current = queue.poll() // Skip any states we've already visited if (visited.contains(current.state)) { continue } visited.add(current.state) if (current.state == goal) { break } val currentCost = bestCostPerState[current.state]!! for(next in current.state.nextPossibleMoves()) { val alt = currentCost + next.cost if (alt < bestCostPerState.getOrDefault(next.state, Int.MAX_VALUE)) { bestCostPerState[next.state] = alt queue.add(Move(next.state, alt)) } } } return bestCostPerState[goal]!! } private data class Move(val state: State, val cost: Int) private data class State(val hall: String, val rooms: String, val roomSize: Int) { fun getRoom(room: Int): String { return rooms.substring(room * roomSize).take(roomSize) } fun nextPossibleMoves() = sequence { for(room in 0 until 4) { for (pos in openSpaces(room)) { yieldIfNotNull(tryMoveOut(room, pos)) } } for(i in hall.indices) { yieldIfNotNull(tryMoveIn(i)) } } private fun openSpaces(room: Int) = sequence { val position = roomPositions[room] var i = position - 1 while (i >= 0 && hall[i] == '.') { if (!roomPositions.contains(i)) { yield(i) } i-- } i = position + 1 while (i < hall.length && hall[i] == '.') { if (!roomPositions.contains(i)) { yield(i) } i++ } } private fun tryMoveOut(roomIndex: Int, targetPosition: Int): Move? { val room = getRoom(roomIndex) val depth = room.indexOfAny(amphipodTypes) if (depth < 0) { return null } val steps = (targetPosition - roomPositions[roomIndex]).absoluteValue + depth + 1 val amphipod = room[depth] val updatedHall = hall.replaceAt(targetPosition, amphipod) val updatedRoom = room.replaceAt(depth, '.') return Move(update(updatedHall, roomIndex, updatedRoom), steps * getEnergyCost(amphipod)) } private fun tryMoveIn(hallwayPosition: Int): Move? { val amphipod = hall[hallwayPosition] val goalRoomIndex = amphipodTypes.indexOf(amphipod) if (goalRoomIndex < 0) { return null } val goalPosition = roomPositions[goalRoomIndex] val start = if (goalPosition > hallwayPosition) hallwayPosition + 1 else hallwayPosition - 1 val min = min(goalPosition, start) val max = max(goalPosition, start) if (!hall.substring(min, max).all { it == '.' }) { return null } val room = getRoom(goalRoomIndex) if (room.any { it != '.' && it != amphipod }) { return null } val depth = room.lastIndexOf('.') val steps = (max - min + 1) + depth + 1 val updatedHall = hall.replaceAt(hallwayPosition, '.') val updatedRoom = room.replaceAt(depth, amphipod) return Move(update(updatedHall, goalRoomIndex, updatedRoom), steps * getEnergyCost(amphipod)) } private fun update(updatedHall: String, roomIndex: Int, updatedRoom: String): State { val updatedRooms = rooms.replaceAt(roomIndex * roomSize, roomSize, updatedRoom) return this.copy(hall = updatedHall, rooms = updatedRooms) } private fun getEnergyCost(amphipod: Char): Int { return when (amphipod) { 'A' -> 1 'B' -> 10 'C' -> 100 'D' -> 1000 else -> throw IllegalArgumentException("Unknown amphipod type: $amphipod") } } } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
5,807
advent-2021
Apache License 2.0
year2016/src/main/kotlin/net/olegg/aoc/year2016/day3/Day3.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2016.day3 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2016.DayOf2016 /** * See [Year 2016, Day 3](https://adventofcode.com/2016/day/3) */ object Day3 : DayOf2016(3) { private val DIGITS = "\\d+".toRegex() override fun first(): Any? { return lines .map { line -> DIGITS.findAll(line) .map { it.value.toInt() } .toList() .sorted() } .filter { it.size == 3 } .count { it[0] + it[1] > it[2] } } override fun second(): Any? { val rows = lines .map { line -> DIGITS.findAll(line) .map { it.value.toInt() } .toList() } val columns = (1..rows.size / 3) .map { it * 3 } .map { rows.take(it).takeLast(3) } .flatMap { matrix -> listOf( listOf(matrix[0][0], matrix[1][0], matrix[2][0]), listOf(matrix[0][1], matrix[1][1], matrix[2][1]), listOf(matrix[0][2], matrix[1][2], matrix[2][2]), ) } .filter { it.size == 3 } .map { it.sorted() } return columns.count { it[0] + it[1] > it[2] } } } fun main() = SomeDay.mainify(Day3)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,174
adventofcode
MIT License
src/day03/Day03.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day03 import readInput fun main() { val input = readInput(parent = "src/Day03", name = "Day03_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartTwo(input: List<String>): Int { var sum = 0 var teamCount = 0 val charsInFirst = mutableSetOf<Char>() val charsInFirstAndSecond = mutableSetOf<Char>() input.forEach { rucksack -> when (teamCount % 3) { 0 -> { charsInFirst.clear() charsInFirst.addAll(rucksack.toSet()) } 1 -> { charsInFirstAndSecond.clear() for (c in rucksack) { if (charsInFirst.contains(c)) { charsInFirstAndSecond.add(c) } } } 2 -> { for (c in rucksack) { if (charsInFirstAndSecond.contains(c)) { sum += c.getPriority() break } } } } teamCount++ } return sum } private fun solvePartOne(input: List<String>): Int { var sum = 0 input.forEach { rucksack -> val charsInFirstHalf = mutableSetOf<Char>() for (i in rucksack.indices) { val c = rucksack[i] if (i < rucksack.length / 2) { charsInFirstHalf.add(c) } else { if (charsInFirstHalf.contains(c)) { sum += c.getPriority() break } } } } return sum } private fun Char.getPriority() = if (isUpperCase()) { this - 'A' + 27 } else { this - 'a' + 1 }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
1,748
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day22.kt
andilau
399,220,768
false
{"Kotlin": 85768}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2020/day/22", date = Date(day = 22, year = 2020) ) class Day22(val lines: List<String>) : Puzzle { override fun partOne(): Int { val deck1: Deck = readDeckOf("Player 1") val deck2: Deck = readDeckOf("Player 2") return if (deck1.play(deck2)) deck1.score else deck2.score } override fun partTwo(): Int { val deck1: Deck = readDeckOf("Player 1") val deck2: Deck = readDeckOf("Player 2") return if (deck1.playRecursive(deck2)) deck1.score else deck2.score } private fun Deck.playRecursive(other: Deck): Boolean { val seen = mutableSetOf(this to other) while (isNotEmpty() && other.isNotEmpty()) { val a = removeFirst() val b = other.removeFirst() val winner = if (a <= size && b <= other.size) deckFromCardTake(a).playRecursive(other.deckFromCardTake(b)) else a > b when { winner -> add(a) && add(b) else -> other.add(b) && other.add(a) } if (!seen.add(Pair(this, other))) return true } return this.isNotEmpty() } private fun Deck.play(other: Deck): Boolean { while (isNotEmpty() && other.isNotEmpty()) { val a = removeFirst() val b = other.removeFirst() if (a > b) add(a) && add(b) else other.add(b) && other.add(a) } return isNotEmpty() } private fun readDeckOf(playerName: String): Deck { return lines .asSequence() .dropWhile { line -> !line.startsWith(playerName) } .drop(1) .takeWhile { line -> line.isNotBlank() } .map { line -> line.toInt() } .toMutableList() .let { Deck(it) } } data class Deck(val deck: MutableList<Int>) : MutableList<Int> by deck { val score: Int get() = deck.foldRightIndexed(0) { index, element, acc -> acc + (size - index) * element } fun deckFromCardTake(count: Int) = Deck(deck.take(count).toMutableList()) } }
7
Kotlin
0
0
2809e686cac895482c03e9bbce8aa25821eab100
2,252
advent-of-code-2020
Creative Commons Zero v1.0 Universal