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/leetcode/Problem1514.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import java.util.PriorityQueue /** * https://leetcode.com/problems/path-with-maximum-probability/ */ class Problem1514 { fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double { val adjList = buildAdjList(n, edges, succProb) val dist = DoubleArray(n) { Double.NEGATIVE_INFINITY } val queue = PriorityQueue<Node>() queue += Node(start, dist[start]) while (queue.isNotEmpty()) { val node = queue.remove() for (edge in adjList[node.n]) { val prob = if (dist[edge.from] == Double.NEGATIVE_INFINITY) edge.prob else dist[edge.from] * edge.prob if (prob > dist[edge.to]) { dist[edge.to] = prob queue += Node(edge.to, prob) } } } return if (dist[end] == Double.NEGATIVE_INFINITY) 0.0 else dist[end] } private fun buildAdjList(n: Int, edges: Array<IntArray>, succProb: DoubleArray): Array<MutableList<Edge>> { val adjList = Array(n) { mutableListOf<Edge>() } for ((i, e) in edges.withIndex()) { val (from, to) = e adjList[from].add(Edge(from, to, succProb[i])) adjList[to].add(Edge(to, from, succProb[i])) } return adjList } private data class Node(val n: Int, val prob: Double) : Comparable<Node> { override fun compareTo(other: Node): Int { return other.prob.compareTo(prob) } } private data class Edge(val from: Int, val to: Int, val prob: Double) }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,664
leetcode
MIT License
src/y2023/d03/Day03.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2023.d03 import println import readInput class Num(val y: Int, val xMin: Int, val xMax: Int, val num: Int) { var adjacentPos: List<Pair<Int, Int>> = getAdjacent(this) override fun toString(): String { return "Num(y=$y, xMin=$xMin, xMax=$xMax, num=$num)" } fun nextToGear(pos: Pair<Int, Int>): Boolean { return adjacentPos.any { it == pos } } } fun getAdjacent(num: Num): List<Pair<Int, Int>> { val adjacentPos = mutableListOf<Pair<Int, Int>>() // top and bottom for (i in num.xMin - 1..num.xMax + 1) { adjacentPos.add(Pair(num.y - 1, i)) adjacentPos.add(Pair(num.y + 1, i)) } // left and right adjacentPos.add(Pair(num.y, num.xMin - 1)) adjacentPos.add(Pair(num.y, num.xMax + 1)) return adjacentPos } fun main() { val classPath = "y2023/d03" fun findNum(board: Array<CharArray>, y: Int, x: Int): Num { val digitArray = mutableListOf<Char>() var idx = x while (idx < board[0].size) { val currDigit = board[y][idx] if (!currDigit.isDigit()) { break } digitArray.add(currDigit) idx++ } return Num(y, x, idx - 1, digitArray.joinToString("").toInt()) } fun part1(input: List<String>): Int { val width = input[0].length val height = input.size val board = Array(width) { CharArray(height) } for (y in 0 until height) { for (x in 0 until width) { board[y][x] = input[y][x] } } val visited = mutableSetOf<Pair<Int, Int>>() val numbers = mutableListOf<Num>() val symbols = mutableSetOf<Pair<Int, Int>>() for (y in 0 until height) { for (x in 0 until width) { if (visited.contains(Pair(y, x))) continue visited.add(Pair(y, x)) when { board[y][x] == '.' -> continue board[y][x].isDigit() -> { val num = findNum(board, y, x) numbers.add(num) for (i in num.xMin..num.xMax) { visited.add(Pair(y, i)) } } else -> symbols.add(Pair(y, x)) // symbol } } } return numbers .filterNot { it.adjacentPos.all { adj -> !symbols.contains(adj) } } .sumOf { it.num } } fun part2(input: List<String>): Int { val width = input[0].length val height = input.size val board = Array(width) { CharArray(height) } for (y in 0 until height) { for (x in 0 until width) { board[y][x] = input[y][x] } } val visited = mutableSetOf<Pair<Int, Int>>() val numbers = mutableListOf<Num>() val gears = mutableSetOf<Pair<Int, Int>>() for (y in 0 until height) { for (x in 0 until width) { if (visited.contains(Pair(y, x))) continue visited.add(Pair(y, x)) when { board[y][x] == '.' -> continue board[y][x] == '*' -> gears.add(Pair(y, x)) board[y][x].isDigit() -> { val num = findNum(board, y, x) numbers.add(num) for (i in num.xMin..num.xMax) { visited.add(Pair(y, i)) } } } } } return gears .map { gear -> Pair(gear, numbers.filter { it.nextToGear(gear) }) } .filter { gear -> gear.second.size == 2 } .sumOf { gear -> gear.second.map { it.num }.reduce { acc, num -> acc * num } } } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") part1(testInput).println() part2(testInput).println() val input = readInput("${classPath}/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
4,179
aoc
Apache License 2.0
jk/src/main/kotlin/leetcode/Solution_LeetCode_1_Two_Sum_Three_Sum.kt
lchang199x
431,924,215
false
{"Kotlin": 86230, "Java": 23581}
package leetcode import java.util.* /** * 两数之和 */ class Solution_LeetCode_1_Two_Sum_Three_Sum { /** * 无序数组:空间换时间 * [](https://leetcode-cn.com/problems/two-sum/) */ fun twoSum(nums: IntArray, target: Int): IntArray { val map = hashMapOf<Int, Int>() nums.forEachIndexed { index, i -> if (map.containsKey(target - nums[index])) { return intArrayOf(index, map[target - nums[index]]!!) } map[nums[index]] = index } return intArrayOf() } /** * 排序数组:双指针 * [](https://leetcode-cn.com/problems/kLl5u1/) */ fun twoSumForSortedArray(nums: IntArray, target: Int): IntArray { var l = 0 var r = nums.size - 1 while (l < r) { val sum = nums[l] + nums[r] if (sum == target) { return intArrayOf(l, r) } else if (sum < target) { l++ } else { r-- } } return intArrayOf() } /** * 数组中和为0的3个数字 * [](https://leetcode-cn.com/problems/1fGaJU/) */ fun threeSum(nums: IntArray): List<List<Int>> { if (nums.size < 3) return emptyList() val result = mutableListOf<List<Int>>() Arrays.sort(nums) // kotlin中for循环i为val不便操作,一般用while var i = 0 while (i < nums.size - 2) { twoSumForThreeSum(nums, i, result) val temp = nums[i] // 排序之后这种连续跳过重复元素才成为可能 while (i < nums.size && temp == nums[i]) { ++i } } return result } private fun twoSumForThreeSum(nums: IntArray, i: Int, result: MutableList<List<Int>>) { var j = i + 1 var k = nums.size - 1 while (j < k) { if (nums[i] + nums[j] + nums[k] == 0) { result.add(listOf(nums[i], nums[j], nums[k])) val temp = nums[j] while (j < k && nums[j] == temp) { j++ } } else if (nums[i] + nums[j] + nums[k] < 0) { j++ } else { k-- } } } } fun main() { println(Solution_LeetCode_1_Two_Sum_Three_Sum().threeSum(intArrayOf(-1, 0, 1, 2, -1, 4))) println(Solution_LeetCode_1_Two_Sum_Three_Sum().threeSum(intArrayOf(1, -1, -1, 0))) }
0
Kotlin
0
0
52a008325dd54fed75679f3e43921fcaffd2fa31
2,527
Codelabs
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2018/Day24.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 24 - Immune System Simulator 20XX * * Problem Description: http://adventofcode.com/2018/day/24 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day24/ */ package com.ginsberg.advent2018 class Day24(immuneInput: List<String>, infectionInput: List<String>) { private val fighters: List<Group> = immuneInput.map { Group.of(Team.ImmuneSystem, it) } + infectionInput.map { Group.of(Team.Infection, it) } fun solvePart1(): Int = fightBattle(fighters).sumBy { it.units } fun solvePart2(): Int = generateSequence(1, Int::inc).mapNotNull { boost -> val combatants = fightBattle(boostImmuneSystem(boost)) if (combatants.all { it.team == Team.ImmuneSystem }) combatants.sumBy { it.units } else null }.first() private fun boostImmuneSystem(boost: Int): List<Group> = fighters.map { it.copy(unitDamage = it.unitDamage + if (it.team == Team.ImmuneSystem) boost else 0) } // Fight the battle with the given combatants, and return the survivors private fun fightBattle(combatants: List<Group>): List<Group> { var deaths: Int? = null while (deaths != 0) { deaths = roundOfFighting(combatants) } return combatants.filter { it.alive } } private fun roundOfFighting(combatants: List<Group>): Int = findTargets(combatants) .sortedByDescending { it.first.initiative } .filterNot { it.second == null } .map { (attacker, target) -> if (attacker.alive) attacker.fight(target!!) else 0 } .sum() private fun findTargets(combatants: List<Group>): Set<Pair<Group, Group?>> { val alreadyTargeted = mutableSetOf<Group>() return combatants.filter { it.alive } .sortedWith(compareByDescending<Group> { it.effectivePower() }.thenByDescending { it.initiative }) .map { group -> group to combatants .filter { it.alive } // Only fight the living .filterNot { group.team == it.team } // Only fight the other team .filterNot { it in alreadyTargeted } // Only fight somebody that isn't already a target .sortedWith(compareByDescending<Group> { group.calculateDamageTo(it) }.thenByDescending { it.effectivePower() }.thenByDescending { it.initiative }) .filterNot { group.calculateDamageTo(it) == 0 } // Remove any targets that we can't actually damage. .firstOrNull() // Account for the fact that we *may* not have a target .also { // Add our selected target to the targeted list if (it != null) alreadyTargeted.add(it) } } .toSet() } private enum class Team { ImmuneSystem, Infection } private data class Group( val team: Team, var units: Int, val unitHp: Int, val unitDamage: Int, val attackType: String, val initiative: Int, val weakTo: Set<String>, val immuneTo: Set<String>, var alive: Boolean = true ) { fun effectivePower(): Int = units * unitDamage fun calculateDamageTo(other: Group): Int = if (this.team == other.team) 0 else effectivePower() * when (attackType) { in other.immuneTo -> 0 in other.weakTo -> 2 else -> 1 } fun fight(other: Group): Int { val unitDeath = calculateDamageTo(other) / other.unitHp other.units -= unitDeath if (other.units <= 0) { other.alive = false } return unitDeath } companion object { private val pattern = """^(\d+) units each with (\d+) hit points (\([,; a-z]+\) )?with an attack that does (\d+) (\w+) damage at initiative (\d+)$""".toRegex() fun of(team: Team, input: String): Group { pattern.find(input)?.let { val (units, unitHp, strongWeak, unitDamage, attackType, initiative) = it.destructured return Group( team = team, units = units.toInt(), unitHp = unitHp.toInt(), unitDamage = unitDamage.toInt(), attackType = attackType, initiative = initiative.toInt(), weakTo = parseStrongWeak("weak", strongWeak), immuneTo = parseStrongWeak("immune", strongWeak) ) } } private fun parseStrongWeak(kind: String, input: String): Set<String> = if (input.isBlank()) emptySet() else { val found = input.drop(1).dropLast(2).split("; ").filter { it.startsWith(kind) } if (found.isEmpty()) { emptySet() } else { found.first().split("to ")[1].split(",").map { it.trim() }.toSet() } } } } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
5,406
advent-2018-kotlin
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2021/day15/day15.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day15 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val riskMap = parseRiskMap(lines) val lowestRiskPath = findLowestRiskPath(riskMap, start = Coord(0, 0), end = Coord(riskMap.getWidth() - 1, riskMap.getHeight() - 1) ) println(toString(riskMap, lowestRiskPath)) println("Lowest total risk of any path: ${getTotalRisk(riskMap, lowestRiskPath)}") val expandedMap = expandMap(riskMap, expandWidth = 4, expandHeight = 4) val lowestRiskPath5x5 = findLowestRiskPath(expandedMap, start = Coord(0, 0), end = Coord(expandedMap.getWidth() - 1, expandedMap.getHeight() - 1) ) println(toString(expandedMap, lowestRiskPath5x5)) println("Lowest total risk of any path: ${getTotalRisk(expandedMap, lowestRiskPath5x5)}") } fun parseRiskMap(lines: List<String>): Map<Coord, Int> = lines.parse2DMap { it.digitToInt() }.toMap() fun expandMap(riskMap: Map<Coord, Int>, expandWidth: Int, expandHeight: Int): Map<Coord, Int> { val width = riskMap.getWidth() val height = riskMap.getHeight() return buildMap { for (j in 0..expandHeight) { for (i in 0..expandWidth) { val delta = Coord(i * width, j * height) for ((coord, risk) in riskMap) { val newCoord = coord + delta var newRisk = risk + i + j while (newRisk > 9) { newRisk -= 9 } put(newCoord, newRisk) } } } } } fun findLowestRiskPath(riskMap: Map<Coord, Int>, start: Coord, end: Coord): List<Coord> = riskMap.toGraph(includeDiagonal = false) .findShortestPath(start.toGraphNode(), end.toGraphNode()) .map { it.coord } fun getTotalRisk(riskMap: Map<Coord, Int>, path: List<Coord>): Int = path.drop(1).sumOf { riskMap[it] ?: 0 } fun toString(riskMap: Map<Coord, Int>, path: List<Coord>, color: Boolean = true): String { val width = riskMap.getWidth() val height = riskMap.getHeight() return buildString { for (y in 0 until height) { for (x in 0 until width) { val coord = Coord(x, y) if (coord in path) { if (color) { append(AsciiColor.BRIGHT_WHITE.format(riskMap[coord])) } else { append(riskMap[coord]) } } else { append(riskMap[coord]) } } if (y < height - 1) { append("\n") } } } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,791
advent-of-code
MIT License
aoc/src/main/kotlin/com/bloidonia/aoc2023/day17/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day17 import com.bloidonia.aoc2023.graph.End import com.bloidonia.aoc2023.graph.Neighbours import com.bloidonia.aoc2023.graph.shortestPath import com.bloidonia.aoc2023.text private const val example = """2413432311323 3215453535623 3255245654254 3446585845452 4546657867536 1438598798454 4457876987766 3637877979653 4654967986887 4564679986453 1224686865563 2546548887735 4322674655533""" private const val example2 = """111111111111 999999999991 999999999991 999999999991 999999999991""" private data class Position(val x: Int, val y: Int) { operator fun plus(other: Position) = Position(x + other.x, y + other.y) } private enum class Direction(val position: Position) { UP(Position(0, -1)), DOWN(Position(0, 1)), LEFT(Position(-1, 0)), RIGHT(Position(1, 0)); fun left() = when (this) { UP -> LEFT LEFT -> DOWN DOWN -> RIGHT RIGHT -> UP } fun right() = when (this) { UP -> RIGHT RIGHT -> DOWN DOWN -> LEFT LEFT -> UP } } private data class Cart(val position: Position, val direction: Direction, val steps: Int) { fun next() = buildList { if (steps < 3) { add(Cart(position + direction.position, direction, steps + 1)) } add(Cart(position + direction.left().position, direction.left(), 1)) add(Cart(position + direction.right().position, direction.right(), 1)) } fun ultraNext() = buildList { if (steps < 10) { add(Cart(position + direction.position, direction, steps + 1)) } // Can't turn until 4 steps -- OR AT STARTING POSITION if (steps >= 4 || position == Position(0, 0)) { add(Cart(position + direction.left().position, direction.left(), 1)) add(Cart(position + direction.right().position, direction.right(), 1)) } } } private fun walk( input: String, nextFn: Neighbours<Cart>, endFn: End<Cart> ): Long? { val map = input.lines().withIndex() .flatMap { line -> line.value.mapIndexed { x, it -> Position(x, line.index) to it.digitToInt().toLong() } } .toMap() // Start going right, as next can cover both the right and down direction val start = Cart(Position(0, 0), Direction.RIGHT, 0) val path = shortestPath(start, endFn, nextFn, { _, (point) -> map[point]!! }) return path.getScore() } private fun part1(input: String): Long? { val (width, height) = input.lines().let { it[0].length to it.size } return walk( input, { it.next().filter { n -> n.position.x in 0..<width && n.position.y in 0..<height } }, { (p, _) -> p == Position(width - 1, height - 1) } ) } private fun part2(input: String): Long? { val (width, height) = input.lines().let { it[0].length to it.size } return walk( input, { it.ultraNext().filter { n -> n.position.x in 0..<width && n.position.y in 0..<height } }, // We need to have done at least 4 steps to get in the end position { (p, _, steps) -> p == Position(width - 1, height - 1) && steps >= 4 } ) } fun main() { println("Example 1: ${part1(example)}") println("Part 1: ${part1(text("/day17.input"))}") println("Example 2a: ${part2(example)}") println("Example 2b: ${part2(example2)}") println("Part 2: ${part2(text("/day17.input"))}") }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
3,398
aoc-2023
MIT License
src/Day04.kt
esteluk
572,920,449
false
{"Kotlin": 29185}
fun main() { fun part1(input: List<String>): Int { return input.map { elves -> val split = elves.split(",").map { range -> val rangeValues = range.split("-") IntRange(rangeValues[0].toInt(), rangeValues[1].toInt()) } val pair = Pair(split[0], split[1]) pair.first.contains(pair.second.first) && pair.first.contains(pair.second.last) || pair.second.contains(pair.first.first) && pair.second.contains(pair.first.last) }.count { it } } fun part2(input: List<String>): Int { return input.map { elves -> val split = elves.split(",").map { range -> val rangeValues = range.split("-") IntRange(rangeValues[0].toInt(), rangeValues[1].toInt()) } val pair = Pair(split[0], split[1]) pair.first.intersect(pair.second).isNotEmpty() }.count { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73
1,244
adventofcode-2022
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day10/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day10 import java.io.File fun main() { val input = File("src/main/kotlin/com/anahoret/aoc2022/day10/input.txt") .readText() .trim() val commandResults = input .split("\n") .map(Command.Companion::parse) .fold(State()) { state, comm -> state.run(comm) } .getCommandResults() // Part 1 part1(commandResults) // Part 2 part2(commandResults) } class State { private var current = CommandResult(0, 1) private val commandResults = mutableListOf<CommandResult>() fun run(command: Command): State { val result = when (command) { is Addx -> CommandResult( endsAfterTick = current.endsAfterTick + command.ticks, registerValueAfter = current.registerValueAfter + command.value ) Noop -> CommandResult( endsAfterTick = current.endsAfterTick + command.ticks, registerValueAfter = current.registerValueAfter ) } commandResults += result current = result return this } fun getCommandResults() = commandResults.toList() } sealed class Command(val ticks: Int) { companion object { fun parse(str: String): Command { return if (str.startsWith("noop")) Noop else Addx(str.split(" ")[1].toInt()) } } } class Addx(val value: Int) : Command(ticks = 2) object Noop : Command(ticks = 1) class CommandResult(val endsAfterTick: Int, val registerValueAfter: Int) private fun part1(commandResults: List<CommandResult>) { (20..220 step 40).sumOf { cycle -> commandResults.last { it.endsAfterTick < cycle } .registerValueAfter * cycle }.let(::println) } private fun part2(commandResults: List<CommandResult>) { val screenWidth = 40 val screenHeight = 6 val screen = Array(screenHeight) { Array(screenWidth) { ' ' } } (1..240).forEach { cycle -> val row = (cycle - 1) / screenWidth val col = (cycle - 1) % screenWidth val sprite = (commandResults.lastOrNull { it.endsAfterTick < cycle }?.registerValueAfter ?: 1) .let { (it - 1)..(it + 1) } if (col in sprite) screen[row][col] = '#' } println(screen.joinToString("\n") { it.joinToString(separator = "") }) }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
2,360
advent-of-code-2022
Apache License 2.0
src/year2023/09/Day09.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`09` import readInput import utils.printlnDebug private const val CURRENT_DAY = "09" private fun parseLineInto(line: String): List<Long> { return line.split(" ") .map { it.toLong() } } fun process(initialList: List<Long>): List<List<Long>> { val resList = mutableListOf(initialList) var currentValue: List<Long> = initialList while (currentValue.all { it == 0L }.not()) { val newList = mutableListOf<Long>() currentValue.windowed(2, 1, false) { val last = it.last() val first = it.first() newList.add(last - first) } currentValue = newList resList.add(currentValue) } return resList } fun List<List<Long>>.predictNewItem(): Long { return map { it.last() } .reversed() .reduce { acc, i -> acc + i } } fun List<List<Long>>.predictPrevItem(): Long { return map { it.first() } .reversed() .reduce { acc, i -> i - acc } } fun main() { fun part1(input: List<String>): Long { return input.map { process(parseLineInto(it)) } .onEach { printlnDebug { it } } .sumOf { it.predictNewItem() } } fun part2(input: List<String>): Long { return input.map { process(parseLineInto(it)) } .onEach { printlnDebug { it } } .sumOf { it.predictPrevItem() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 114L) val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 1479011877L) // Part 2 val part2 = part2(input) println(part2) check(part2 == 973L) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
1,882
KotlinAdventOfCode
Apache License 2.0
src/Day07.kt
allwise
574,465,192
false
null
fun main() { fun part1(input:String): Int { val processFiles = ProcessFiles(input) return processFiles.process() } fun part2(input:String): Int { val processFiles = ProcessFiles(input) return processFiles.process2() } // test if implementation meets criteria from the description, like: val testInput = readWholeFile("Day07_test") println("testinput 1 :" +part1(testInput)) check(part1(testInput) == 95437) println("testinput 2 :" +part2(testInput)) check(part2(testInput) == 24933642) val input = readWholeFile("Day07") println("real 1: " + part1(input)) println("real 2: " + part2(input)) // println(part2(input)) } class ProcessFiles(val input:String) { private val commands = input.replace("\r".toRegex(),"").split("\$ ") .map { command -> command.split("\n") .let { it.first() to it.drop(1)} } var root = Dir("/") var currentDir = root val totalSpace =70000000 val neededSpace = 30000000 init{ createFileSystem() } fun process(): Int { root.visualize("") val dirs = root.getAllDirs() return dirs.map { it.getSize() }.filter{ it<=100000 }.sum() } private fun createFileSystem() { commands.forEach { (command, rows) -> if (command.startsWith("ls")) { rows.forEach { currentDir.addContent(it) } } if (command.startsWith("cd ")) { cd(command.drop(3)) } } } fun cd(to: String) { //println(" cd \"$to\"") currentDir = when (to) { "/" -> root ".." -> currentDir.parent!! else -> currentDir.dirs.filter { it.name==to }.single() } } fun process2():Int{ // root.visualize("") val spaceToFree = neededSpace -(totalSpace -root.getSize()) val smallesUsableDir =root.getAllDirs().filter { it.getSize()>spaceToFree }.sortedBy { it.getSize() }.first() return smallesUsableDir.getSize() } } data class Dir(val name:String,val parent:Dir?=null){ var dirs:MutableList<Dir> = mutableListOf() var files:MutableMap<String,Int> = mutableMapOf() fun getSize():Int{ val fileSize =files.map { it.value }.sum() val dirSize = this.dirs.sumOf { it.getSize() } // println("size of $name: ${fileSize + dirSize}") return fileSize+dirSize } fun addContent(row:String){ // println("row \"$row\"") if(row.trim().isEmpty()){ return } row.split(" ").let{ if(it.first()=="dir"){ dirs.add(Dir(it[1],this)) return } if(it[0].matches("\\d*".toRegex())){ files.put(it[1], it[0].toInt()) } } } fun getAllDirs(): List<Dir> { val subList = listOf(this) + dirs.map { it.getAllDirs() }.flatten() return subList } fun visualize(pre:String){ println("$pre+$name") dirs.forEach{ it.visualize("$pre ") } files.forEach { (name, size) -> println(" $pre$name $size") } } }
0
Kotlin
0
0
400fe1b693bc186d6f510236f121167f7cc1ab76
3,255
advent-of-code-2022
Apache License 2.0
src/Day04.kt
Reivax47
572,984,467
false
{"Kotlin": 32685}
fun main() { fun part1(input: List<String>): Int { fun secontiennent(FirstElveDebut: Int, FirstElveFin: Int, SecondElveDebut: Int, SecondElveFin: Int): Boolean { return ((FirstElveDebut >= SecondElveDebut && FirstElveFin <= SecondElveFin) || (FirstElveDebut <= SecondElveDebut && FirstElveFin >= SecondElveFin)) } var somme = 0 input.forEach { pair -> val elves = pair.split(",") val firstelve = elves[0].split("-") val secondelve = elves[1].split("-") somme += if (secontiennent( firstelve[0].toInt(), firstelve[1].toInt(), secondelve[0].toInt(), secondelve[1].toInt() ) ) 1 else 0 } return somme } fun part2(input: List<String>): Int { fun overlap(FirstElveDebut: Int, FirstElveFin: Int, SecondElveDebut: Int, SecondElveFin: Int): Boolean { if (SecondElveDebut > FirstElveFin || SecondElveFin < FirstElveDebut) { return false } return true } var somme = 0 input.forEach { pair -> val elves = pair.split(",") val firstelve = elves[0].split("-") val secondelve = elves[1].split("-") somme += if (overlap( firstelve[0].toInt(), firstelve[1].toInt(), secondelve[0].toInt(), secondelve[1].toInt() ) ) 1 else 0 } return somme } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0affd02997046d72f15d493a148f99f58f3b2fb9
1,899
AD2022-01
Apache License 2.0
src/Day19.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
fun main() { fun parseInput(input: List<String>): MutableList<List<Int>> { val output = mutableListOf<List<Int>>() for (i in input) { val regex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian""".toRegex() val (num, ore, clay, obOre, obClay, geodeOre, geodeClay) = regex.find(i)!!.destructured output.add(listOf(num, ore, clay, obOre, obClay, geodeOre, geodeClay).map{it.toInt()}) } return output } //Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 4 ore. Each obsidian robot costs 2 ore and 7 clay. Each geode robot costs 4 ore and 13 obsidian. fun part1(input: MutableList<List<Int>>): Int { val END_TIME = 24 var scores = mutableListOf<Int>() for (bp in input) { val (num, ore, clay, obOre, obClay) = bp val geoOre = bp[5] val geoObs = bp[6] //println("num: $num, ore: $ore, clay: $clay, obOre: $obOre, obClay: $obClay, geoOre: $geoOre, geoObs: $geoObs") var state = mutableListOf(1, 0, 0, 0, 0, 0, 0, 0) // robots(ore, clay, obsidian, geode) resources(o, c, o, g) val q = ArrayDeque<MutableList<Int>>() q.add(state) for (i in 1..END_TIME) { val numInQ = q.size repeat(numInQ) { state = q.removeFirst() val robots = state.subList(0, 4) var oldResources = state.subList(4, 8) var newResources = robots.zip(oldResources) { a, b -> a + b } // Use resources to build new robots while ((oldResources[0] > geoOre) && (oldResources[2] > geoObs)) { } // Calculate resources built by current robots } } } return 0 } fun part2(input: List<String>): Int { val state = mutableListOf(1, 2, 3, 4, 5, 6, 7,8) // robots(ore, clay, obsidian, geode) resources(o, c, o, g) val sub1 = state.subList(0, 4) val sub2 = state.subList(4, 8) val sub3 = sub1.zip(sub2) { a, b -> a + b } println(sub1) println(sub2) println(sub3) return 0 } val input = readInput("../input/Day19") val blueprint = parseInput(input) println(part1(blueprint)) println(part2(input)) }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
2,546
aoc-2022
Apache License 2.0
2k23/aoc2k23/src/main/kotlin/14.kt
papey
225,420,936
false
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
package d14 fun main() { println("Part 1: ${part1(input.read("14.txt"))}") println("Part 2: ${part2(input.read("14.txt"))}") } fun part1(input: List<String>): Int { val platform = Platform(input.map { it.toCharArray() }) platform.tilt(Platform.Direction.North) return platform.load() } fun part2(input: List<String>): Int { val platform = Platform(input.map { it.toCharArray() }) val states: MutableMap<String, Int> = mutableMapOf() var times = 0 var remaining = 1000000000 while (!states.containsKey(platform.state())) { states[platform.state()] = times platform.cycle() times++ } val cycleLen = times - states[platform.state()]!! remaining - times remaining -= (remaining / cycleLen) * cycleLen repeat(remaining) { platform.cycle() } return platform.load() } class Platform(input: List<CharArray>) { private var dish = input private val roundedRock = 'O' private val emptySpace = '.' enum class Direction { North, West, South, East } fun tilt(dir: Direction) { return when (dir) { Direction.North -> { dish = tiltNorth(dish) } Direction.East -> { val oriented = transpose(dish).reversed() val tilted = tiltNorth(oriented) dish = transpose(tilted.reversed()) } Direction.West -> { dish = transpose(tiltNorth(transpose(dish))) } Direction.South -> { dish = tiltNorth(dish.reversed()).reversed() } } } fun cycle() = Direction.entries.forEach { tilt(it) } fun state() = dish.joinToString(":") { it.joinToString("") } fun load(): Int = dish.reversed().mapIndexed { index, chars -> chars.count { it == roundedRock } * (index + 1) }.sum() private fun tiltNorth(originDish: List<CharArray>): List<CharArray> { val tiltedDish = originDish.toMutableList() originDish.indices.forEach { y -> (originDish[0].indices).forEach x@{ x -> if (originDish[y][x] != roundedRock) { return@x } val newY = (0..<y).reversed().takeWhile { originDish[it][x] == emptySpace }.lastOrNull() ?: -1 if (newY != -1) { tiltedDish[newY][x] = roundedRock tiltedDish[y][x] = emptySpace } } } return tiltedDish } private fun transpose(dish: List<CharArray>): List<CharArray> { return dish[0].indices.map { i -> dish.map { it[i] }.toCharArray() } } }
0
Rust
0
3
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
2,796
aoc
The Unlicense
src/Day12.kt
fonglh
573,269,990
false
{"Kotlin": 48950, "Ruby": 1701}
import kotlin.math.absoluteValue fun main() { fun buildMap(input: List<String>): Array<CharArray> { var map = Array(input.size) { CharArray(input[0].length) } input.forEachIndexed { index, line -> map[index] = line.toCharArray() } return map } fun findStartAndEnd(map: Array<CharArray>): Pair<Pair<Int, Int>, Pair<Int, Int>> { var start: Pair<Int, Int> = Pair(0, 0) var end: Pair<Int, Int> = Pair(0, 0) map.forEachIndexed { rowNumber, row -> row.forEachIndexed { colNumber, col -> if (col == 'S') { start = Pair(rowNumber, colNumber) map[rowNumber][colNumber] = 'a' } else if (col == 'E') { end = Pair(rowNumber, colNumber) map[rowNumber][colNumber] = 'z' } } } return Pair(start, end) } fun isValidMove(map: Array<CharArray>, curr: Pair<Int, Int>, nextStep: Pair<Int, Int>): Boolean { val currHeight = map[curr.first][curr.second].hashCode() val nextHeight = map[nextStep.first][nextStep.second].hashCode() return nextHeight in 0..currHeight+1 } fun part1(input: List<String>): Int { var map = buildMap(input) val distances = HashMap<Pair<Int, Int>, Int>(map.size * map[0].size) val visited = mutableSetOf<Pair<Int, Int>>() val queue = mutableListOf<Pair<Int, Int>>() val startAndEnd = findStartAndEnd(map) val start = startAndEnd.first val end = startAndEnd.second distances[start] = 0 queue.add(start) visited.add(start) while(queue.isNotEmpty()) { val curr = queue.removeFirst() val currDistance = distances[curr]!! // reached the top if (curr == end) { return distances[curr]!! } for (i in -1..1) { for (j in -1..1) { //offsets will give up, down, left right if (i.absoluteValue != j.absoluteValue) { // check if new coords are valid val nextStep = Pair(curr.first + i, curr.second + j) if (nextStep.first >=0 && nextStep.first < map.size && nextStep.second >= 0 && nextStep.second < map[0].size && !visited.contains(nextStep) && isValidMove(map, curr, nextStep)) { // no need to handle relaxation step where distances get reduced // since all distances are equal if (!distances.containsKey(nextStep)) { distances[nextStep] = 1 + currDistance queue.add(nextStep) } } } } } visited.add(curr) } return 0 } // climb down by one, climb up by any amount. fun isValidMovePart2(map: Array<CharArray>, curr: Pair<Int, Int>, nextStep: Pair<Int, Int>): Boolean { val currHeight = map[curr.first][curr.second].hashCode() val nextHeight = map[nextStep.first][nextStep.second].hashCode() return nextHeight >= (currHeight - 1) } fun part2(input: List<String>): Int { var map = buildMap(input) val distances = HashMap<Pair<Int, Int>, Int>(map.size * map[0].size) val visited = mutableSetOf<Pair<Int, Int>>() val queue = mutableListOf<Pair<Int, Int>>() val startAndEnd = findStartAndEnd(map) val start = startAndEnd.first val end = startAndEnd.second // start from the E point and look for the first 'a' distances[end] = 0 queue.add(end) visited.add(end) while(queue.isNotEmpty()) { val curr = queue.removeFirst() val currDistance = distances[curr]!! // reached the bottom if (map[curr.first][curr.second] == 'a') { return distances[curr]!! } for (i in -1..1) { for (j in -1..1) { //offsets will give up, down, left right if (i.absoluteValue != j.absoluteValue) { // check if new coords are valid val nextStep = Pair(curr.first + i, curr.second + j) if (nextStep.first >=0 && nextStep.first < map.size && nextStep.second >= 0 && nextStep.second < map[0].size && !visited.contains(nextStep) && isValidMovePart2(map, curr, nextStep)) { // no need to handle relaxation step where distances get reduced // since all distances are equal if (!distances.containsKey(nextStep)) { distances[nextStep] = 1 + currDistance queue.add(nextStep) } } } } } visited.add(curr) } println("why here?") return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ef41300d53c604fcd0f4d4c1783cc16916ef879b
5,653
advent-of-code-2022
Apache License 2.0
src/Day04.kt
andydenk
573,909,669
false
{"Kotlin": 24096}
fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { return input .map { it.toRangePair() } .count { (first, second) -> first in second || second in first } } private fun part2(input: List<String>): Int { return input .map { it.toRangePair() } .count { (first, second) -> first.intersects(second) || second.intersects(first) } } private operator fun IntRange.contains(otherRange: IntRange): Boolean { return first() <= otherRange.first() && last() >= otherRange.last() } private fun IntRange.intersects(otherRange: IntRange): Boolean { return first() <= otherRange.last && otherRange.first <= last } private fun String.toRangePair(): Pair<IntRange, IntRange> { return substringBefore(',').toIntRange() to substringAfter(',').toIntRange() } private fun String.toIntRange(): IntRange { return substringBefore('-').toInt()..substringAfter('-').toInt() }
0
Kotlin
0
0
1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1
1,218
advent-of-code-2022
Apache License 2.0
src/Day07.kt
rickbijkerk
572,911,701
false
{"Kotlin": 31571}
fun main() { class Node( val value: Int, val children: MutableList<Node> = mutableListOf(), val name: String, val parent: Node? = null, var folderSize: Int = 0 ) { override fun toString(): String { return "Node(name='$name', value=$value)" } } var lessThanCutOff = mutableListOf<Int>() fun foldersLessThan(parentNode: Node): Int { val size = parentNode.children.sumOf { node -> if (node.children.isNotEmpty()) { foldersLessThan(node) } else { node.value } } parentNode.folderSize = size if (size < 100_000) { lessThanCutOff.add(size) } return size } fun buildTree(input: List<String>): Node { val root = Node(0, name = "/") var currentNode = root input.forEach { line -> if (line.startsWith("$ cd")) { when (val dirToGoTo = line.split(" ")[2]) { "/" -> currentNode = root ".." -> currentNode = currentNode.parent!! else -> currentNode = currentNode.children.first { it.name == dirToGoTo } } } else if (line == "$ ls") { // do nothing } else if (!line.startsWith("$")) { val split = line.split(" ") if (line.startsWith("dir")) { currentNode.children.add(Node(0, name = split[1], parent = currentNode)) } else { currentNode.children.add(Node(split[0].toInt(), name = split[1], parent = currentNode)) } } } return root } fun part1(input: List<String>): Int { lessThanCutOff = mutableListOf() val root = buildTree(input) foldersLessThan(root) return lessThanCutOff.sum() } fun calculateFolderSize(parentNode: Node): Int { val size = parentNode.children.sumOf { node -> if (node.children.isNotEmpty()) { calculateFolderSize(node) } else { node.value } } parentNode.folderSize = size return size } fun getFoldersBiggerThan(parentNode: Node, minimalSize: Int, result: MutableList<Node>): List<Node> { val size = parentNode.children.forEach { node -> if (node.children.isNotEmpty()) { getFoldersBiggerThan(node, minimalSize, result) } else { node.value } } if (parentNode.folderSize > minimalSize) { result.add(parentNode) } return result } fun part2(input: List<String>): Int { val root = buildTree(input) calculateFolderSize(root) val spaceLeft = 70000000 - root.folderSize val neededSpace = 30000000 - spaceLeft val result = getFoldersBiggerThan(root, neededSpace, mutableListOf()) return result.map { it.folderSize }.minOf { it } } val testInput = readInput("day07_test") // test part1 val resultPart1 = part1(testInput) val expectedPart1 = 95437 //TODO Change me println("Part1\nresult: $resultPart1") println("expected:$expectedPart1 \n") check(resultPart1 == expectedPart1) //Check results part1 val input = readInput("day07") println("Part1 ${part1(input)}\n\n") // 1402048 // test part2 val resultPart2 = part2(testInput) val expectedPart2 = 24933642 //TODO Change me println("Part2\nresult: $resultPart2") println("expected:$expectedPart2 \n") check(resultPart2 == expectedPart2) //Check results part2 println("Part2 ${part2(input)}") // 9494924 <- too low }
0
Kotlin
0
0
817a6348486c8865dbe2f1acf5e87e9403ef42fe
3,827
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day4.kt
MisterJack49
729,926,959
false
{"Kotlin": 31964}
package days import kotlin.math.pow class Day4 : Day(4) { override fun partOne() = inputList .filterNot { it.isEmpty() } .parseCards().sumOf { it.points } override fun partTwo() = Deck(inputList .filterNot { it.isEmpty() } .parseCards()) .run { processCards() cards }.sumOf { it.instances } } private data class Deck(val cards: List<Card>) { fun processCards() { cards.forEach { card -> if(card.matches().none()) return@forEach val win = card.id + 1..card.id + card.matches().count() for (i in win) { cards[i-1].instances += card.instances } } } } private data class Card( val id: Int, val winning: List<Int>, val drawn: List<Int>, var points: Int = 0, var instances: Int = 1 ) { init { points = (if (matches().isEmpty()) 0.0 else 2.0.pow(matches().count() - 1)).toInt() } fun matches() = drawn.intersect(winning.toSet()) } private val cardRegex = Regex("(Card\\s+(?<id>\\d+)):\\s+(?<winning>(\\d+(?>\\s*))+)\\|\\s+(?<drawn>(\\d+(?>\\s*))+)") private fun List<String>.parseCards() = map { string -> val match = cardRegex.find(string)!! Card(match.groups["id"]!!.value.toInt(), match.groups["winning"]!!.value.split(" ").filterNot { it.isEmpty() }.map { it.toInt() }, match.groups["drawn"]!!.value.split(" ").filterNot { it.isEmpty() }.map { it.toInt() } ) }
0
Kotlin
0
0
807a6b2d3ec487232c58c7e5904138fc4f45f808
1,594
AoC-2023
Creative Commons Zero v1.0 Universal
advent-of-code-2021/src/code/day7/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day7 import java.io.File import kotlin.math.abs fun main() { doIt("Day 7 Part 1: Test Input", "src/code/day7/test.input", part1) doIt("Day 7 Part 1: Real Input", "src/code/day7/part1.input", part1) doIt("Day 7 Part 2: Test Input", "src/code/day7/test.input", part2); doIt("Day 7 Part 2: Real Input", "src/code/day7/part1.input", part2); } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Long) { val lines = arrayListOf<String>() File(input).forEachLine { lines.add(it) } println(String.format("%s: Ans: %d", msg , calc(lines))) } val part1: (List<String>) -> Long = { lines -> val input = parse(lines) val minNum = input.nums.minOrNull()!! val maxNum = input.nums.maxOrNull()!! var minCost = Long.MAX_VALUE for (i in minNum .. maxNum) { val costI = cost(input.nums, i) //println("$i - $costI") if (costI < minCost) { minCost = costI } } minCost } val part2: (List<String>) -> Long = { lines -> val input = parse(lines) val minNum = input.nums.minOrNull()!! val maxNum = input.nums.maxOrNull()!! var minCost = Long.MAX_VALUE for (i in minNum .. maxNum) { val costI = cost2(input.nums, i) //println("$i - $costI") if (costI < minCost) { minCost = costI } } minCost } val parse: (List<String>) -> Input = { lines -> val nums = lines[0].split(",").map { it.toInt() } Input(nums) } fun cost(nums: List<Int>, pos: Int): Long { var sum: Long = 0 for (element in nums) { sum += abs(element - pos) } return sum } fun cost2(nums: List<Int>, pos: Int): Long { var sum: Long = 0 for (element in nums) { val dist = abs(element - pos) sum += (dist * dist + dist)/2 } return sum } class Input(val nums: List<Int>)
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
1,887
misc-dev
MIT License
aoc2023/day17.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval import java.util.TreeSet fun main() { Day17.execute() } private object Day17 { fun execute() { INPUT = readInput() println("Part 1: ${part1()}") println("Part 2: ${part2()}") } private fun part1(): Int { dijkstra { it.neighbours() } return endNodes().minOf { it.dist } } private fun part2(): Int { dijkstra { it.ultraCrucibleNeighbours() } return endNodes(true).minOf { it.dist } } private fun readInput(): List<List<Int>> = InputRetrieval.getFile(2023, 17).readLines().map { it.map { c -> c.digitToInt() } } private fun endNodes(ultraCrucible: Boolean = false): List<Vertex> { val maxX = INPUT.first().size - 1 val maxY = INPUT.size - 1 return if (ultraCrucible) { NODES.values.filter { it.x == maxX && it.y == maxY && it.lastDirectionChange > 2 } } else { NODES.values.filter { it.x == maxX && it.y == maxY } } } lateinit var INPUT: List<List<Int>> private val NODES = mutableMapOf<Triple<Pair<Int, Int>, Direction, Int>, Vertex>() private fun getNode(pos: Pair<Int, Int>, dir: Direction, lastChange: Int): Vertex? { val (x, y) = pos val maxX = INPUT.first().size val maxY = INPUT.size if (x < 0 || y < 0 || x >= maxX || y >= maxY) { return null } return NODES.getOrPut(Triple(pos, dir, lastChange)) { Vertex(x = x, y = y, direction = dir, cost = INPUT[y][x], lastDirectionChange = lastChange) } } /** Implementation of dijkstra's algorithm, based on https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Kotlin */ private fun dijkstra(debug: Boolean = false, neighboursCalculation: (Vertex) -> Set<Vertex>) { val maxX = INPUT.first().size - 1 val maxY = INPUT.size - 1 NODES.clear() val q = TreeSet<Vertex>() val startingNodes = listOf( getNode(0 to 0, Direction.RIGHT, 0)!!, getNode(0 to 0, Direction.DOWN, 0)!! ) startingNodes.forEach { it.dist = 0 q.add(it) } while (!q.isEmpty()) { // Vertex with the shortest distance (first iteration will return source) val u = q.pollFirst()!! if (debug && u.x == maxX && u.y == maxY) { print("Found the target Node: ") u.printPath() println() } // If distance is infinite we can ignore 'u' (and any other remaining vertices), since they are unreachable if (u.dist == Int.MAX_VALUE) break // Look at distances to each neighbour for (v in neighboursCalculation.invoke(u)) { val alternateDist = u.dist + v.cost if (alternateDist < v.dist) { // Shorter path to neighbour found q.remove(v) v.dist = alternateDist v.previous = u q.add(v) } } } } private enum class Direction { UP, DOWN, LEFT, RIGHT } private data class Vertex( val x: Int, val y: Int, val direction: Direction, val cost: Int, var dist: Int = Int.MAX_VALUE, val lastDirectionChange: Int, var previous: Vertex? = null, ) : Comparable<Vertex> { fun neighbours(): Set<Vertex> { val neighbours = mutableSetOf<Vertex>() when (direction) { Direction.UP, Direction.DOWN -> { // Go forward if (lastDirectionChange < 2) { if (direction == Direction.UP) { getNode(x to y - 1, Direction.UP, lastDirectionChange + 1)?.let { neighbours.add(it) } } else { getNode(x to y + 1, Direction.DOWN, lastDirectionChange + 1)?.let { neighbours.add(it) } } } // Go left getNode(x - 1 to y, Direction.LEFT, 0)?.let { neighbours.add(it) } // Go Right getNode(x + 1 to y, Direction.RIGHT, 0)?.let { neighbours.add(it) } } Direction.LEFT, Direction.RIGHT -> { // Go forward if (lastDirectionChange < 2) { if (direction == Direction.LEFT) { getNode(x - 1 to y, Direction.LEFT, lastDirectionChange + 1)?.let { neighbours.add(it) } } else { getNode(x + 1 to y, Direction.RIGHT, lastDirectionChange + 1)?.let { neighbours.add(it) } } } // Go up getNode(x to y - 1, Direction.UP, 0)?.let { neighbours.add(it) } // Go down getNode(x to y + 1, Direction.DOWN, 0)?.let { neighbours.add(it) } } } return neighbours } fun ultraCrucibleNeighbours(): Set<Vertex> { val neighbours = mutableSetOf<Vertex>() when (direction) { Direction.UP, Direction.DOWN -> { // Go forward if (lastDirectionChange < 9) { if (direction == Direction.UP) { getNode(x to y - 1, Direction.UP, lastDirectionChange + 1)?.let { neighbours.add(it) } } else { getNode(x to y + 1, Direction.DOWN, lastDirectionChange + 1)?.let { neighbours.add(it) } } } if (lastDirectionChange > 2) { // Go left getNode(x - 1 to y, Direction.LEFT, 0)?.let { neighbours.add(it) } // Go Right getNode(x + 1 to y, Direction.RIGHT, 0)?.let { neighbours.add(it) } } } Direction.LEFT, Direction.RIGHT -> { // Go forward if (lastDirectionChange < 9) { if (direction == Direction.LEFT) { getNode(x - 1 to y, Direction.LEFT, lastDirectionChange + 1)?.let { neighbours.add(it) } } else { getNode(x + 1 to y, Direction.RIGHT, lastDirectionChange + 1)?.let { neighbours.add(it) } } } if (lastDirectionChange > 2) { // Go up getNode(x to y - 1, Direction.UP, 0)?.let { neighbours.add(it) } // Go down getNode(x to y + 1, Direction.DOWN, 0)?.let { neighbours.add(it) } } } } return neighbours } fun printPath() { val name = "[${x},${y}]" when (previous) { this -> print(name) null -> print("$name(unreached)") else -> { previous!!.printPath() print(" -> $name(${dist})") } } } override fun compareTo(other: Vertex): Int { if (dist == other.dist) { return "${x}-${y}-${direction}-${lastDirectionChange}".compareTo("${other.x}-${other.y}-${other.direction}-${other.lastDirectionChange}") } return dist.compareTo(other.dist) } } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
7,724
Advent-Of-Code
MIT License
advent-of-code2015/src/main/kotlin/day8/Advent8.kt
REDNBLACK
128,669,137
false
null
package day8 import parseInput import splitToLines /** --- Day 8: Matchsticks --- Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored. It is common in many programming languages to provide a way to escape special characters in strings. For example, C, JavaScript, Perl, Python, and even PHP handle special characters in very similar ways. However, it is important to realize the difference between the number of characters in the code representation of the string literal and the number of characters in the in-memory string itself. For example: "" is 2 characters of code (the two double quotes), but the string contains zero characters. "abc" is 5 characters of code, but 3 characters in the string data. "aaa\"aaa" is 10 characters of code, but the string itself contains six "a" characters and a single, escaped quote character, for a total of 7 characters in the string data. "\x27" is 6 characters of code, but the string itself contains just one - an apostrophe ('), escaped using hexadecimal notation. Santa's list is a file that contains many double-quoted string literals, one on each line. The only escape sequences used are \\ (which represents a single backslash), \" (which represents a lone double-quote character), and \x plus two hexadecimal characters (which represents a single character with that ASCII code). Disregarding the whitespace in the file, what is the number of characters of code for string literals minus the number of characters in memory for the values of the strings in total for the entire file? For example, given the four strings above, the total number of characters of string code (2 + 5 + 10 + 6 = 23) minus the total number of characters in memory for string values (0 + 3 + 7 + 1 = 11) is 23 - 11 = 12. --- Part Two --- Now, let's go the other way. In addition to finding the number of characters of code, you should now encode each code representation as a new string and find the number of characters of the new encoded representation, including the surrounding double quotes. For example: "" encodes to "\"\"", an increase from 2 characters to 6. "abc" encodes to "\"abc\"", an increase from 5 characters to 9. "aaa\"aaa" encodes to "\"aaa\\\"aaa\"", an increase from 10 characters to 16. "\x27" encodes to "\"\\x27\"", an increase from 6 characters to 11. Your task is to find the total number of characters to represent the newly encoded strings minus the number of characters of code in each original string literal. For example, for the strings above, the total encoded length (6 + 9 + 16 + 11 = 42) minus the characters in the original code representation (23, just like in the first part of this puzzle) is 42 - 23 = 19. */ fun main(args: Array<String>) { val test = """ |"" |"abc" |"aaa\"aaa" |"\x27" """.trimMargin() println(calcSizeDiff(test) == mapOf("first" to 12, "second" to 19)) val input = parseInput("day8-input.txt") println(calcSizeDiff(input)) } fun calcSizeDiff(input: String): Map<String, Int> { fun String.encodedCount() = 2 + sumBy { if (it == '\\' || it == '\"') 2 else 1 } fun String.decodedCount() = trim('"').replace("\\\"", "r") .replace("\\\\", "r") .replace(Regex("\\\\x[a-f0-9]{2}"), "r").length val lines = input.splitToLines() val lengthTotal = lines.sumBy { it.length } val decodedTotal = lines.sumBy(String::decodedCount) val encodedTotal = lines.sumBy(String::encodedCount) return mapOf("first" to lengthTotal - decodedTotal, "second" to encodedTotal - lengthTotal) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
3,723
courses
MIT License
src/Day08.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
enum class Direction {UP, DOWN, LEFT, RIGHT} fun main() { fun treeVisibleInDir(grid: List<String>, x: Int, y: Int, treeHeight: Int, direction: Direction): Pair<Boolean, Int> { when(direction) { Direction.UP -> { if(y-1 < 0) { return true to 0 } if(treeHeight <= grid[x][y-1].code) { return false to 1 } val recur = treeVisibleInDir(grid,x,y-1, treeHeight, direction) return recur.first to recur.second + 1 } Direction.DOWN -> { if(y+1 == grid.size) { return true to 0 } if(treeHeight <= grid[x][y+1].code) { return false to 1 } val recur = treeVisibleInDir(grid,x,y+1, treeHeight, direction) return recur.first to recur.second + 1 } Direction.LEFT -> { if(x-1 < 0) { return true to 0 } if(treeHeight <= grid[x-1][y].code) { return false to 1 } val recur = treeVisibleInDir(grid,x-1,y, treeHeight, direction) return recur.first to recur.second + 1 } Direction.RIGHT -> { if(x+1 == grid[0].length) { return true to 0 } if(treeHeight <= grid[x+1][y].code) { return false to 1 } val recur = treeVisibleInDir(grid,x+1,y, treeHeight, direction) return recur.first to recur.second + 1 } } } fun Pair<Boolean, Int>.getVisibility(): Boolean { return this.first } fun Pair<Boolean, Int>.getVisibleTrees(): Int { return this.second } fun part1And2(input: List<String>): Pair<Int, Int> { val width = input[0].length val height = input.size var visibleTrees = 0 var maxScenicScore = 0 for(y in 0 until width) { for(x in 0 until height) { val treeHeight = input[x][y].code // a list of pairs representing if the tree is visible // and its number of visible trees val treeVisibilities: List<Pair<Boolean, Int>> = Direction.values().map { treeVisibleInDir(input,x,y,treeHeight,it) } // check if tree is visible in any direction if(treeVisibilities.any{it.getVisibility()}) { visibleTrees++ } // update max scenic score maxScenicScore = maxScenicScore.coerceAtLeast( // calculate the scenic score by multiplying each // direction's visible trees treeVisibilities.map { it.getVisibleTrees() }.reduce { acc, i -> acc * i} ) } } return visibleTrees to maxScenicScore } val input = readInput("Day08") println(part1And2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
3,185
KotlinAdvent2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2015/Day9.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2015 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.permutations import com.chriswk.aoc.util.report import org.apache.logging.log4j.LogManager import kotlin.math.min class Day9: AdventDay(2015, 9) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day9() report { day.part1() } report { day.part2() } } val logger = LogManager.getLogger() } fun distances(input: List<String>): Map<Distance, Int> { return input.flatMap { val (cities, distance) = it.split(" = ") val (from, to) = cities.split(" to ") listOf( (Distance(from, to) to distance.toInt()), (Distance(to, from) to distance.toInt()) ) }.toMap() } fun totalDistance(distances: Map<Distance, Int>, journeys: List<String>, total: Int): Int { return if (journeys.isEmpty() || journeys.size == 1) { total } else { val (from, to) = journeys.take(2) totalDistance(distances, journeys.drop(1), total + distances.getOrDefault(Distance(from, to), 0)) } } fun shortestDistance(distances: Map<Distance, Int>, journeys: List<List<String>>): Int { return journeys.minOf { totalDistance(distances, it, 0) } } fun longestDistance(distances: Map<Distance, Int>, journeys: List<List<String>>): Int { return journeys.maxOf { totalDistance(distances, it, 0) } } fun locations(distances: Map<Distance, Int>): List<List<String>> { return distances.keys.flatMap { (from, to) -> val l = mutableListOf(from, to) distances.keys.forEach { if(!l.contains(it.to)) { l.add(it.to) } if(!l.contains(it.from)) { l.add(it.from) } } l.permutations() }.distinct() } fun part1(): Int { val d = distances(inputAsLines) val journeys = locations(d) logger.info("${journeys.size} to compare") assert(journeys.all { it.size == 8 }) return shortestDistance(d, journeys) } fun part2(): Int { val d = distances(inputAsLines) val journeys = locations(d) logger.info("${journeys.size} to compare") assert(journeys.all { it.size == 8 }) return longestDistance(d, journeys) } } data class Distance(val from: String, val to: String)
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,558
adventofcode
MIT License
src/hard/_4MedianOfTwoSortedArrays.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package hard class _4MedianOfTwoSortedArrays { class Solution { fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val length1 = nums1.size val length2 = nums2.size val findNext = (length1 + length2) % 2 == 0 val middle = (length1 + length2 - 1) / 2 val first = findNumByIndex(middle, nums1, nums2, length1, length2) var halfDelta = 0.0 if (findNext) { val second = findNumByIndex(middle + 1, nums1, nums2, length1, length2) halfDelta = (second - first) / 2.0 } return first + halfDelta } private fun findNumByIndex(index: Int, nums1: IntArray, nums2: IntArray, length1: Int, length2: Int): Double { var pointer1 = 0 var pointer2 = 0 var answer = 0 while ((pointer1 + pointer2) <= index) { answer = if (pointer1 == length1) { nums2[pointer2++] } else if (pointer2 == length2) { nums1[pointer1++] } else if (nums1[pointer1] < nums2[pointer2]) { nums1[pointer1++] } else { nums2[pointer2++] } } return answer.toDouble() } } class BestSolution { fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { if (nums1.size > nums2.size) { return findMedianSortedArrays(nums2, nums1) } val m = nums1.size val n = nums2.size var left = 0 var right = m // median1:前一部分的最大值 // median2:后一部分的最小值 var median1 = 0 var median2 = 0 while (left <= right) { // 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1] // 后一部分包含 nums1[i .. m-1] 和 nums2[j .. n-1] val i = (left + right) / 2 val j = (m + n + 1) / 2 - i // nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j] val nums_im1 = if (i == 0) Int.MIN_VALUE else nums1[i - 1] val nums_i = if (i == m) Int.MAX_VALUE else nums1[i] val nums_jm1 = if (j == 0) Int.MIN_VALUE else nums2[j - 1] val nums_j = if (j == n) Int.MAX_VALUE else nums2[j] if (nums_im1 <= nums_j) { median1 = Math.max(nums_im1, nums_jm1) median2 = Math.min(nums_i, nums_j) left = i + 1 } else { right = i - 1 } } return if ((m + n) % 2 == 0) (median1 + median2) / 2.0 else median1.toDouble() } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
2,907
AlgorithmsProject
Apache License 2.0
src/Day03.kt
ostersc
570,327,086
false
{"Kotlin": 9017}
fun main(){ fun part1(input: List<String>): Int { //count the 0s in each column val zeroSum=input.first().indices.map { charNum -> input.count{it[charNum]=='0'}} //turn them into 0 or 1 based on being the majority val digits=zeroSum.map { if(it <= input.size/2) '1' else '0' } //turn those into a string, but just flip the "bits" for the other value val epsilonDigits=digits.joinToString("") val gammaDigits=digits.map{if(it=='1') "0" else "1"}.joinToString("") //base 2 number from string return gammaDigits.toInt(2) * epsilonDigits.toInt(2) } fun part2(input: List<String>): Int { var remaining=input var oxygenDigits="" for (i in input.first().indices){ val zeroSum=remaining.first().indices.map { charNum -> remaining.count{it[charNum]=='0'}} remaining = remaining.filter { it[i].equals(if (zeroSum[i] <= remaining.size / 2) '1' else '0') } if(remaining.size==1) {oxygenDigits=remaining.first() ; break} } val oxygenRating=oxygenDigits.toInt(2) remaining=input var co2Digitis="" for (i in remaining.first().indices){ val zeroSum=remaining.first().indices.map { charNum -> remaining.count{it[charNum]=='0'}} remaining = remaining.filter { it[i].equals(if (zeroSum[i] <= remaining.size / 2) '0' else '1') } if(remaining.size==1) {co2Digitis=remaining.first() ; break} } val co2Rating=co2Digitis.toInt(2) return oxygenRating*co2Rating } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 198) check(part2(testInput) == 230) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
836ff780252317ee28b289742396c74559dd2b6e
1,871
advent-of-code-2021
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/FindMin.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 154. 寻找旋转排序数组中的最小值 II * * 已知一个长度为 n 的数组,预先按照升序排列,经由 1 到 n 次 旋转 后,得到输入数组。例如,原数组 nums = [0,1,4,4,5,6,7] 在变化后可能得到: * 若旋转 4 次,则可以得到 [4,5,6,7,0,1,4] * 若旋转 7 次,则可以得到 [0,1,4,4,5,6,7] * 注意,数组 [a[0], a[1], a[2], ..., a[n-1]] 旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], ..., a[n-2]] 。 * * 给你一个可能存在 重复 元素值的数组 nums ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的 最小元素 。 * */ class FindMin { companion object { @JvmStatic fun main(args: Array<String>) { println(FindMin().findMin(intArrayOf(1, 3, 5))) println(FindMin().findMin(intArrayOf(2, 2, 2, 0, 1))) println(FindMin().findMin(intArrayOf(4, 5, 6, 7, 0, 1, 4))) println(FindMin().findMin(intArrayOf(1, 0, 1, 1, 1))) } } // 6,7,0,1,4,4,5 fun findMin(nums: IntArray): Int { var start = 0 var end = nums.size - 1 var min = nums[start] var mid: Int while (start <= end) { mid = start + (end - start).shr(1) when { nums[start] == nums[mid] -> { min = Math.min(nums[start], min) start++ } nums[start] < nums[mid] -> { min = Math.min(nums[start], min) start = mid + 1 } else -> { min = Math.min(nums[mid], min) end = mid - 1 } } } return min } fun findMin2(nums: IntArray): Int { var low = 0 var high = nums.size - 1 while (low < high) { val pivot = low + (high - low).shr(1) when { nums[pivot] < nums[high] -> high = pivot nums[pivot] > nums[high] -> low = pivot + 1 else -> high -= 1 } } return nums[low] } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,255
daily_algorithm
Apache License 2.0
src/Day03.kt
allisonjoycarter
574,207,005
false
{"Kotlin": 22303}
fun main() { fun part1(input: List<String>): Int { val shared = arrayListOf<Char>() input.forEach { line -> val firstCompartmentItems = line.take(line.length / 2) val secondCompartmentItems = line.takeLast(line.length / 2) val commonItem = firstCompartmentItems.asIterable().intersect(secondCompartmentItems.toSet()) shared.add(commonItem.first()) } return shared.sumOf { character -> if (character.isLowerCase()) { character.code - 96 } else { character.code - 64 + 26 } } } fun part2(input: List<String>): Int { val badges = arrayListOf<Char>() for (i in input.indices step 3) { val commonItem = input[i].asIterable() .intersect(input[i + 1].toSet()) .intersect(input[i + 2].toSet()) badges.add(commonItem.first()) } return badges.sumOf { character -> if (character.isLowerCase()) { character.code - 96 } else { character.code - 64 + 26 } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println("Part 1:") println(part1(input)) println("Part 2:") println(part2(input)) }
0
Kotlin
0
0
86306ee6f4e90c1cab7c2743eb437fa86d4238e5
1,517
adventofcode2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Day02.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day02(input: List<String>) { private data class Game(val id: Int, val colorSets: List<Colors>) { fun isPossible(colors: Colors) = colorSets.all { it.red <= colors.red && it.green <= colors.green && it.blue <= colors.blue } fun fewestColors() = Colors(colorSets.maxOf { it.red }, colorSets.maxOf { it.green }, colorSets.maxOf { it.blue }) companion object { fun fromString(str: String): Game { val (id, colors) = str.substring(5).split(": ") val colorSets = colors.split("; ").map { Colors.fromString(it) } return Game(id.toInt(), colorSets) } } } private data class Colors(var red: Int, var green: Int, var blue: Int) { companion object { fun fromString(colorSet: String): Colors { val result = Colors(0, 0, 0) colorSet.split(", ").map { val (count, color) = it.split(" ") when (color) { "red" -> result.red = count.toInt() "green" -> result.green = count.toInt() "blue" -> result.blue = count.toInt() } } return result } } } private val games = input.map { Game.fromString(it) } fun solvePart1() = games.filter { it.isPossible(Colors(12, 13, 14)) }.sumOf { it.id } fun solvePart2() = games.map { it.fewestColors() }.sumOf { it.red * it.green * it.blue } }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
1,570
advent-2023
MIT License
src/Day02.kt
Shykial
572,927,053
false
{"Kotlin": 29698}
fun main() { fun part1(input: List<String>): Int = input .map { it.cutExcluding(" ") } .sumOf { calculateScore(Shape.forLetter(it.first), Shape.forLetter(it.second)) } fun part2(input: List<String>) = input .map { it.cutExcluding(" ") } .map { Shape.forLetter(it.first) to ExpectedResult.forLetter(it.second) } .sumOf { calculateScore(it.first, it.first.getShapeForResult(it.second)) } val input = readInput("Day02") println(part1(input)) println(part2(input)) } private fun calculateScore(opponentShape: Shape, yourShape: Shape) = yourShape.score + yourShape.scoreAgainst(opponentShape) private enum class ExpectedResult(val letter: String) { LOSE("X"), DRAW("Y"), WIN("Z"); companion object { private val lettersMap = values().associateBy { it.letter } fun forLetter(letter: String) = lettersMap[letter] ?: error("Invalid letter passed") } } private enum class Shape( val letters: List<String>, val score: Int, ) { ROCK(listOf("A", "X"), 1), PAPER(listOf("B", "Y"), 2), SCISSORS(listOf("C", "Z"), 3); fun scoreAgainst(other: Shape) = when { this == other -> 3 (this.score - other.score).mod(3) == 1 -> 6 else -> 0 } fun getShapeForResult(expectedResult: ExpectedResult) = when (expectedResult) { ExpectedResult.LOSE -> forScore((this.score - 1).takeUnless { it == 0 } ?: 3) ExpectedResult.DRAW -> this ExpectedResult.WIN -> forScore(this.score % 3 + 1) } companion object { private val lettersMap = values() .flatMap { it.letters.map { letter -> letter to it } } .toMap() private val scoresMap = values().associateBy { it.score } fun forLetter(letter: String) = lettersMap[letter] ?: error("Invalid letter passed") fun forScore(score: Int) = scoresMap[score] ?: error("Invalid score passed") } }
0
Kotlin
0
0
afa053c1753a58e2437f3fb019ad3532cb83b92e
1,952
advent-of-code-2022
Apache License 2.0
facebook/y2020/round1/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2020.round1 private fun solve(): Int { val (n, m, k, _) = readInts() val (p, q) = listOf(n, m).map { size -> readInts().toMutableList().also { list -> val (a, b, c, d) = readInts() for (i in k until size) { list.add(((a.toLong() * list[i - 2] + b.toLong() * list[i - 1] + c) % d + 1).toInt()) } }.sorted() } var (low, high) = 0 to (p[0] - q[0]).abs() + q.last() - q[0] while (low + 1 < high) { val time = (low + high) / 2 var i = 0 for (x in p) { val extraTime = (time - (x - q[i]).abs()).takeIf { it >= 0 } ?: continue val y = maxOf(q[i] + extraTime, x + extraTime / 2) while (i < m && q[i] <= y) i++ if (i == m) break } if (i == m) high = time else low = time } return high } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun Int.abs() = kotlin.math.abs(this) private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,040
competitions
The Unlicense
src/main/kotlin/day15/Solution.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day15 import java.io.File import kotlin.math.abs import kotlin.system.measureTimeMillis fun manhattanDistance(x1: Long, y1: Long, x2: Long, y2: Long) = abs(x1-x2) + abs(y1-y2) class LineScan( initStart: Long, initEnd: Long ) { val start = minOf(initStart, initEnd) val end = maxOf(initStart, initEnd) fun union(other: LineScan): List<LineScan> = if(other.start-1 > end || other.end+1 < start) listOf(this, other) else listOf(LineScan( minOf(other.start, start), maxOf(other.end, end))) fun union(others: List<LineScan>): List<LineScan> = others.fold(Pair(this, emptyList<LineScan>())) { acc, it -> val united = acc.first.union(it) Pair( united.first(), acc.second + united.drop(1) ) }.let {listOf(it.first) + it.second } } class SensorScan( val x: Long, val y: Long, private val beaconX: Long, private val beaconY: Long ) { val radius = manhattanDistance(x, y, beaconX, beaconY) fun contains(newX: Long, newY: Long) = manhattanDistance(x, y, newX, newY) <= radius fun hasBeacon(newX: Long, newY: Long) = newX == beaconX && newY == beaconY fun lineScanAtHeight(height: Long) = LineScan( x - (radius - abs(y-height)), x + (radius - abs(y-height)) ) } fun List<SensorScan>.findXBoundaries() = this.fold(Pair(this.first(), this.first())) { acc, scan -> Pair( scan.takeIf { it.x < acc.first.x } ?: acc.first, scan.takeIf { it.x > acc.second.x } ?: acc.second ) }.let { Pair(it.first.x - it.first.radius, it.second.x + it.second.radius) } fun List<SensorScan>.uniqueExcludedPosition(y: Long) = this.filter { abs(y-it.y) <= it.radius } .fold(emptyList<LineScan>()) { acc, it -> it.lineScanAtHeight(y).union(acc) } fun parseInputFile() = File("src/main/kotlin/day15/input.txt") .readLines() .fold(emptyList<SensorScan>()) { acc, it -> Regex("Sensor at x=(-?[0-9]+), y=(-?[0-9]+): closest beacon is at x=(-?[0-9]+), y=(-?[0-9]+)") .find(it)!! .let{ acc + SensorScan( it.groupValues[1].toLong(), it.groupValues[2].toLong(), it.groupValues[3].toLong(), it.groupValues[4].toLong() ) } } fun findBeaconFreePoints(row: Long) = parseInputFile() .let { scans -> val boundaries = scans.findXBoundaries() (boundaries.first .. boundaries.second).fold(0) { acc, it -> if ( scans.any{ scan -> scan.contains(it, row) } && scans.all { scan -> !scan.hasBeacon(it, row) }) acc + 1 else acc } } fun findBeacon(range: Long) = parseInputFile() .let {scans -> (0L .. range).fold(emptyList<Long>()) { acc, y -> val lineScan = scans.uniqueExcludedPosition(y) if(lineScan.size == 1 && lineScan.first().start <= 0L && lineScan.first().end >= range ) acc else if(lineScan.size == 1 && lineScan.first().start > 0L) acc + listOf(y + lineScan.first().start*4000000L) else if(lineScan.size == 1 && lineScan.first().end < range) acc + listOf(y + lineScan.first().end*4000000L) else acc + listOf(y + (lineScan.minBy { it.end }.end+1)*4000000L) } } fun main() { measureTimeMillis { println("In the row where y=2000000, the positions cannot contain a beacon are: ${findBeaconFreePoints(10)}") val beacons = findBeacon(4000000L) if (beacons.size > 1) println("I did not find any beacon") else println("The beacon tuning frequency is: ${beacons.first()}") }.let { println("The whole process took: $it milliseconds") } }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
3,975
advent-of-code-2022
MIT License
src/main/kotlin/aoc2017/FractalArt.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.nonEmptyLines fun fractalArt(input: String, iterations: Int): Int { val rules = RuleBook.parse(input) var block = Block(listOf(".#.", "..#", "###")) repeat(iterations) { block = block.enhance(rules) } return block.pixelsOnCount } private class RuleBook(private val rules: List<Rule>) { fun findReplacement(fingerprint: Fingerprint) = rules.find { it.matches(fingerprint) }?.output ?: error("no matching rule for $fingerprint") companion object { fun parse(input: String) = RuleBook(input.nonEmptyLines().map(Rule.Companion::parse)) } } private class Block private constructor(val size: Int) { private val grid = Array(size) { CharArray(size) } constructor(lines: List<String>) : this(lines.size) { lines.forEachIndexed { y, s -> s.forEachIndexed { x, c -> grid[y][x] = c } } } val pixelsOnCount: Int get() = grid.sumBy { r -> r.count { it == '#' } } override fun toString() = buildString { for (line in grid) appendLine(String(line)) } fun enhance(rules: RuleBook) = when { size % 2 == 0 -> enhance(rules, 2, 3) size % 3 == 0 -> enhance(rules, 3, 4) else -> error("invalid size $size") } private fun enhance(rules: RuleBook, mod: Int, newMod: Int): Block { val parts = size / mod val enhanced = Block(parts * newMod) for (y in 0 until parts) { for (x in 0 until parts) { val fingerprint = fingerprint(x * mod, y * mod, mod) val replacement = rules.findReplacement(fingerprint) enhanced.copyFrom(x * newMod, y * newMod, replacement) } } return enhanced } private fun fingerprint(x: Int, y: Int, size: Int) = buildString { for (yy in y until y + size) for (xx in x until x + size) append(grid[yy][xx]) } private fun copyFrom(x: Int, y: Int, block: Block) { for (yy in 0 until block.size) for (xx in 0 until block.size) { val v = block.grid[yy][xx] grid[yy + y][xx + x] = v } } } private typealias Fingerprint = String private class Rule(permutationIndices: List<List<Int>>, private val pattern: String, val output: Block) { private val permutations = permutationIndices.map { indices -> indices.map { pattern[it] }.joinToString("") }.toSet() fun matches(fingerprint: Fingerprint) = fingerprint in permutations companion object { private val permutations2x2 = digitLists("0123", "2031", "2310", "1203", "1032", "2301", "3210") private val permutations3x3 = run { val rots = digitLists("012345678", "630741852", "876543210", "258147036") val flips = digitLists("012345678", "210543876", "678345012", "876543210") rots.flatMap { rot -> flips.map { flip -> rot.map { flip[it] } } } } private val regex = Regex("(.+) => (.+)") fun parse(input: String): Rule { val m = regex.matchEntire(input) ?: error("invalid input '$input'") val pattern = m.groupValues[1].split('/').joinToString("") val replacement = Block(m.groupValues[2].split('/')) return when (pattern.length) { 4 -> Rule(permutations2x2, pattern, replacement) 9 -> Rule(permutations3x3, pattern, replacement) else -> error("invalid pattern '$pattern'") } } private fun digitLists(vararg s: String): List<List<Int>> = s.map { r -> r.map { it.toInt() - '0'.toInt() } } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
3,809
advent-of-code
MIT License
src/Day03.kt
iartemiev
573,038,071
false
{"Kotlin": 21075}
const val UpperNormalize = 38 const val LowerNormalize = 96 fun main() { fun findCommonChar(input1: String, input2: String): Char { val charSet: Set<Char> = input1.toCharArray().toSet() return input2.find { charSet.contains(it) } ?: throw IllegalStateException("Invalid State") } fun findCommonChar(input1: String, input2: String, input3: String): Char { val charSet: Set<Char> = input1.toCharArray().toSet() val commonSet = input2.toCharArray().filter { charSet.contains(it) }.toSet() return input3.find { commonSet.contains(it) } ?: throw IllegalStateException("Invalid State") } fun charToPriority(char: Char): Int { val normalize: Int = if (char.isUpperCase()) UpperNormalize else LowerNormalize return char.code - normalize } fun part1(input: List<String>): Int { return input.sumOf { line -> val subStr1 = line.substring(0, line.length/2) val subStr2 = line.substring(line.length/2) val commonChar = findCommonChar(subStr1, subStr2) charToPriority(commonChar) } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { (subStr1, subStr2, subStr3) -> val commonChar = findCommonChar(subStr1, subStr2, subStr3) charToPriority(commonChar) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d2b7a974c2736903a9def65282be91fbb104ffd
1,535
advent-of-code
Apache License 2.0
src/Day02.kt
rmyhal
573,210,876
false
{"Kotlin": 17741}
import java.util.stream.Collectors import kotlin.IllegalArgumentException fun main() { fun part1(input: List<String>): Long { return regularGame(input) } fun part2(input: List<String>): Long { return strategyGame(input) } val input = readInput("Day02") println(part1(input)) println(part2(input)) } private enum class Shape { ROCK, PAPER, SCISSORS; } private fun String.toShape(): Shape = when (this) { "A", "X" -> Shape.ROCK "B", "Y" -> Shape.PAPER "C", "Z" -> Shape.SCISSORS else -> throw IllegalArgumentException("unknown shape $this") } private const val losePoints = 0 private const val drawPoints = 3 private const val winPoints = 6 private val shapePoints = mapOf(Shape.ROCK to 1, Shape.PAPER to 2, Shape.SCISSORS to 3) // key = shape, value = a set of shapes which will lose to key private val rulesMap = mapOf( Shape.ROCK to setOf(Shape.SCISSORS), Shape.PAPER to setOf(Shape.ROCK), Shape.SCISSORS to setOf(Shape.PAPER), ) private fun regularGame(input: List<String>): Long { var totalScore = 0L input.forEach { guide -> val (opponent, me) = guide.split(" ").map { it.toShape() } val result = when { opponent == me -> drawPoints rulesMap.getValue(me).contains(opponent) -> winPoints else -> losePoints } totalScore += result + shapePoints.getValue(me) } return totalScore } private fun strategyGame(input: List<String>): Long { var totalScore = 0L input .map { it.split(" ") } .forEach { guide -> val opponent = guide[0].toShape() val strategy = guide[1].toStrategy() val shape = when (strategy) { Strategy.DRAW -> opponent Strategy.WIN -> getWinShapeFor(`for` = opponent) Strategy.LOSE -> rulesMap.getValue(opponent).first() } totalScore += strategy.toPoints() + shapePoints.getValue(shape) } return totalScore } private fun getWinShapeFor(`for`: Shape): Shape { return rulesMap.entries .stream() .filter { entry -> entry.value.contains(`for`) } .map { it.key } .collect(Collectors.toSet()) .first() } enum class Strategy { LOSE, DRAW, WIN; } private fun String.toStrategy(): Strategy = when (this) { "X" -> Strategy.LOSE "Y" -> Strategy.DRAW "Z" -> Strategy.WIN else -> throw IllegalArgumentException("unknown strategy $this") } private fun Strategy.toPoints() = when (this) { Strategy.LOSE -> losePoints Strategy.DRAW -> drawPoints Strategy.WIN -> winPoints }
0
Kotlin
0
0
e08b65e632ace32b494716c7908ad4a0f5c6d7ef
2,483
AoC22
Apache License 2.0
src/day5/Day.kt
helbaroudy
573,339,882
false
null
package day5 import readInput fun parseInput(input: List<String>): Pair<MutableList<String>, MutableList<Movement>> { val instructions = mutableListOf<Movement>() val stacks = MutableList((input[0].length + 1) / 4) { "" } for (entry in input) { if (entry.isNotEmpty() && !entry.startsWith("move")) { parseStacks(entry, stacks) } else if (entry.isNotEmpty()) { instructions.add(entry.parseMovement()) } } return Pair(stacks, instructions) } private fun parseStacks(entry: String, stacks: MutableList<String>) { for ((current, i) in (1..entry.length step 4).withIndex()) { if (entry[i] != ' ' && !entry[i].isDigit()) { stacks[current] = stacks[current] + entry[i] } } } fun main() { fun moveOne(stacks: MutableList<String>, fromIndex: Int, toIndex: Int) { if (stacks[fromIndex].isNotEmpty()) { stacks[toIndex] = stacks[fromIndex][0] + stacks[toIndex] stacks[fromIndex] = stacks[fromIndex].removeRange(0, 1) } } fun moveMultiple( stacks: MutableList<String>, quantity: Int, toIndex: Int, fromIndex: Int, ) { stacks[toIndex] = stacks[fromIndex].substring(0, quantity) + stacks[toIndex] stacks[fromIndex] = stacks[fromIndex].removeRange(0, quantity) } fun applyInstructions( stacks: MutableList<String>, instructions: List<Movement>, batched: Boolean, ) { for (instruction in instructions) { val fromIndex = instruction.from - 1 val toIndex = instruction.to - 1 if (batched) { moveMultiple(stacks, instruction.quantity, toIndex, fromIndex) } else { for (i in 0.until(instruction.quantity)) { moveOne(stacks, fromIndex, toIndex) } } } } fun part1(input: List<String>): String { val (stacks, instructions) = parseInput(input) applyInstructions(stacks, instructions, false) return stacks.fold("") { result, stack -> result + stack[0] } } fun part2(input: List<String>): String { val (stacks, instructions) = parseInput(input) applyInstructions(stacks, instructions, true) return stacks.fold("") { result, stack -> result + stack[0] } } val testInput = readInput("Day05_test") part1(testInput) check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") //part1(input) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") check(part1(input) == "SPFMVDTZT") check(part2(input) == "ZFSJBPRFP") } data class Movement(val quantity: Int, val from: Int, val to: Int) fun String.parseMovement(): Movement { if (!startsWith("move")) error("Invalid movement") val split = this.split("move ", " from ", " to ") return Movement(split[1].toInt(), split[2].toInt(), split[3].toInt()) }
0
Kotlin
0
0
e9b98fc0eda739048e68f4e5472068d76ee50e89
3,042
aoc22
Apache License 2.0
src/Day04.kt
mkfsn
573,042,358
false
{"Kotlin": 29625}
fun main() { fun IntRange.covers(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last fun IntRange.overlaps(other: IntRange): Boolean = other.contains(this.first) || other.contains(this.last) fun pairToRange(pair: String): IntRange { val (x, y) = pair.split("-").map { it.toInt() } return IntRange(x, y) } fun toRangePair(section: String): List<IntRange> = section.split(",").map { pairToRange(it) } fun part1(input: List<String>): Int { return input .map { toRangePair(it) } .map { it[0].covers(it[1]) || it[1].covers(it[0]) } .count { it } } fun part2(input: List<String>): Int { return input .map { toRangePair(it) } .map { it[0].overlaps(it[1]) || it[1].overlaps(it[0]) } .count { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
8c7bdd66f8550a82030127aa36c2a6a4262592cd
1,163
advent-of-code-kotlin-2022
Apache License 2.0
src/Day10.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
sealed class Instruction(val cycles: Int, val operation: (previousX: Int) -> Int) { class NoOp : Instruction(1, { it }) class AddX(private val amount: Int) : Instruction(2, { it + amount }) companion object { fun parse(line: String) = when { line == "noop" -> NoOp() line.startsWith("addx") -> AddX(line.substringAfter(" ").toInt()) else -> throw IllegalArgumentException() } } } class CPU { val history: MutableList<Int> = mutableListOf(1) private val x: Int get() = history.last() private fun tick(value: Int = x) = history.add(value) fun execute(program: List<Instruction>) = program.forEach { instruction -> repeat(instruction.cycles - 1) { tick() } tick(instruction.operation(x)) } } class Sprite(width: Int, position: Int) { private val reach = (width - 1) / 2 val occupiedPixels: IntRange = (position - reach)..(position + reach) } class CRT(private val width: Int, height: Int) { private val pixels: MutableList<Boolean> = MutableList((width * height) + 1) { false } fun tick(cycle: Int, sprite: Sprite) { val renderingAt = cycle.rem(width) pixels[cycle] = renderingAt in sprite.occupiedPixels } fun render(on: String = "#", off: String = ".") = pixels.joinToString("") { if (it) on else off }.chunked(40).forEach(::println) } fun main() { fun part1(instructions: List<String>): Int { val cpu = CPU().apply { execute(instructions.map(Instruction::parse)) } return listOf(20, 60, 100, 140, 180, 220).sumOf { cpu.history[it - 1] * it } } fun part2(instructions: List<String>) { val crt = CRT(40, 6) CPU() .apply { execute(instructions.map(Instruction::parse)) } .history .forEachIndexed { cycle, x -> crt.tick(cycle, Sprite(3, x)) } crt.render() } val testInput = readInput("Day10_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
2,131
advent-of-code-in-kotlin-2022
Apache License 2.0
src/Day02.kt
kedvinas
572,850,757
false
{"Kotlin": 15366}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val (a, b) = it.split(" ") val score: Int = when (a) { "A" -> when (b) { "X" -> 1 + 3 "Y" -> 2 + 6 else -> 3 + 0 } "B" -> when (b) { "X" -> 1 + 0 "Y" -> 2 + 3 else -> 3 + 6 } else -> when (b) { "X" -> 1 + 6 "Y" -> 2 + 0 else -> 3 + 3 } } return@sumOf score } } fun part2(input: List<String>): Int { return input.sumOf { val (a, b) = it.split(" ") val score: Int = when (a) { "A" -> when (b) { "X" -> 3 + 0 "Y" -> 1 + 3 else -> 2 + 6 } "B" -> when (b) { "X" -> 1 + 0 "Y" -> 2 + 3 else -> 3 + 6 } else -> when (b) { "X" -> 2 + 0 "Y" -> 3 + 3 else -> 1 + 6 } } return@sumOf score } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
04437e66eef8cf9388fd1aaea3c442dcb02ddb9e
1,561
adventofcode2022
Apache License 2.0
src/Day18.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { data class Point(val x: Long, val y: Long) fun solve(dirs: List<Pair<Char, Long>>): Long { var perimeter = 0L val points = run { val res = ArrayDeque<Point>() res.add(Point(0,0)) for (dir in dirs) { val cur = res.last() val (d, l) = dir perimeter += l when (d) { 'R', '0' -> res.add(cur.copy(x = cur.x + l)) 'D', '1' -> res.add(cur.copy(y = cur.y + l)) 'L', '2' -> res.add(cur.copy(x = cur.x - l)) 'U', '3' -> res.add(cur.copy(y = cur.y - l)) else -> error(d) } } res.dropLast(1) res } val n = points.size val res = points.indices.sumOf { i -> points[i].x * points[(i+1)%n].y - points[(i+1)%n].x * points[i].y } return res/2 + perimeter/2 + 1 } val input = readInput("Day18") println(solve(input.map { line -> line.split(" ").let { it[0][0] to it[1].toLong() } })) println(solve(input.map { line -> val code = line.substringAfter('#').substringBefore(')') val l = code.substring(0, 5).toLong(16) code[5] to l })) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,312
advent-of-code-kotlin
Apache License 2.0
archive/2022/Day08.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.streams.toList private const val EXPECTED_1 = 21 private const val EXPECTED_2 = 8 private inline fun <T> List<List<Int>>.map (action: (Int, Int, Int) -> T): List<T> { val result = mutableListOf<T>() for ((y, row) in this.withIndex()) { for ((x, value) in row.withIndex()) { result.add(action(x, y, value)) } } return result } private class Day08(isTest: Boolean) : Solver(isTest) { fun heightMap() = readAsLines().map { line -> line.map { it - '0' } } val dirs = arrayOf( -1 to 0, 1 to 0, 0 to -1, 0 to 1 ) fun part1(): Any { val heights = heightMap() return heights.map { startX, startY, height -> for (dir in dirs) { var x = startX var y = startY while (true) { y += dir.first x += dir.second if (y < 0 || y >= heights.size || x < 0 || x >= heights[y].size) { return@map 1 } else if (heights[y][x] >= height) { break } } } return@map 0 }.sum() } fun part2(): Any { val heights = heightMap() return heights.map { startX, startY, height -> var result = 1 for (dir in dirs) { if (result == 0) break var x = startX var y = startY var viewScore = 0 while (true) { y += dir.first x += dir.second if (y < 0 || y >= heights.size || x < 0 || x >= heights[y].size) { break } viewScore++ if (heights[y][x] >= height) { break } } result *= viewScore } result }.max() } } fun main() { val testInstance = Day08(true) val instance = Day08(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println(instance.part1()) testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } } println(instance.part2()) }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
2,368
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc23/Day15.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 object Day15 { data class Lens(val label: String, val focalLength: Int) sealed class Operator(open val name: String) { val box: Int get() = hash(name) data class Dash(override val name: String) : Operator(name) data class Equal(override val name: String, val lens: Lens) : Operator(name) } fun calculateHashSum(input: String): Int { val steps = input.trim().split(',') val hashes = steps.map { hash(it) } return hashes.sum() } fun calculateFocusingPower(input: String): Int { val ops = parseInput(input) val boxes: Map<Int, List<Lens>> = emptyMap() val placement = ops.fold(boxes) { acc, op -> when (op) { is Operator.Dash -> { val newBox = acc[op.box]?.filter { it.label != op.name } if (newBox == null) acc else acc + (op.box to newBox) } is Operator.Equal -> { val box = acc.getOrDefault(op.box, emptyList()) val newBox = if (op.lens.label in box.map { it.label }) { box.map { if (it.label == op.lens.label) op.lens else it } } else { box + op.lens } acc + (op.box to newBox) } } } val focusingPowers = placement.map { (box, lenses) -> lenses.mapIndexed { idx, lens -> val boxFactor = box + 1 val slotFactor = idx + 1 boxFactor * slotFactor * lens.focalLength }.sum() } return focusingPowers.sum() } private fun hash(input: String): Int = input .fold(0) { acc, c -> val ascii = c.code val newValue = (acc + ascii) * 17 newValue % 256 } private fun parseInput(input: String): List<Operator> { val steps = input.trim().split(',') return steps.map { step -> if ('-' in step) { Operator.Dash(step.substringBefore('-')) } else { val label = step.substringBefore('=') val focalLength = step.substringAfter('=').toInt() Operator.Equal(label, Lens(label, focalLength)) } } } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
2,375
advent-of-code-23
Apache License 2.0
src/Day02.kt
achugr
573,234,224
false
null
fun main() { fun part1(input: List<String>): Int { return input.map { it.split(" ").map { str -> when (str) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> throw IllegalArgumentException("Unsupported bet") } } }.map { Pair(it[1], (it[1] - it[0] + 3) % 3) }.map { it.first + when (it.second) { 0 -> 3 1 -> 6 2 -> 0 else -> throw IllegalArgumentException("Unsupported round outcome") } }.sumOf { it } } fun part2(input: List<String>): Int { return input.map { it.split(" ").map { str -> when (str) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> throw IllegalArgumentException("Unsupported bet") } } }.map { val usersBet = when (it[1]) { 1 -> (it[0] + 1) % 3 + 1 2 -> it[0] 3 -> it[0] % 3 + 1 else -> throw IllegalArgumentException("Unsupported round outcome") } Pair(it[0], usersBet) }.map { Pair(it.second, (it.second - it.first + 3) % 3) }.map { it.first + when (it.second) { 0 -> 3 1 -> 6 2 -> 0 else -> throw IllegalArgumentException("Unsupported round outcome") } }.sumOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
d91bda244d7025488bff9fc51ca2653eb6a467ee
1,792
advent-of-code-kotlin-2022
Apache License 2.0
day6/src/main/kotlin/com/lillicoder/adventofcode2023/day6/Day6.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day6 fun main() { val day6 = Day6() val races = RaceParser().parseFile("input.txt") println("Total possible winning permutations is ${day6.part1(races)}.") println("Total possible winning permutations as one race is ${day6.part2(races)}.") } class Day6 { fun part1(races: List<Race>) = RecordSetterCalculator().countWaysToSetRecords(races).toLong() fun part2(races: List<Race>): Long { val time = races.joinToString("") { it.duration.toString() } val distance = races.joinToString("") { it.bestDistance.toString() } val asOneRace = Race(time.toLong(), distance.toLong()) return RecordSetterCalculator().countWaysToSetRecord(asOneRace).toLong() } } /** * Represents a race record. * @param duration Duration of a race in milliseconds. * @param bestDistance Best distance ran in this race. */ data class Race( val duration: Long, val bestDistance: Long, ) class RaceParser { /** * Parses the given raw race input to an equivalent list of [Race]. * @param raw Raw races input. * @param separator Line separator for the given input. * @return Races. */ fun parse( raw: String, separator: String = System.lineSeparator(), ): List<Race> { val sections = raw.split(separator) val times = sections[0].substringAfter(":").split(" ").filter { it.isNotEmpty() }.map { it.toLong() } val distances = sections[1].substringAfter(":").split(" ").filter { it.isNotEmpty() }.map { it.toLong() } return times.zip(distances).map { Race(it.first, it.second) } } /** * Parses the file for the given filename to an equivalent list of [Race]. * @param filename Filename. * @return Races. */ fun parseFile(filename: String) = parse(javaClass.classLoader.getResourceAsStream(filename)!!.reader().readText()) } /** * Determines possible ways of beating a record distance for a given [Race]. */ class RecordSetterCalculator { /** * Determines the count of possible permutations that would result in a new * distance record being set for the given [Race]. * @param race Race to evaluate. * @return Count of permutations that result in a new distance record. */ fun countWaysToSetRecord(race: Race) = LongRange(0, race.duration).count { speed -> /** * A race is split into two phases: * * 1) Pressing a toy boat's button to charge it * 2) Boat traveling after releasing the charge button * * You can depress the charge button for 0 to N milliseconds, where N is the race duration. * Boat speed is M millimeters/millisecond, where M is how long the button was pressed. * * We will only consider whole integer values, no fractions. * * Naive solution: for each possible value of N, determine how far we go for the remaining * time at speed M. If that distance is greater than the record, we have found a * desired outcome. */ val remainingTime = race.duration - speed val distance = speed * remainingTime distance > race.bestDistance } /** * Determines the total possible permutations that would result in a new distance * record being set for the given list of [Race]. * @param races Races to evaluate. * @return Count of permutations that result in a new distance record across all races. */ fun countWaysToSetRecords(races: List<Race>) = races.map { countWaysToSetRecord(it) }.reduce { accumulator, count -> accumulator * count } }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
3,802
advent-of-code-2023
Apache License 2.0
src/Day07.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import java.util.* data class Directory(var totalSize: Long = 0, val children: MutableMap<String, Directory> = mutableMapOf()) fun buildFolder(commands: List<String>): Map<String, Long> { val root = Directory() val path = Stack<Directory>() var currentDirectory = root for (line in commands) { val tokens = line.split(" ") when (tokens[0]) { // $ cd <path> or $ ls "$" -> { if (tokens[1] == "cd") { currentDirectory = when(tokens[2]) { ".." -> path.pop() // go back one folder up "/" -> root // go back all the way up else -> { path.push(currentDirectory) // store current folder to go back later currentDirectory.children[tokens[2]]!! // move to specified folder } } } else { // ls command. Not doing anything since we'll handle the outputs on the next loop } } // output of ls "dir" -> currentDirectory.children[tokens[1]] = Directory() // dir <dir_name> else -> currentDirectory.totalSize += tokens[0].toLong() // <file_size> <file_name> } } return calculateSize(root) } fun calculateSize(root: Directory, path: String = "", cache: MutableMap<String, Long> = mutableMapOf()): Map<String, Long> { root.children.forEach { calculateSize(it.value, "$path/${it.key}", cache)} cache[path] = root.totalSize + root.children.map { cache["$path/${it.key}"]!! }.sum() return cache } fun main() { fun part1(input: List<String>): Long { val folders = buildFolder(input) return folders.filter { (_, v) -> v <= 100_000 }.values.sum() } fun part2(input: List<String>): Long { val folders = buildFolder(input) val rootSize = folders[""]!! return folders.filter { (_, v) -> v > rootSize - 40_000_000L }.values.minOf { it } } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
2,200
Advent-Of-Code-2022
Apache License 2.0
src/Day03.kt
sk0g
572,854,602
false
{"Kotlin": 7597}
fun findCommonItem(s: String): Char { val (firstHalf, secondHalf) = s.chunked(s.length / 2) return firstHalf.toHashSet() .intersect(secondHalf.toHashSet()) .first() } fun Char.getPriority(): Int = if (this.isUpperCase()) { this.code + 27 - 'A'.code } else { this.code + 1 - 'a'.code } fun getCommonItemAndPriority(items: List<String>): Pair<Char, Int> { assert(items.size == 3) val (s1, s2, s3) = items val commonCharacter = s1.toHashSet() .intersect(s2.toHashSet()) .intersect(s3.toHashSet()) .first() return commonCharacter to commonCharacter.getPriority() } fun main() { fun part1Assertions() { assert(findCommonItem("vJrwpWtwJgWrhcsFMMfFFhFp") == 'p') assert(findCommonItem("jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL") == 'L') assert(findCommonItem("PmmdzqPrVvPwwTWBwg") == 'P') assert(findCommonItem("wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn") == 'v') assert(findCommonItem("ttgJtRGJQctTZtZT") == 't') assert(findCommonItem("CrZsJsPPZsGzwwsLwLmpwMDw") == 's') } fun part2Assertions() { assert( getCommonItemAndPriority( listOf( "vJrwpWtwJgWrhcsFMMfFFhFp", "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL", "PmmdzqPrVvPwwTWBwg", ), ) == 'r' to 18, ) assert( getCommonItemAndPriority( listOf( "wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn", "ttgJtRGJQctTZtZT", "CrZsJsPPZsGzwwsLwLmpwMDw", ), ) == 'Z' to 52, ) } val input = readInput("Day03") part1Assertions() val part1Value = input.sumOf { findCommonItem(it).getPriority() } println("Part 1: $part1Value") part2Assertions() val part2Value = input .chunked(3) .map { getCommonItemAndPriority(it) } .sumOf { it.second } println("Part 2: $part2Value") }
0
Kotlin
0
0
cd7e0da85f71d40bc7e3761f16ecfdce8164dae6
2,040
advent-of-code-22
Apache License 2.0
src/Day04.kt
qmchenry
572,682,663
false
{"Kotlin": 22260}
fun main() { fun rangeToSet(range: String): Set<Int> { val (from, to) = range.split("-").map { it.toInt() } return (from..to).toSet() } fun rangePairs(pair: String): Pair<Set<Int>, Set<Int>> { val (left, right) = pair.split(",") return Pair(rangeToSet(left), rangeToSet(right)) } fun isOneFullyOverlapped(left: Set<Int>, right: Set<Int>): Boolean { return left.containsAll(right) || right.containsAll(left) } fun arePartiallyOverlapped(left: Set<Int>, right: Set<Int>): Boolean { return left.intersect(right).isNotEmpty() } fun part1(input: List<String>): Int { return input .map { rangePairs(it) } .count { (left, right) -> isOneFullyOverlapped(left, right) } } fun part2(input: List<String>): Int { return input .map { rangePairs(it) } .count { (left, right) -> arePartiallyOverlapped(left, right) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_sample") check(part1(testInput) == 2) check(part2(testInput) == 4) val realInput = readInput("Day04_input") println("Part 1: ${part1(realInput)}") println("Part 2: ${part2(realInput)}") }
0
Kotlin
0
0
2813db929801bcb117445d8c72398e4424706241
1,290
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/days/day2/Day2.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day2 import days.Day class Day2: Day(false) { override fun partOne(): Any { val games = readInput().map{ val id = it.substringBefore(":").substringAfter(" ").toInt() val values = it.substringAfter(": ").replace(";",",").split(", ").map{ it -> val color = it.substringAfter(" ").toLowerCase() val value = it.substringBefore(" ").toInt() ColorValue(color, value) } Game(id, values) } val validGames = games.filter { game -> game.value.all { color -> (color.color != "red" || color.value <= 12) && (color.color != "green" || color.value <= 13) && (color.color != "blue" || color.value <= 14) } } return validGames.sumOf { it.id } } override fun partTwo(): Any { val games = readInput().map{ val id = it.substringBefore(":").substringAfter(" ").toInt() val values = it.substringAfter(": ").replace(";",",").split(", ").map{ it -> val color = it.substringAfter(" ").toLowerCase() val value = it.substringBefore(" ").toInt() ColorValue(color, value) } Game(id, values) } val map: MutableMap<Game, ArrayList<ColorValue>> = mutableMapOf() for (game in games) { map[game] = arrayListOf() map[game]?.add(ColorValue("red",game.value.filter { it.color == "red" }.map { it.value }.max())) map[game]?.add(ColorValue("green",game.value.filter { it.color == "green" }.map { it.value }.max())) map[game]?.add(ColorValue("blue",game.value.filter { it.color == "blue" }.map { it.value }.max())) } return map.map { it.value.map { it.value }.reduce{ acc, i -> acc * i } }.sum() } } class Game(val id:Int, val value:List<ColorValue>){ override fun toString(): String { return "Game(id=$id, value=$value)" } } class ColorValue(val color:String, val value:Int){ override fun toString(): String { return "ColorValue(color='$color', value=$value)" } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
2,202
advent-of-code_2023
The Unlicense
src/year2015/day06/Day06.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day06 import readInput fun main() { val input = readInput("2015", "Day06") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val grid = Array(1000) { Array(1000) { false } } input.executeActionsOnGrid(grid) { action, value -> when (action) { Action.Toggle -> !value Action.TurnOn -> true Action.TurnOff -> false } } return grid.sumOf { row -> row.count { it } } } private fun part2(input: List<String>): Int { val grid = Array(1000) { Array(1000) { 0 } } input.executeActionsOnGrid(grid) { action, value -> (value + when (action) { Action.Toggle -> 2 Action.TurnOn -> 1 Action.TurnOff -> -1 }).coerceAtLeast(0) } return grid.sumOf { it.sum() } } private enum class Action { Toggle, TurnOn, TurnOff; companion object { fun of(action: String) = when (action) { "toggle" -> Toggle "turn on" -> TurnOn "turn off" -> TurnOff else -> error("action $action not supported") } } } private val pattern = "(toggle|turn off|turn on) (\\d+,\\d+) through (\\d+,\\d+)".toRegex() private fun <T> List<String>.executeActionsOnGrid(grid: Array<Array<T>>, action: (Action, T) -> T) { forEach { instruction -> val (_, action, coord1, coord2) = pattern.matchEntire(instruction)?.groupValues ?: error("Pattern not matching $instruction") val (x1, y1) = coord1.split(',').map { it.toInt() } val (x2, y2) = coord2.split(',').map { it.toInt() } for (y in y1..y2) { for (x in x1..x2) { grid[y][x] = action(Action.of(action), grid[y][x]) } } } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,809
AdventOfCode
Apache License 2.0
app/src/main/kotlin/day07/Day07.kt
W3D3
433,748,408
false
{"Kotlin": 72893}
package day07 import common.InputRepo import common.readSessionCookie import common.solve import java.util.Collections.max import java.util.Collections.min import kotlin.math.abs fun main(args: Array<String>) { val day = 7 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay07Part1, ::solveDay07Part2) } fun solveDay07Part1(input: List<String>): Int { return median(input) // return bruteforce(input) } private fun bruteforce(input: List<String>): Int { val positions = parsePositions(input) var min: Int = Int.MAX_VALUE for (position in positions) { val sumOf = positions.sumOf { abs(it - position) } if (sumOf < min) { min = sumOf; } } return min } fun median(input: List<String>): Int { val positions = parsePositions(input) var median = positions.sorted()[positions.size / 2] return positions.sumOf { abs(it - median) } } fun solveDay07Part2(input: List<String>): Int { return bruteforce2(input); } private fun bruteforce2(input: List<String>): Int { val positions = parsePositions(input).sorted() var min: Int = Int.MAX_VALUE print(positions) for (goal in min(positions)..max(positions)) { val sumOf = positions.sumOf { pos -> val sum = generateSequence(0) { if (it < abs(pos - goal)) it + 1 else null }.sum() println("$sum fuel for goal $goal from $pos") sum } println("===============================") println("Total: $sumOf") if (sumOf < min) { min = sumOf; println("NEW MIN: $sumOf") } else { // no new min in the sorted list means, we're done break } } return min } private fun parsePositions(input: List<String>) = input.map { line -> line.split(",").map(String::toInt) }.flatten()
0
Kotlin
0
0
df4f21cd99838150e703bcd0ffa4f8b5532c7b8c
1,911
AdventOfCode2021
Apache License 2.0
src/day12/Day12.kt
JoeSkedulo
573,328,678
false
{"Kotlin": 69788}
package day12 import Runner import java.util.* import kotlin.collections.HashSet fun main() { Day12Runner().solve() } class Day12Runner : Runner<Int>( day = 12, expectedPartOneTestAnswer = 31, expectedPartTwoTestAnswer = 29 ) { override fun partOne(input: List<String>, test: Boolean): Int { val squares = mapSquares(input) val end = squares.first { it.elevation == "E" } val start = squares.first { it.elevation == "S" } return search( squares = squares, start = start, end = end ) ?: throw RuntimeException() } override fun partTwo(input: List<String>, test: Boolean): Int { val squares = mapSquares(input) val end = squares.first { it.elevation == "E" } val starts = squares.filter { it.getElevationInt() == 0 } val possibleRoutes = starts.mapNotNull { start -> search( squares = squares, start = start, end = end ) } return possibleRoutes.min() } private fun mapSquares(input: List<String>) : List<MapSquare> { return input.mapIndexed { x, line -> line.mapIndexed { y, char -> MapSquare( x = x, y = y, elevation = char.toString() ) } }.flatten() } private fun search(squares: List<MapSquare>, start: MapSquare, end: MapSquare) : Int? { val queue = LinkedList<Pair<MapSquare, Int>>() val seen = HashSet<MapSquare>() queue.add(Pair(start, 0)) while (!queue.isEmpty()) { val (square, distance) = queue.remove() if (square == end) { return distance } if (!seen.contains(square)) { seen.add(square) squares.adjacentSquares(square).forEach { adjacentSquare -> if (!seen.contains(adjacentSquare)) { queue.add(Pair(adjacentSquare, distance + 1)) } } } } return null } private fun List<MapSquare>.getOrNull(x: Int, y: Int) : MapSquare? { return firstOrNull { square -> square.x == x && square.y == y } } private fun List<MapSquare>.adjacentSquares(currentSquare: MapSquare) : List<MapSquare> { return listOfNotNull( getOrNull(currentSquare.x - 1, currentSquare.y), getOrNull(currentSquare.x, currentSquare.y - 1), getOrNull(currentSquare.x, currentSquare.y + 1), getOrNull(currentSquare.x + 1, currentSquare.y), ).filter { adjacent -> currentSquare.canMoveTo(adjacent) } } private fun MapSquare.canMoveTo(other: MapSquare) : Boolean = let { current -> val currentValue = current.getElevationInt() val otherValue = other.getElevationInt() otherValue -1 <= currentValue } private fun MapSquare.getElevationInt() = let { square -> when (val elevation = square.elevation) { "S" -> 0 "E" -> 25 else -> ('a'..'z').map { it.toString() }.indexOf(elevation) } } } data class MapSquare( val x: Int, val y: Int, val elevation: String )
0
Kotlin
0
0
bd8f4058cef195804c7a057473998bf80b88b781
3,362
advent-of-code
Apache License 2.0
src/day09/day09.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day09 import util.Direction2NonDiagonal import util.Direction2NonDiagonal.* import util.Point import util.plus import util.readInput import util.shouldBe import kotlin.math.abs import kotlin.math.sign fun main() { val day = 9 val testInput = readInput(day, testInput = true).parseInput() part1(testInput) shouldBe 88 part2(testInput) shouldBe 36 val input = readInput(day).parseInput() println("output for part1: ${part1(input)}") println("output for part2: ${part2(input)}") } private data class Move( val direction: Direction2NonDiagonal, val amount: Int, ) private class Input( val moves: List<Move>, ) private fun List<String>.parseInput(): Input { val moves = map { val (d, n) = it.split(" ") Move( direction = when (d) { "R" -> Right "U" -> Up "L" -> Left "D" -> Down else -> error("unknown direction '$d'") }, amount = n.toInt() ) } return Input(moves) } private fun part1(input: Input): Int { return solve(input, 2) } private fun part2(input: Input): Int { return solve(input, 10) } private fun solve(input: Input, ropeLength: Int): Int { val positions = Array(ropeLength) { Point(0, 0) } val visitedPoints = mutableSetOf(positions.last()) for ((direction, amount) in input.moves) { repeat(amount) { positions[0] = positions[0] + direction for (i in 0..ropeLength - 2) { val a = positions[i] val b = positions[i + 1] val dx = a.x - b.x val dy = a.y - b.y if (maxOf(abs(dx), abs(dy)) > 1) { positions[i + 1] = Point(b.x + dx.sign, b.y + dy.sign) } } visitedPoints += positions.last() } } return visitedPoints.size }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
1,940
advent-of-code-2022
Apache License 2.0
src/Day03.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
fun main() { fun Char.getPriority(): Int = if (isLowerCase()) { 1 + (this - 'a') } else { 27 + (this - 'A') } data class Rucksack(val compartment1: Set<Char>, val compartment2: Set<Char>) { fun commonItem(): Char = compartment1.intersect(compartment2).single() fun allItems() = compartment1.union(compartment2) } fun String.toRucksack(): Rucksack { val n = length / 2 return Rucksack(take(n).toSet(), takeLast(n).toSet()) } fun getBadge(rucksacks: List<Rucksack>): Char { val commonItems = rucksacks.first().allItems().toMutableSet() rucksacks.drop(1).forEach { commonItems.retainAll(it.allItems()) } return commonItems.single() } fun part1(input: List<String>): Int = input.sumOf { it.toRucksack().commonItem().getPriority() } fun part2(input: List<String>): Int = input.map { it.toRucksack() }.chunked(3).sumOf { getBadge(it).getPriority() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
1,263
advent-of-code-22
Apache License 2.0
src/day12/Day12.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day12 import java.io.File fun main() { val data = parse("src/day12/Day12.txt") println("🎄 Day 12 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Row( val springs: String, val numbers: List<Int>, ) private fun String.toRow(): Row { val (springs, numbers) = this.split(" ") return Row(springs, numbers.split(",").map(String::toInt)) } private fun parse(path: String): List<Row> = File(path) .readLines() .map(String::toRow) private typealias Cache = MutableMap<Pair<String, List<Int>>, Long> private fun solve(springs: String, numbers: List<Int>, cache: Cache = mutableMapOf()): Long { if (cache.containsKey(springs to numbers)) { return cache.getValue(springs to numbers) } if (springs.isEmpty()) { return if (numbers.isEmpty()) 1L else 0L } if (numbers.isEmpty()) { return if (springs.contains('#')) 0L else 1L } var count = 0L if (springs.first() in ".?") { count += solve(springs.substring(1), numbers, cache) } if (springs.first() in "#?") { val n = numbers.first() if (springs.length > n) { val group = springs.substring(0, n) if (!group.contains('.') && springs[n] != '#') { count += solve(springs.substring(n + 1), numbers.drop(1), cache) } } if (springs.length == n) { if (!springs.contains('.')) { count += solve("", numbers.drop(1), cache) } } } cache[springs to numbers] = count return count } private fun part1(data: List<Row>): Long = data.sumOf { (springs, numbers) -> solve(springs, numbers) } private fun part2(data: List<Row>): Long = data.sumOf { (springs, numbers) -> solve( generateSequence { springs }.take(5).toList().joinToString("?"), generateSequence { numbers }.take(5).toList().flatten()) }
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
2,147
advent-of-code-2023
MIT License
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day06.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.Point class Day06 : Day(title = "Chronal Coordinates") { companion object Configuration { private const val MAX_DISTANCE_SUM = 10000 } override fun first(input: Sequence<String>): Any = input .parse() .let { (points, min, max) -> min.createGridTo(max) .mapNotNull { gridPoint -> points.findNearest(gridPoint) } .groupBy { it.second } .values .asSequence() .filter { gridPoints -> gridPoints.none { (point, _) -> point.onEdge(min, max) } } .map { it.size } .max() ?: 0 } override fun second(input: Sequence<String>): Any = input .parse() .let { (points, min, max) -> val xLimit = (MAX_DISTANCE_SUM - (max.x - min.x)) / points.size val yLimit = (MAX_DISTANCE_SUM - (max.y - min.y)) / points.size Point.of(min.x - xLimit, min.y - yLimit) .createGridTo(Point.of(max.x + xLimit, max.y + yLimit)) .count { gp -> points.sumBy { p -> p.manhattan(gp) } < MAX_DISTANCE_SUM } } private fun Sequence<String>.parse(): Triple<List<Point>, Point, Point> { var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE var minX = Int.MAX_VALUE var minY = Int.MAX_VALUE return this@parse .map { it.split(", ").map(String::toInt) } .map { (x, y) -> if (x > maxX) maxX = x if (y > maxY) maxY = y if (x < minX) minX = x if (y < minY) minY = y Point.of(x, y) } .toList() .let { Triple(it, Point.of(minX, minY), Point.of(maxX, maxY)) } } private fun List<Point>.findNearest(origin: Point): Pair<Point, Point>? = this .fold( Closest(Pair(Point.ZERO_ZERO, Int.MAX_VALUE), false) ) { closest, destination -> destination.manhattan(origin).let { distance -> when { distance < closest.coord.second -> Closest(destination to distance) distance == closest.coord.second -> closest.apply { valid = false } else -> closest } } } .takeIf { it.valid } ?.let { origin to it.coord.first } private fun Point.onEdge(min: Point, max: Point): Boolean = x == min.x || x == max.x || y == min.y || y == max.y private fun Point.createGridTo(p: Point, including: Boolean = true): Sequence<Point> = if (this == p) sequenceOf(this) else (p.x - x + if (including) 1 else 0).let { width -> var n = 0 generateSequence { Point.of(x + n % width, y + n / width).also { n++ } } .take((p.y - y + if (including) 1 else 0) * width) } data class Closest(var coord: Pair<Point, Int>, var valid: Boolean = true) }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
3,098
AdventOfCode
MIT License
src/Day06.kt
FuKe
433,722,611
false
{"Kotlin": 19825}
fun main() { test() val puzzleInput: List<Int> = readInput("Day06.txt")[0] .split(",") .map { it.toInt() } val partOneResult: Int = partOne(puzzleInput) println("Part one result: $partOneResult") val partTwoResult: Long = partTwo(puzzleInput) println("Part two result: $partTwoResult") } private fun partOne(initialFish: List<Int>): Int { val result: MutableList<Int> = initialFish.toMutableList() for (i in 1 .. 80) { val newFish: MutableList<Int> = mutableListOf() for (n in 0 until result.size) { var fish: Int = result[n] - 1 if (fish < 0) { fish = 6 newFish += 8 } result[n] = fish } result += newFish } return result.size } private fun partTwo(initialFish: List<Int>): Long { var cycleMap: MutableMap<Int, Long> = mutableMapOf( 0 to 0, 1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 0, 6 to 0, 7 to 0, 8 to 0, ) initialFish.forEach { cycleMap[it] = cycleMap[it]!! + 1 } for (n in 1 .. 256) { cycleMap = simulateDay(cycleMap) } return cycleMap.values.sum() } private fun simulateDay(fishMap: MutableMap<Int, Long>): MutableMap<Int, Long> { return mutableMapOf( 0 to fishMap[1]!!, 1 to fishMap[2]!!, 2 to fishMap[3]!!, 3 to fishMap[4]!!, 4 to fishMap[5]!!, 5 to fishMap[6]!!, 6 to fishMap[7]!! + fishMap[0]!!, 7 to fishMap[8]!!, 8 to fishMap[0]!! ) } private fun test() { val initialState: List<Int> = listOf(3, 4, 3, 1, 2) val partOneResult = partOne(initialState) check(partOneResult == 5934) val partTwoResult = partTwo(initialState) check(partTwoResult == 26984457539) }
0
Kotlin
0
0
1cfe66aedd83ea7df8a2bc26c453df257f349b0e
1,868
advent-of-code-2021
Apache License 2.0
src/main/kotlin/day16/Day16.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day16 import kotlin.math.ceil fun solveA(input: List<String>): Int { val valves = input.map(String::parseValve) // valves.forEach { println(it) } valves.calculateShortestPaths() // // valves.forEach { // println("${it.name} : ${it.shortestPathTo.map { it.key.name to it.value }}") // } var currentPosition = valves.find { it.name == "AA" }!! var nextMove: Valve? = null var distance = 0 var flowSum = 0 for (times in 0 until 30) { println("== Minute ${times + 1} == ") println("Valves ${valves.count { it.open }} are open, releasing ${ valves.filter { it.open }.sumOf { it.flow } } pressure.") println("Currently at ${currentPosition.name} distance $distance") flowSum += valves.filter { it.open }.sumOf { it.flow } if (distance > 0) { distance-- println() continue } if (nextMove != null) { currentPosition = nextMove println("You open valve ${currentPosition.name}.") println() currentPosition.open = true nextMove = null continue } val closest = valves.filter { v -> v.name != currentPosition.name }.filter { v -> !v.open && v.flow > 0 } .sortedWith(compareByDescending<Valve> { v -> ceil(v.flow.toFloat() / v.shortestPathTo[currentPosition.name]!!.toFloat()) }.thenBy { v -> v.shortestPathTo[currentPosition.name] }) println("CLOSEST ${closest.map { it.name }}") nextMove = closest.firstOrNull() ?: continue distance = nextMove.shortestPathTo[currentPosition.name]!! - 1 println("You move to valve $nextMove") println() } return flowSum } fun List<Valve>.calculateShortestPaths() = this.forEach { valve -> var path = 0 this.forEach { valve.shortestPathTo[it.name] = Int.MAX_VALUE } valve.shortestPathTo[valve.name] = 0 var currentTunnels = valve.tunnelsTo.toValves(this) while (currentTunnels.isNotEmpty()) { val next = mutableListOf<Valve>() currentTunnels.forEach { if (valve.shortestPathTo[it.name]!! > path + 1) { valve.shortestPathTo[it.name] = path + 1 next.addAll(it.tunnelsTo.toValves(this)) } } currentTunnels = next path++ } } fun List<String>.toValves(valves: List<Valve>) = this.map { name -> valves.find { it.name == name }!! } //2980 fun solveB(input: List<String>): Int { val valves = input.map(String::parseValve) valves.calculateShortestPaths() var maximum = 0 for (i in 0..1000000) { var flowSum = 0 valves.forEach { it.open = false it.targeted = false } val e1 = Elephant("Elephant 1", valves) val e2 = Elephant("Elephant 2", valves) for (times in 0 until 26) { flowSum += valves.filter { it.open }.sumOf { it.flow } e1.step() e2.step() } if (flowSum > maximum) maximum = flowSum } return maximum } data class Elephant(val name: String, val valves: List<Valve>) { private var currentPosition = valves.find { it.name == "AA" }!! private var nextMove: Valve? = null private var distance = 0 fun step() { if (distance > 0) { distance-- return } if (nextMove != null) { currentPosition = nextMove!! currentPosition.open = true nextMove = null return } val closest = valves .filter { v -> v.name != currentPosition.name } .filter { v -> !v.targeted } .filter { v -> !v.open && v.flow > 0 } .sortedWith(compareByDescending<Valve> { v -> ceil(v.flow.toFloat() / v.shortestPathTo[currentPosition.name]!!.toFloat()) }.thenBy { v -> v.shortestPathTo[currentPosition.name] }) if (closest.isEmpty()) return nextMove = closest.take(4).shuffled().first() nextMove!!.targeted = true distance = nextMove!!.shortestPathTo[currentPosition.name]!! - 1 } } fun String.parseValve(): Valve { val split = this.split("; ") val tunnels = split.last().split(" ").drop(4).joinToString("").split(",") val name = split.first().split(" ")[1] val flow = split.first().split(" ").last().split("=").last() return Valve(name, flow.toInt(), tunnels) } data class Valve(val name: String, val flow: Int, val tunnelsTo: List<String>, var open: Boolean = false) { val shortestPathTo = mutableMapOf<String, Int>() var targeted = false }
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
4,699
advent-of-code-2022
Apache License 2.0
src/Day11.kt
tomoki1207
572,815,543
false
{"Kotlin": 28654}
import javax.script.ScriptEngine import javax.script.ScriptEngineManager data class Monkey(val specs: List<String>) { private val engine: ScriptEngine = ScriptEngineManager().getEngineByExtension("js") val no: Int = "\\d+".toRegex().find(specs[0])!!.value.toInt() val items: MutableList<Int> = specs[1].substringAfter("items: ").split(", ").map { it.toInt() }.toMutableList() private val operation: String = specs[2].substringAfter("= ") val divisible: Int = specs[3].substringAfter("by ").toInt() private val throwToWhenTrue: Int = specs[4].substringAfter("monkey ").toInt() private val throwToWhenFalse: Int = specs[5].substringAfter("monkey ").toInt() var times: Int = 0 fun turn(reducer: (Long) -> Long): List<Pair<Int, Int>> { if (items.isEmpty()) { return emptyList() } val throwTo = items.map { item -> times++ val level = reducer((engine.eval(operation.replace("old", item.toString())) as Number).toLong()) val mod = (level % divisible).toInt() (if (mod == 0) throwToWhenTrue else throwToWhenFalse) to level.toInt() } items.clear() return throwTo } } fun main() { fun part1(input: List<String>): Long { val monkeys = input.chunked(7).map { Monkey(it) }.associateBy { it.no } repeat(20) { for (monkey in monkeys.values) { monkey.turn { it / 3 }.map { (no, level) -> monkeys[no]!!.items.add(level) } } } return monkeys.values.sortedByDescending { it.times }.let { (first, second) -> first.times * second.times.toLong() } } fun part2(input: List<String>): Long { val monkeys = input.chunked(7).map { Monkey(it) }.associateBy { it.no } val mod = monkeys.values.map { it.divisible.toLong() }.reduce(Long::times) repeat(10000) { for (monkey in monkeys.values) { monkey.turn { it % mod }.map { (no, level) -> monkeys[no]!!.items.add(level) } } } return monkeys.values.sortedByDescending { it.times } .take(2) .map { it.times.toLong() } .reduce(Long::times) } val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
2,527
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
raneric
573,109,642
false
{"Kotlin": 13043}
fun main() { fun part1(input: List<String>): Int { return input.map { it.checkIfBetween() }.sum() } fun part2(input: List<String>): Int { return input.map { it.checkIfOverlapp() }.sum() } val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun String.checkIfBetween(): Int { val range = this.split(',') val firstRange = range[0].trim().split('-').map { it.toInt() } val secondRange = range[1].trim().split('-').map { it.toInt() } return if ((secondRange[0] in firstRange[0]..firstRange[1] && secondRange[1] in firstRange[0]..firstRange[1]) || (firstRange[0] in secondRange[0]..secondRange[1] && firstRange[1] in secondRange[0]..secondRange[1]) ) 1 else 0 } fun String.checkIfOverlapp(): Int { val range = this.split(',') val firstRange = range[0].trim().split('-').map { it.toInt() } val secondRange = range[1].trim().split('-').map { it.toInt() } return if (secondRange[0] in firstRange[0]..firstRange[1] || secondRange[1] in firstRange[0]..firstRange[1] || firstRange[0] in secondRange[0]..secondRange[1] || firstRange[1] in secondRange[0]..secondRange[1] ) 1 else 0 }
0
Kotlin
0
0
9558d561b67b5df77c725bba7e0b33652c802d41
1,247
aoc-kotlin-challenge
Apache License 2.0
src/main/kotlin/sk/mkiss/algorithms/dynamic/LongestIncreasingSubsequence.kt
marek-kiss
430,858,906
false
{"Kotlin": 85343}
package sk.mkiss.algorithms.dynamic import kotlin.math.max object LongestIncreasingSubsequence { /** * get the size of the longest increasing subsequence of the given sequence * time complexity: Θ(n^2) * * @param sequence * @return */ fun getSizeOfLIS(sequence: List<Int>): Int { val longestEndingAt = calculateLISEndingInX(sequence) return longestEndingAt.maxOrNull() ?: 0 } private fun calculateLISEndingInX(sequence: List<Int>): List<Int> { val longestEndingAt = MutableList(sequence.size) { 1 } (sequence.indices).forEach { i -> (0 until i).forEach { j -> if (sequence[j] < sequence[i]) { longestEndingAt[i] = max(longestEndingAt[i], longestEndingAt[j] + 1) } } } return longestEndingAt } fun getLIS(sequence: List<Int>): List<Int> { if (sequence.isEmpty()) return emptyList() val longestEndingAt = calculateLISEndingInX(sequence) val lis = mutableListOf<Int>() // reconstruct the LIS from longestEndingAt var nextIndex = getNextIndex(longestEndingAt, sequence, end = sequence.size, prevValue = Int.MAX_VALUE) while (nextIndex != null) { lis.add(sequence[nextIndex]) nextIndex = getNextIndex(longestEndingAt, sequence, end = nextIndex, prevValue = sequence[nextIndex]) } return lis.reversed() } private fun getNextIndex(longestEndingAt: List<Int>, sequence: List<Int>, end: Int, prevValue: Int): Int? { var maxL = 0 var index: Int? = null (0 until end).forEach { i -> if (prevValue > sequence[i] && longestEndingAt[i] > maxL) { maxL = longestEndingAt[i] index = i } } return index } /** * get the size of the longest increasing subsequence of the given sequence * time complexity: O(nlogn) * * @param sequence * @return */ fun getSizeOfLISFast(sequence: List<Int>): Int { if (sequence.isEmpty()) return 0 // for each size of increasing subsequence keep the smallest ending of this sequence val subsequenceOfSizeEndings = mutableListOf(sequence[0]) sequence.forEach { x -> if (subsequenceOfSizeEndings.last() < x) { subsequenceOfSizeEndings.add(x) } else if (subsequenceOfSizeEndings.last() > x) { val index = getIndexOfSmallestBigger(subsequenceOfSizeEndings, 0, subsequenceOfSizeEndings.size, x) subsequenceOfSizeEndings[index] = x } } // the last element in the subsequenceOfSizeEndings is the ending of the longest increasing subsequence return subsequenceOfSizeEndings.size } private fun getIndexOfSmallestBigger(sortedList: List<Int>, s: Int, e: Int, x: Int): Int { require(s in sortedList.indices) require(e <= sortedList.size) require(s < e) if (s == e - 1) return s val m = s + ((e - s) / 2) return if (sortedList[m - 1] >= x) { getIndexOfSmallestBigger(sortedList, s, m, x) } else { getIndexOfSmallestBigger(sortedList, m, e, x) } } }
0
Kotlin
0
0
296cbd2e04a397597db223a5721b6c5722eb0c60
3,320
algo-in-kotlin
MIT License
src/Day03.kt
juliantoledo
570,579,626
false
{"Kotlin": 34375}
fun main() { /* A for Rock, B for Paper, and C for Scissors X for Rock, Y for Paper, and Z for Scissors 1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. */ fun itemsList(input: List<String>): List<Pair<List<Char>, List<Char>>> { var itemList = mutableListOf<Pair<List<Char>, List<Char>>>() input.forEach { line -> val charList = line.toList() val a = charList.subList(0, charList.size/2) val b = charList.subList(charList.size/2, charList.size) itemList.add(Pair(a, b)) } return itemList } fun letterValue(char: Char): Int { var value = char.digitToInt(radix = 36) - 9 if (char.isUpperCase()) value += 26 return value } fun part1(itemList: List<Pair<List<Char>, List<Char>>> ): Int { var totalScore = 0 itemList.forEach { items -> val common = items.first.intersect(items.second.toSet()) val value = letterValue(common.first()) totalScore += value } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 var itemList = mutableListOf<List<Char>>() input.forEach { line -> val charList = line.toList() itemList.add(charList) } for (i in 0 until itemList.size step 3 ) { val common = itemList[i].intersect(itemList[i+1]).intersect(itemList[i+2]) val value = letterValue(common.first()) totalScore += value } return totalScore } fun part2(elfCalories: MutableList<Int>): Int { elfCalories.sortDescending() return elfCalories[0] + elfCalories[1] + elfCalories[2] } var input = readInput("Day03_test") var items = itemsList(input) println( part1(items)) input = readInput("Day03_input") items = itemsList(input) println( part1(items)) println( part2(input)) }
0
Kotlin
0
0
0b9af1c79b4ef14c64e9a949508af53358335f43
2,162
advent-of-code-kotlin-2022
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2023/Day7.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2023 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom /** * --- Day 7: Camel Cards --- * https://adventofcode.com/2023/day/7 */ class Day7 : Solver { override fun solve(lines: List<String>): Result { return resultFrom( CardScorer(false).cardScore(lines), CardScorer(true).cardScore(lines) ) } private class CardScorer(val partB: Boolean) { fun cardScore(lines: List<String>): Int { val parsedInput = lines.map { it.split(" ") } .map { Pair(it[0], it[1].toInt()) } .sortedWith { h1, h2 -> compareHands(h1.first, h2.first) } .toList() return parsedInput.withIndex() .sumOf { (idx, hand) -> hand.second * (idx + 1) } } private fun compareHands(h1: String, h2: String): Int { val score1 = if (partB) handScoreB(h1) else handScore(h1) val score2 = if (partB) handScoreB(h2) else handScore(h2) if (score1 > score2) return 1 else if (score1 < score2) return -1 else { // Compare cards next if scores are the same. for (i in h1.indices) { if (h1[i].cardScore(partB) > h2[i].cardScore(partB)) return 1 if (h1[i].cardScore(partB) < h2[i].cardScore(partB)) return -1 } } error("Two hands are the same!") } private fun handScoreB(hand: String): Int { if (hand == "JJJJJ") return handScore("AAAAA") // We assume that it's most beneficial for all Jokers to always // be the same value to maximize outcome. // Determine joker card by looking at the most valuable card. val bestCard = hand.cardCounts().asIterable() .filter { it.key != 'J' } .sortedWith { c1, c2 -> // Choose card of highest frequency first. if (c1.value < c2.value) 1 else if (c1.value > c2.value) -1 else { // If the same (2 pairs), choose highest scoring card. if (c1.key.cardScore(partB) < c2.key.cardScore(partB)) 1 else -1 } } return handScore(hand.replace('J', bestCard.first().key)) } private fun handScore(hand: String): Int { val counts = hand.cardCounts() if (counts.values.contains(5)) return 6 if (counts.values.contains(4)) return 5 if (counts.values.contains(3)) { if (counts.values.contains(2)) return 4 // full house else return 3 } if (counts.values.count { it == 2 } == 2) return 2 if (counts.values.count { it == 2 } == 1) return 1 return 0 // All cards are different. } private fun Char.cardScore(partB: Boolean): Int { if (this.isDigit()) return this.digitToInt() if (this == 'T') return 10 if (this == 'J') return if (partB) 1 else 11 if (this == 'Q') return 12 if (this == 'K') return 13 if (this == 'A') return 14 error("Unknown card: $this") } private fun String.cardCounts(): Map<Char, Int> { val counts = mutableMapOf<Char, Int>() for (card in this) { counts.putIfAbsent(card, 0) counts[card] = counts[card]!! + 1 } return counts } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,204
euler
Apache License 2.0
src/main/kotlin/Day6.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List import kotlin.math.* object Day6 { fun part1(input: List<String>): String { val parseNumbers: (String, String) -> List<Int> = { str: String, prefix: String -> str.replace(prefix, "") .trim() .split("\\s+".toRegex()) .map { it.toInt() } } val times = parseNumbers(input.first(), "Time:") val distances = parseNumbers(input.last(), "Distance:") return times.zip(distances) .map { (time, distance) -> val (maxTime, minTime) = maxAndMinTimes(time.toLong(), distance.toLong()) maxTime - minTime + 1 }.reduce { a, b -> a * b }.toString() } fun part2(input: List<String>): String { val parseNumber: (String, String) -> Long = { str: String, prefix: String -> str.replace(prefix, "") .trim() .replace(" ", "") .toLong() } val time = parseNumber(input.first(), "Time:") val distance = parseNumber(input.last(), "Distance:") val (maxTime, minTime) = maxAndMinTimes(time, distance) // Add 1 to count the upper as inclusive return (maxTime - minTime + 1).toString() } /** * If we look at the equation for distance, we get: * distance = holdTime * (time - holdTime) * Turning this into a quadratic equation, we get: * 0 = -holdTime^2 + time * holdTime - distance * * We can then use the quadratic formula to find the holdTime: * holdTime = (-time +- sqrt(time^2 - 4 * -(distance + 1))) / -2 * * Note, we set distance + 1 because we have to exceed the target distance */ private fun maxAndMinTimes(time: Long, distance: Long): Pair<Long, Long> { val squareRoot = sqrt(time.toDouble().pow(2) - 4 * (distance + 1)) val upper = (-time - squareRoot) / -2 val lower = (-time + squareRoot) / -2 // We have to floor the upper because we cannot hold fractional seconds, and have to ceil the lower return floor(upper).toLong() to ceil(lower).toLong() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
2,178
kotlin-kringle
Apache License 2.0
src/Day03.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { fun List<Char>.sumPriorities() = this.sumOf { type -> if (type.isLowerCase()) type - 'a' + 1 else type - 'A' + 27 } fun part1(input: List<String>): Int { val rucksacksCompartments = input.map { line -> val middleIndex = line.length / 2 line.substring(0, middleIndex).toSet() to line.substring(middleIndex, line.length).toSet() } val itemTypes = rucksacksCompartments.fold(mutableListOf<Char>()) { itemTypes, (first, second) -> itemTypes.also { itemTypes.addAll(first.intersect(second)) } } return itemTypes.sumPriorities() } fun part2(input: List<String>): Int { val badgeItemTypes = input.chunked(3).flatMap { (first, second, third) -> first.toSet().intersect(second.toSet()).intersect(third.toSet()) } return badgeItemTypes.sumPriorities() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
1,188
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day08.kt
SimonMarquis
570,868,366
false
{"Kotlin": 50263}
class Day08(input: List<String>) { private val forest = Forest(input) fun part1() = with(forest) { walk().count { it.isVisible() } } fun part2() = with(forest) { walk().maxOf { it.scenicScore() } } } private typealias Tree = Pair<Int, Int> private class Forest(input: List<String>) { private val Tree.x: Int get() = first private val Tree.y: Int get() = second private val data = input.map { it.map(Char::digitToInt) } private val height = data.size private val width = data.first().size fun Tree.height() = data[y][x] fun walk(): Sequence<Tree> = sequence { for (y in 0 until height) for (x in 0 until width) yield(x to y) } fun Tree.isVisible(): Boolean { if (x == 0 || y == 0 || x == width - 1 || y == height - 1) return true return directions().any { line -> line.none { tree -> tree.height() >= height() } } } fun Tree.scenicScore(): Long { if (x == 0 || y == 0 || x == width - 1 || y == height - 1) return 0 return directions().map { it.viewingDistance(height()) }.reduce { acc, i -> acc * i } } private fun Tree.directions() = listOf<Pair<IntProgression, (Int) -> Tree>>( (y - 1 downTo 0) to { x to it }, /*up*/ (x + 1 until width) to { it to y }, /*right*/ (y + 1 until height) to { x to it }, /*down*/ (x - 1 downTo 0) to { it to y }, /*left*/ ).map { (it, transform) -> it.asSequence().map(transform) } private fun Sequence<Tree>.viewingDistance(height: Int) = takeWhileInclusive { it.height() < height }.count().toLong() }
0
Kotlin
0
0
a2129cc558c610dfe338594d9f05df6501dff5e6
1,652
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day16.kt
jmerle
317,518,472
false
null
package com.jaspervanmerle.aoc2020.day class Day16 : Day("30869", "4381476149273") { private val inputParts = getInput().split("\n\n") private val rangesByField = inputParts[0] .lines() .map { it.split(": ") } .fold(mutableMapOf<String, List<IntRange>>()) { acc, lineParts -> acc[lineParts[0]] = lineParts[1] .split(" or ") .map { val (left, right) = it.split("-").map { it.toInt() } left..right } acc } private val myTicket = inputParts[1] .lines()[1] .split(",") .map { it.toInt() } private val nearbyTickets = inputParts[2] .lines() .drop(1) .map { line -> line.split(",").map { it.toInt() } } private val allRanges = rangesByField.values.flatten() override fun solvePartOne(): Any { return nearbyTickets.sumBy { ticket -> ticket.filter { field -> allRanges.none { field in it } }.sum() } } override fun solvePartTwo(): Any { val validTickets = (nearbyTickets + listOf(myTicket)) .filter { ticket -> ticket.none { field -> allRanges.none { field in it } } } val options = rangesByField.keys .map { field -> val possibleColumns = rangesByField.keys.indices .filter { currentIndex -> validTickets.all { ticket -> rangesByField[field]!!.any { ticket[currentIndex] in it } } } field to possibleColumns.toMutableList() } .toMutableList() while (options.any { it.second.size > 1 }) { val singles = options.filter { it.second.size == 1 }.flatMap { it.second } for ((_, possibleColumns) in options.filter { it.second.size > 1 }) { possibleColumns.removeAll(singles) } } return options .filter { it.first.startsWith("departure") } .map { myTicket[it.second[0]].toLong() } .reduce { a, b -> a * b } } }
0
Kotlin
0
0
81765a46df89533842162f3bfc90f25511b4913e
2,280
advent-of-code-2020
MIT License
kotlin/src/2022/Day11_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
private val itemsRegex = Regex(".*items: (.*)") private val opRegex = Regex("Operation: new = ([a-z0-9]+) ([+-/*]) ([a-z0-9]+)") private val testRegex = Regex(".*divisible by (\\d+)") private val decRegex = Regex(".*throw to monkey (\\d+)") class Monkey(lines: List<String>) { var items: MutableList<Long> val operation: (Long) -> Long val test: (Long) -> Boolean val decision: Pair<Int, Int> val mod: Int // if the token is 'old', return `it` else the token's integer value private fun v(token: String, it: Long) = if (token == "old") it else token.toLong() init { val r1 = itemsRegex.matchEntire(lines[1].trim())!! items = r1.groups[1]!!.value.split(",").map {it.trim().toLong()}.toMutableList() val r2 = opRegex.matchEntire(lines[2].trim())!! val (x1, op, x2) = r2.groupValues.subList(1, 4) operation = when (op) { "*" -> {it -> v(x1, it) * v(x2, it)} "+" -> {it -> v(x1, it) + v(x2, it)} "-" -> {it -> v(x1, it) - v(x2, it)} else -> {it -> v(x1, it) / v(x2, it)} } val r3 = testRegex.matchEntire(lines[3].trim())!! mod = r3.groups[1]!!.value.toInt() test = {it % mod == 0L} val r4 = decRegex.matchEntire(lines[4].trim()) val m1 = r4!!.groupValues[1].toInt() val r5 = decRegex.matchEntire(lines[5].trim()) val m2 = r5!!.groupValues[1].toInt() decision = m1 to m2 } } fun main() { val input = readInput(11).split("\n\n") .asSequence() .map {it.trim()} .map {it.lines()} var monkeys = input.map {Monkey(it)}.toList() var insp = MutableList(monkeys.size) {0} // part1 repeat(20) { for ((i, monkey) in monkeys.withIndex()) { for (item in monkey.items) { val x = monkey.operation(item) / 3 if (monkey.test(x)) monkeys[monkey.decision.first].items.add(x) else monkeys[monkey.decision.second].items.add(x) } insp[i] += monkey.items.size monkey.items.clear() } } println(insp.sortedDescending().take(2).reduce { a, b -> a*b }) // common multiple of the monkeys' modular values (not necessarly LCM) val N = monkeys.map {it.mod}.reduce {acc, i -> acc*i} // part2 monkeys = input.map {Monkey(it)}.toList() insp = MutableList(monkeys.size) {0} repeat(10000) { for ((i, monkey) in monkeys.withIndex()) { for (item in monkey.items) { val x = monkey.operation(item) % N if (monkey.test(x)) monkeys[monkey.decision.first].items.add(x) else monkeys[monkey.decision.second].items.add(x) } insp[i] += monkey.items.size monkey.items.clear() } } println(insp.sortedDescending().take(2).map{it.toLong()}.reduce { a, b -> a * b }) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
2,958
adventofcode
Apache License 2.0
src/Day07.kt
KarinaCher
572,657,240
false
{"Kotlin": 21749}
fun main() { val MOST_SIZE = 100000 val TOTAL_SPACE = 70000000 val REQUIRED_FREE_SPACE = 30_000_000 fun changeDir(currentDir: Dir, command: List<String>, rootDir: Dir): Dir { val dirName = command[2] return when (dirName) { "/" -> rootDir ".." -> currentDir.parent ?: rootDir else -> { if (!currentDir.dirs.map { it.name }.toList().contains(dirName)) { val dir = Dir(name = dirName, currentDir) currentDir.dirs.add(dir) } currentDir.dirs.filter { it.name.equals(dirName) }.first() } } } fun getFileStructure(input: List<String>): Dir { val rootDir = Dir(parent = null, name = "/") var currentDir = rootDir val iter = input.listIterator() var line = iter.next() while (iter.hasNext()) { if (line.startsWith("$")) { // command found val command = line.split(" ") if (command[1].equals("cd")) { currentDir = changeDir(currentDir, command, rootDir) line = iter.next() } else if (command[1].equals("ls")) { var dirList = iter.next() while (!dirList.startsWith("$")) { val sp = dirList.split(" ") if (dirList.startsWith("dir")) { // add directory val dirName = sp[1] if (!currentDir.dirs.map { it.name }.toList().contains(dirName)) { currentDir.dirs.add(Dir(name = dirName, parent = currentDir)) } } else { // add File currentDir.files.add(ElvesFile(name = sp[1], size = sp[0].toInt())) } dirList = if (iter.hasNext()) iter.next() else break } line = dirList } } } return rootDir } fun dirSize(dir: Dir): Int { if (dir.files.isEmpty()) { return 0 } else { // println("dir " + dir.name) return dir.files.stream() // .peek { println("file size " + it.name + " " + it.size) } .mapToInt { it.size }.sum() } } fun traverse(parent: Dir, map: MutableMap<Dir, Int>): Int { for (dir in parent.dirs) { var result = 0 if (dir.dirs.isNotEmpty()) { result += traverse(dir, map) + dirSize(dir) } else { result = dirSize(dir) } map.put(dir, result) } return parent.dirs.stream().mapToInt {map.get(it) ?: 0}.sum() } fun getList(root: Dir): Map<Dir, Int> { val map = mutableMapOf<Dir, Int>() val size = traverse(root, map) + dirSize(root) map.put(root, size) map.forEach { println("map: " + it.key.name + " " + it.value) } return map } fun part1(input: List<String>): Int { val root = getFileStructure(input) val traverse = getList(root) return traverse.filter { it.value < MOST_SIZE }.toMap().values.stream().mapToInt { it.toInt() }.sum() } fun part2(input: List<String>): Int { val root = getFileStructure(input) val list = getList(root) val sorted = list.toList().sortedBy { it.second }.toMap() val rootDir = list.filterKeys{ it.name.equals("/") }.values.first() var freeSpace = TOTAL_SPACE.minus(rootDir) for (dir in sorted) { val dirSize = dir.value println("free " + freeSpace + " " + dirSize + " sum " + (freeSpace.plus(dirSize))) if ((freeSpace.plus(dirSize)) > REQUIRED_FREE_SPACE) { return dirSize } } return -1 } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } class Dir( val name: String, val parent: Dir?, val files: MutableList<ElvesFile> = mutableListOf(), val dirs: MutableList<Dir> = mutableListOf() ) class ElvesFile( val name: String, val size: Int )
0
Kotlin
0
0
17d5fc87e1bcb2a65764067610778141110284b6
4,482
KotlinAdvent
Apache License 2.0
src/main/kotlin/days/Day9Data.kt
yigitozgumus
572,855,908
false
{"Kotlin": 26037}
package days import utils.SolutionData fun main() = with(Day9Data()) { solvePart1() solvePart2() } data class Vector(val x: Int = 0, val y: Int = 0) { operator fun plus(v: Vector): Vector = Vector(this.x + v.x, this.y + v.y) operator fun minus(v: Vector): Vector = Vector(this.x - v.x, this.y - v.y) } class Day9Data : SolutionData(inputFile = "inputs/day9.txt") { val inputList = rawData .map { it.split(" ") } .map { it.first().toString() to it.last().toString().toInt() } fun getDirection(input: String): Vector = when (input) { "D" -> Vector(x = 0, y = -1) "U" -> Vector(x = 0, y = 1) "R" -> Vector(x = 1, y = 0) else -> Vector(x = -1, y = 0) } fun tailMovement(input: Vector): Vector = when { input.x == 2 -> Vector(x = 1, y = input.y) input.x == -2 -> Vector(x = -1, y = input.y) input.y == 2 -> Vector(x = input.x, y = 1) input.y == -2 -> Vector(x = input.x, y = -1) else -> Vector() } fun ropeMovement(input: Vector): Vector = when { input.x == 2 && input.y == 2 -> Vector(x = 1, y = 1) input.x == -2 && input.y == 2 -> Vector(x = -1, y = 1) input.x == 2 && input.y == -2 -> Vector(x = 1, y = -1) input.x == -2 && input.y == -2 -> Vector(x = -1, y = -1) else -> tailMovement(input) } } fun Day9Data.solvePart1() { var head = Vector() var tail = Vector() val seen = mutableListOf<Vector>() inputList.forEach { pair -> repeat(pair.second) { head += getDirection(pair.first) val tailMove = tailMovement(head - tail) tail += tailMove seen.add(tail) } } println(seen.toSet().count()) } fun Day9Data.solvePart2() { var head = Vector() var tail = MutableList(9){ Vector() } val seen = mutableListOf<Vector>() inputList.forEach { pair -> repeat(pair.second) { head += getDirection(pair.first) var tempHead = head (0 until 9).forEach { val newTailMove = ropeMovement(tempHead - tail[it]) tail[it] += newTailMove tempHead = tail[it] } seen.add(tail.last()) } } println(seen.toSet().count()) }
0
Kotlin
0
0
9a3654b6d1d455aed49d018d9aa02d37c57c8946
2,309
AdventOfCode2022
MIT License
y2015/src/main/kotlin/adventofcode/y2015/Day06.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2015 import adventofcode.io.AdventSolution import adventofcode.y2015.Day06.Action.* object Day06 : AdventSolution(2015, 6, "Probably a Fire Hazard") { override fun solvePartOne(input: String): Int = execute(parse(input)) { v, a -> when (a) { ON -> 1 OFF -> 0 TOGGLE -> 1 - v } } override fun solvePartTwo(input: String): Int = execute(parse(input)) { v, a -> when (a) { ON -> v + 1 OFF -> maxOf(v - 1, 0) TOGGLE -> v + 2 } } private inline fun execute(instructions: Sequence<Instruction>, execute: (v: Int, a: Action) -> Int): Int { val screen = Array(1000) { IntArray(1000) } for (instruction in instructions) { for (y in instruction.y1..instruction.y2) { val row = screen[y] for (x in instruction.x1..instruction.x2) row[x] = execute(row[x], instruction.a) } } return screen.sumOf(IntArray::sum) } private fun parse(input: String): Sequence<Instruction> { val regex = "(.*) (\\d+),(\\d+) through (\\d+),(\\d+)".toRegex() return input.lineSequence() .map { regex.matchEntire(it)!!.destructured } .map { (a, x1, y1, x2, y2) -> val act = when (a) { "turn on" -> ON "turn off" -> OFF "toggle" -> TOGGLE else -> throw IllegalArgumentException(a) } Instruction(act, x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt()) } } enum class Action { ON, OFF, TOGGLE } data class Instruction(val a: Action, val x1: Int, val y1: Int, val x2: Int, val y2: Int) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,967
advent-of-code
MIT License
src/Day14.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day14.printSolutionIfTest(24,93) } object Day14: Day<Int, Int>(14) { data class Point(val x:Int, val y:Int) override fun part1(lines: List<String>, ) = countSand(lines, false) override fun part2(lines: List<String>, ) = countSand(lines, true) fun countSand(lines: List<String>, floor: Boolean): Int { val grid = loadGrid(lines) val maxy = grid.maxOf { it.y } + 2 var size = 0 while(drop(Point(500, 0), grid, maxy, floor)) size++ return size; } private fun loadGrid(lines: List<String>): MutableSet<Point> { val grid = mutableSetOf<Point>() lines.map { line -> line.split(" -> ").map { point -> point.split(",") }.map { (x, y) -> Point(x.toInt(), y.toInt()) } }.forEach { path -> addToGrid(path, grid) } return grid } fun drop(start: Point, grid: MutableSet<Point>, maxDepth: Int, floor: Boolean): Boolean { val below = Point(start.x, start.y+1) val dl = Point(start.x-1, start.y+1) val dr = Point(start.x+1, start.y+1) return when{ !floor && start.y > maxDepth -> false floor && start.y == maxDepth-1 -> grid.add(start) grid.containsAll(listOf(below, dl, dr)) -> grid.add(start) !grid.contains(below) -> drop(below, grid, maxDepth, floor) !grid.contains(dl) -> drop(dl, grid, maxDepth, floor) !grid.contains(dr) -> drop(dr, grid, maxDepth, floor) else -> false } } private fun addToGrid(path: List<Point>, grid: MutableSet<Point>) { path.windowed(2, 1).forEach { (a, b) -> range(a.x, b.x).forEach{grid.add(Point(it, a.y))} range(a.y, b.y).forEach{grid.add(Point(a.x, it))} } } private fun range(a:Int, b:Int) = minOf(a,b) .. maxOf(a,b) }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
1,887
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day18.kt
sicruse
315,469,617
false
null
package days import java.util.* fun Int.exclusiveRangeTo(other: Int): IntRange = IntRange(this + 1, other - 1) class Day18 : Day(18) { private val problems: List<Problem> by lazy { inputList.map { problemText -> Problem(problemText) } } class Problem(private val expression: String) { enum class PrecedenceRules { BYORDER { override fun regex():List<Regex> = listOf("(\\d+) ([+*]) (\\d+)".toRegex()) }, MULTIPLYFIRST { override fun regex(): List<Regex> = listOf("(\\d+) ([+]) (\\d+)".toRegex(), "(\\d+) ([*]) (\\d+)".toRegex()) }; abstract fun regex(): List<Regex> } fun evaluate(rules: PrecedenceRules, expression: String = this.expression): String { var adjustedExpression = "" // Find, evaluate & remove parentheses if (expression.contains('(')) { val stack = Stack<Int>() for ((i,c) in expression.withIndex()) { when (c) { '(' -> stack.push(i) ')' -> { val open = stack.pop() if (stack.empty()) { val subExpression = expression.substring(open.exclusiveRangeTo(i)) val head = expression.take(open) val tail = if (i < expression.length) expression.drop(i + 1) else "" adjustedExpression = evaluate (rules, head + evaluate(rules, subExpression) + tail ) break } } else -> {} } } } else adjustedExpression = expression // We now have adjusted the expression so that it contains only values & operations (no parentheses) // Evaluate the adjusted expression according to the required precedence rules for (match in rules.regex()) { var operation = match.find(adjustedExpression) while (operation != null) { val result = operation.destructured .let { (_p1, _op, _p2) -> val p1 = _p1.toLong() val p2 = _p2.toLong() when (_op) { "+" -> p1 + p2 "*" -> p1 * p2 else -> throw IllegalArgumentException("Bad input '$adjustedExpression'") } } adjustedExpression = match.replaceFirst(adjustedExpression, result.toString()) operation = match.find(adjustedExpression) } } return adjustedExpression } } override fun partOne(): Any { return problems .map { it.evaluate(Problem.PrecedenceRules.BYORDER).toLong() } .sum() } override fun partTwo(): Any { return problems .map { it.evaluate(Problem.PrecedenceRules.MULTIPLYFIRST).toLong() } .sum() } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
3,272
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
src/com/kingsleyadio/adventofcode/y2021/day17/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day17 import com.kingsleyadio.adventofcode.util.readInput import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun part1(yRange: List<Int>): Int { val (y1, y2) = yRange.map { y -> if (y >= 0) y else y.inv() } val max = max(y1, y2) return max * (max + 1) shr 1 } fun part2(xRange: List<Int>, yRange: List<Int>): Int { val (x1, x2) = xRange val (y1, y2) = yRange var count = 0 for (xItem in 1..x2) { val ymax = yRange.sumOf { abs(it) } //Sufficiently large upper bound for (yItem in min(0, y1)..ymax) { var x = 0 var dx = xItem var y = 0 var dy = yItem while (x <= x2 && y >= y1) { x += dx y += dy-- if (dx > 0) dx-- if (x in x1..x2 && y in y1..y2) { count++ break } } } } return count } fun main() { readInput(2021, 17).forEachLine { line -> val (xdata, ydata) = line.substringAfter("target area: ").split(", ") val xRange = xdata.substringAfter("=").split("..").map { it.toInt() } val yRange = ydata.substringAfter("=").split("..").map { it.toInt() } println(part1(yRange)) println(part2(xRange, yRange)) } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,374
adventofcode
Apache License 2.0
gcj/y2022/round3/b_small.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2022.round3 private fun solve(): Long { val (n, colors) = readInts() val constraints = List(colors) { readInts() } val hats = readInts().map { it - 1 } val byColor = List(colors) { mutableListOf<Int>() } val indexInColor = IntArray(colors) for (i in hats.indices) { byColor[hats[i]].add(i) } val x = IntArray(colors) val y = IntArray(colors) val z = IntArray(colors) fun fillXYZ(c: Int, start: Int) { val (lowIn, highIn) = constraints[c] val ofC = byColor[c] if (ofC.size == 0) { x[c] = 2 * n; y[c] = -1; z[c] = -1 return } val low = maxOf(lowIn, 1) val high = minOf(highIn, ofC.size) if (start > 0) indexInColor[c]++ val index = indexInColor[c] fun get(i: Int) = if (i < ofC.size) ofC[i] else (ofC[i - ofC.size] + n) x[c] = get(index) + 1 if (ofC.size < low) { y[c] = -1; z[c] = -1 } else { y[c] = get(index + low - 1) + 1 z[c] = if (high >= ofC.size) 2 * n else get(index + high) + 1 } } val good = IntArray(2 * n) fun add(from: Int, to: Int, value: Int) { if (from >= to) return for (k in from until to) good[k] += value } fun count(start: Int): Int { var perfects = 0 for (k in 2 until n) if (good[start + k] == colors) perfects++ return perfects } for (c in constraints.indices) { fillXYZ(c, 0) add(0, x[c], 1) add(y[c], z[c], 1) } var ans = count(0).toLong() for (i in 0..n - 2) { val c = hats[i] add(0, x[c], -1) add(y[c], z[c], -1) fillXYZ(c, i + 1) add(0, x[c], 1) add(y[c], z[c], 1) ans += count(i + 1) } return ans } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,797
competitions
The Unlicense
src/day4/Day4.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day4 import readInput import toPair fun main() { val testInput = parse(readInput("day04/test")) val input = parse(readInput("day04/input")) println(solve1(testInput)) println(solve1(input)) println(solve2(testInput)) println(solve2(input)) } fun solve1(input: List<Pair<IntRange, IntRange>>): Int { fun IntRange.contains(r: IntRange) = r.first in this && r.last in this fun computePair(a: IntRange, b: IntRange) = if (a.contains(b) || b.contains(a)) 1 else 0 return input.sumOf { (a, b) -> computePair(a, b) } } fun solve2(input: List<Pair<IntRange, IntRange>>): Int { fun computePair(a: IntRange, b: IntRange) = if ((a intersect b).isEmpty()) 0 else 1 return input.sumOf { (a, b) -> computePair(a, b) } } fun parse(input: List<String>): List<Pair<IntRange, IntRange>> { fun toRange(s: String): IntRange { val (a, b) = s.split("-").map { c -> c.trim().toInt() }.toPair() return a..b } fun parseLine(v: String): Pair<IntRange, IntRange> { return v.split(',') .map { toRange(it) } .toPair() } return input.map { parseLine(it) } }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
1,158
aoc-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2023/Day03GearRatios.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2023 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.neighbors import adventofcode.common.product class Day03GearRatios(customInput: PuzzleInput? = null) : Puzzle(customInput) { override fun partOne() = input .parsePartNumbers() .filter { partNumber -> partNumber.isValidPartNumber(input.parseGrid()) } .sumOf(PartNumber::value) override fun partTwo() = input .parsePartNumbers() .asSequence() .map { partNumber -> partNumber.getAdjacentGears(input.parseGrid()) to partNumber.value } .filter { (gears, _) -> gears.isNotEmpty() } .groupBy { (gears, _) -> gears } .map { (_, adjacentParts) -> adjacentParts.map { (_, adjacentPartNumber) -> adjacentPartNumber } } .filter { adjacentPartNumbers -> adjacentPartNumbers.size == 2 } .sumOf(List<Int>::product) companion object { private val PART_NUMBER_REGEX = """(\d+)""".toRegex() private data class PartNumber( val value: Int, val location: Pair<IntRange, Int> ) { fun isValidPartNumber(grid: List<List<Char>>) = neighbors(grid) .map { (x, y) -> grid[y][x] } .filterNot { value -> value == '.' } .isNotEmpty() fun getAdjacentGears(grid: List<List<Char>>) = neighbors(grid) .filter { (x, y) -> grid[y][x] == '*' } .toSet() private fun neighbors(grid: List<List<Char>>): Set<Pair<Int, Int>> { val coordinates = location .first .map { x -> x to location.second } .toSet() return coordinates .flatMap { (x, y) -> grid.neighbors(x, y, includeDiagonals = true) } .toSet() .minus(coordinates) } } private fun String.parseGrid(): List<List<Char>> = lines().map(String::toList) private fun String.parsePartNumbers(): List<PartNumber> = lines() .flatMapIndexed { y, line -> PART_NUMBER_REGEX .findAll(line) .map { PartNumber(it.value.toInt(), it.range to y) } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,311
AdventOfCode
MIT License
02/src/commonMain/kotlin/Main.kt
daphil19
725,415,769
false
{"Kotlin": 131380}
expect fun getLines(inputOrPath: String): List<String> fun main() { val lines = getLines(INPUT_FILE) // val lines = ("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green\n" + // "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue\n" + // "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red\n" + // "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red\n" + // "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green").split("\n") part1(lines) part2(lines) } const val MAX_RED = 12L const val MAX_GREEN = 13L const val MAX_BLUE = 14L fun part1(lines: List<String>) { println(lines.map { line -> line.split(": ").let { val id = it.first().removePrefix("Game ") id.toLong() to it.last().split("; ") } } .filter { (id, games) -> // print(id) games.forEach { game -> val remaining = mutableMapOf("red" to MAX_RED, "green" to MAX_GREEN, "blue" to MAX_BLUE) game.split(", ").forEach { cubeAndColor -> cubeAndColor.split(" ").let { val color = it.last() remaining[color]?.let { count -> remaining[color] = count - it.first().toLong() } if (remaining.values.any { it < 0L }) { // boo return@filter false//.also { println(" no")} } } } } true//.also { println("")} } .sumOf { (id, _) -> id }) } fun part2(lines: List<String>) { println(lines.map { line -> line.split(": ").let { val id = it.first().removePrefix("Game ") id.toInt() to it.last().split("; ") } } .map { (id, games) -> // print(id) val most = mutableMapOf<String, Long>() games.forEach { game -> // val remaining = mutableMapOf("red" to MAX_RED, "green" to MAX_GREEN, "blue" to MAX_BLUE) game.split(", ").forEach { cubeAndColor -> cubeAndColor.split(" ").let { val color = it.last() val count = it.first().toLong() most.getOrPut(color) { count }.run { if (count > this) { most[color] = count } } } } } most.values.reduce { acc, l -> acc * l } // true.also { println("")} } .sum()) }
0
Kotlin
0
0
70646b330cc1cea4828a10a6bb825212e2f0fb18
2,734
advent-of-code-2023
Apache License 2.0
src/Day10.kt
hoppjan
433,705,171
false
{"Kotlin": 29015, "Shell": 338}
fun main() { fun part1(input: List<String>) = input.sumOf { line -> line.lineScore() } fun part2(input: List<String>) = input.filterNotCorrupted() .map { it.completionScore() } .median() val day = "10" val testInput = StringInputReader.read("Day${day}_test") val input = StringInputReader.read("Day$day") // part 1 val testSolution1 = 26397 val testOutput1 = part1(testInput) printTestResult(1, testOutput1, testSolution1) check(testOutput1 == testSolution1) printResult(1, part1(input).also { check(it == 216297) }) // part 2 val testSolution2 = 288957L val testOutput2 = part2(testInput) printTestResult(2, testOutput2, testSolution2) check(testOutput2 == testSolution2) printResult(2, part2(input).also { check(it == 2165057169L) }) } private fun String.lineScore() = analyzeBrackets(default = 0) { scoreMapPartOne[it] ?: 0 } private fun String.completionScore(): Long = openBrackets { openedBrackets -> openedBrackets .mapNotNull { scoreMapPartTwo[brackets[it]] } .reversed() .fold(0L) { acc, i -> acc * 5 + i } } private fun String.openBrackets(withOpenBrackets: (MutableList<Char>) -> Long) = analyzeBrackets(withOpenBrackets) { 0L } private fun List<String>.filterNotCorrupted() = filter { it.isNotCorrupted() } private fun String.isNotCorrupted() = analyzeBrackets(default = true) { false } private fun <R> String.analyzeBrackets(default: R, onUnexpected: (Char) -> R) = analyzeBrackets({ default }, onUnexpected) private fun <R> String.analyzeBrackets(onDefault: (MutableList<Char>) -> R, onUnexpected: (Char) -> R): R { val opened = mutableListOf<Char>() for (bracket in this) when (bracket) { in brackets -> opened.add(bracket) brackets[opened.lastOrNull()] -> opened.removeLast() else -> return onUnexpected(bracket) } return onDefault(opened) } fun List<Long>.median() = sorted().let { it[it.size / 2] } val brackets = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>', ) val scoreMapPartOne = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) val scoreMapPartTwo = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4, )
0
Kotlin
0
0
04f10e8add373884083af2a6de91e9776f9f17b8
2,434
advent-of-code-2021
Apache License 2.0
src/year2022/day21/Day21.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2022.day21 import readInputFileByYearAndDay import readTestFileByYearAndDay import kotlin.math.abs fun String.containsAny(of: List<String>): Boolean { for (keyword in of) if (this.contains(keyword, true)) return true return false } fun main() { fun resolvePart1(monkey: String, monkeys: Map<String, String>): Long { val task = monkeys[monkey]!! if (!task.containsAny(listOf("*", "/", "+", "-"))) return task.toLong() val components = task.split(" ") val resultLeft = resolvePart1(components.first(), monkeys) val resultRight = resolvePart1(components.last(), monkeys) return if (task.contains("*")) resultLeft * resultRight else if (task.contains("/")) resultLeft / resultRight else if (task.contains("+")) resultLeft + resultRight else resultLeft - resultRight } // we additionally memorize which recursive path depends on the output of the human // if a path does not, we substitute its entry in monkeys to reduce the number of recursive // calls in the future fun resolvePart2(monkey: String, monkeys: MutableMap<String, String>): Pair<Double, Boolean> { val task = monkeys[monkey]!! if (!task.containsAny(listOf("*", "/", "+", "-"))) return monkeys[monkey]!!.toDouble() to (monkey == "humn") val components = task.split(" ") val resultLeft = resolvePart2(components.first(), monkeys) val resultRight = resolvePart2(components.last(), monkeys) val calcResult = if (task.contains("*")) resultLeft.first * resultRight.first else if (task.contains("/")) resultLeft.first / resultRight.first else if (task.contains("+")) resultLeft.first + resultRight.first else resultLeft.first - resultRight.first val dependsOnHuman = resultLeft.second || resultRight.second if (!dependsOnHuman) monkeys[monkey] = calcResult.toString() return calcResult to dependsOnHuman } fun resolveRootFor(monkeys: MutableMap<String, String>, humanNumber: Double): Pair<Long, Long> { monkeys["humn"] = humanNumber.toString() val listeningTo = monkeys["root"]!!.split(" + ") val solution0 = resolvePart2(listeningTo.first(), monkeys) val solution1 = resolvePart2(listeningTo.last(), monkeys) return solution0.first.toLong() to solution1.first.toLong() } fun part1(input: List<String>): Long = input.map { it.split(": ") } .associate { it.first() to it.last() } .let { resolvePart1("root", it) } fun part2(input: List<String>): Long { val monkeys = input.map { it.split(": ") }.associate { it.first() to it.last() }.toMutableMap() var left = 0L var right = Long.MAX_VALUE // binary search while (true) { val solutionLeft = resolveRootFor(monkeys, left.toDouble()) val solutionRight = resolveRootFor(monkeys, right.toDouble()) if (solutionLeft.first == solutionLeft.second) return left if (solutionRight.first == solutionRight.second) return right val middle = (left + right) / 2 if (abs(solutionLeft.first - solutionLeft.second) > abs(solutionRight.first - solutionRight.second)) left = middle else right = middle } } val testInput = readTestFileByYearAndDay(2022, 21) check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInputFileByYearAndDay(2022, 21) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
3,611
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2021/Day10.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2021 import readInput import java.util.* /** * A character in a chunk. * @property open the open symbol * @property close the close symbol * @property corruptScore the score this character gives, if it is the one corrupting the chunk * @property missingScore the amount this character adds to the score, if it is missing in a chunk */ private enum class ChunkChar(val open: Char, val close: Char, val corruptScore: Int, val missingScore: Int) { A('(', ')', 3, 1), B('[', ']', 57, 2), C('{', '}', 1197, 3), D('<', '>', 25137, 4); companion object { /** * Valid opening symbols */ val openings = values().map { it.open } /** * Valid closing symbols */ val closings = values().map { it.close } /** * @param c the open or close symbol of a chunk character * @return the corresponding chunk character */ fun from(c: Char) = values().first { it.open == c || it.close == c } } override fun toString() = open.toString() } /** * Checks if this chunk is corrupted or incomplete */ private fun String.checkChunk(): Result<*, *> { val stack = Stack<ChunkChar>() for (char in this) { when (char) { in ChunkChar.openings -> stack.push(ChunkChar.from(char)) in ChunkChar.closings -> if (stack.pop().close != char) return CorruptResult(ChunkChar.from(char)) } } return if (stack.isNotEmpty()) { IncompleteResult(stack.reversed()) } else { ValidResult } } /** * Object describing the result of a chunk analysis, see [String.checkChunk] */ private sealed class Result<T, N>(val result: T) { /** * @return the result score */ abstract fun getScore(): N } /** * Class representing a corrupt chunk result. * @property result the invalid character */ private class CorruptResult(invalidChar: ChunkChar) : Result<ChunkChar, Int>(invalidChar) { override fun getScore() = result.corruptScore } /** * Class representing an incomplete chunk result. * @property result the missing characters */ private class IncompleteResult(missing: List<ChunkChar>) : Result<List<ChunkChar>, Long>(missing) { override fun getScore() = result.fold(0L) { acc, current -> acc * 5 + current.missingScore } } /** * Object representing a valid chunk result. */ private object ValidResult : Result<Any?, Int>(null) { override fun getScore() = 0 } private fun part1(input: List<String>) = input.map { it.checkChunk() }.filterIsInstance(CorruptResult::class.java).sumOf { it.getScore() } private fun part2(input: List<String>): Long { val scores = input.map { it.checkChunk() }.filterIsInstance(IncompleteResult::class.java) .map { it.getScore() }.sorted() return scores[scores.size / 2] } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 26397) check(part2(testInput) == 288957L) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,136
adventOfCode
Apache License 2.0
src/Day20.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Long { val numbers = input.mapIndexed { index, s -> Number(index, s.toLong()) } val file = GroveCoordinateFile(numbers.toMutableList()) file.mix() return file.sumGroveCoordinates() } fun part2(input: List<String>): Long { val decryptionKey = 811589153 val numbers = input.mapIndexed { index, s -> Number(index, s.toLong() * decryptionKey) } val file = GroveCoordinateFile(numbers.toMutableList()) repeat(10) { file.mix() } return file.sumGroveCoordinates() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") assertEquals(3, part1(testInput)) assertEquals(1623178306, part2(testInput)) val input = readInput("Day20") println(part1(input)) println(part2(input)) } private class GroveCoordinateFile(val numbers: MutableList<Number>) { fun mix() { val maxIndex = numbers.lastIndex for (i in 0..maxIndex) { val currentIndex = numbers.indexOfFirst { it.initialIndex == i } val currentNumber = numbers.removeAt(currentIndex) val newIndex = (currentIndex + currentNumber.value).mod(numbers.size) numbers.add(newIndex, currentNumber) } } fun sumGroveCoordinates(): Long { val indexOfZero = numbers.indexOfFirst { it.value == 0L } val firstIndex = (indexOfZero + 1000).mod(numbers.size) val secondIndex = (indexOfZero + 2000).mod(numbers.size) val thirdIndex = (indexOfZero + 3000).mod(numbers.size) return numbers[firstIndex].value + numbers[secondIndex].value + numbers[thirdIndex].value } } data class Number(val initialIndex: Int, val value: Long) { override fun toString() = value.toString() }
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
1,758
aoc2022
Apache License 2.0
src/Day02.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
fun main() { fun part1(input: List<String>): Int { var sum = 0 for (s in input) { val (first, second) = s.split(" ") val elf = first.first() - 'A' + 1 val me = second.first() - 'X' + 1 if (elf == 1 && me == 3) sum += 0 else if (elf == 3 && me == 1) sum += 6 else if (me > elf) sum += 6 else if (elf == me) sum += 3 else if (elf > me) sum += 0 sum += me } return sum } fun part2(input: List<String>): Int { var sum = 0 for (s in input) { val (first, second) = s.split(" ") val elf = first.first() - 'A' + 1 val win = second.first() - 'X' val me = when (win) { 0 -> if (elf == 1) 3 else elf - 1 1 -> elf else -> if (elf == 3) 1 else elf + 1 } sum += me + win * 3 } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") // println(part1(testInput)) check(part1(testInput) == 15+12+10) // println(part2(testInput)) check(part2(testInput) == 12+16+10) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
1,337
AoC-2022
Apache License 2.0
2022/Day13.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
private sealed interface Elem : Comparable<Elem> { data class EInt(val v: Int) : Elem { override fun toString() = v.toString() } data class EList(val lst: List<Elem>) : Elem { override fun toString() = "[${lst.joinToString(",")}]" } override fun compareTo(other: Elem): Int { when { this is EInt && other is EInt -> return this.v.compareTo(other.v) this is EList && other is EList -> { for (i in 0 until maxOf(this.lst.size, other.lst.size)) { when { i >= this.lst.size -> return -1 i >= other.lst.size -> return 1 else -> { val r = this.lst[i].compareTo(other.lst[i]) if (r != 0) return r } } } return 0 } this is EInt -> return EList(listOf(this)).compareTo(other) other is EInt -> return this.compareTo(EList(listOf(other))) else -> error("") } } companion object { fun parseList(s: String, start: Int): Pair<EList, Int> { val res = mutableListOf<Elem>() var i = start while (i < s.length) { when (s[i]) { ',' -> i++ '[' -> { val (lst, end) = parseList(s, i+1) res.add(lst) i = end } ']' -> { return EList(res) to i+1 } else -> { val ni = s.indexOfAny(charArrayOf(',', ']'), i) res.add(EInt(s.substring(i, ni).toInt())) i = ni } } } error("") } } } fun main() { val input = readInput("Day13") var res1 = 0 val res2 = mutableListOf<Elem>() for (i in input.indices step 3) { val (s1) = Elem.parseList(input[i], 1) val (s2) = Elem.parseList(input[i+1], 1) println(s1) println(s2) println(s1.compareTo(s2)) if (s1 <= s2) res1 += (i/3)+1 res2.add(s1) res2.add(s2) } println(res1) val (div1) = Elem.parseList("[[2]]", 1) val (div2) = Elem.parseList("[[6]]", 1) res2.addAll(listOf(div1, div2)) res2.sort() println((res2.indexOf(div1)+1) * (res2.indexOf(div2)+1)) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
2,564
advent-of-code-kotlin
Apache License 2.0
src/Day02.kt
paul-griffith
572,667,991
false
{"Kotlin": 17620}
import Outcome.Draw import Outcome.Lose import Outcome.Win import Hand.Paper import Hand.Rock import Hand.Scissors private enum class Hand(val score: Int) { Rock(1), Paper(2), Scissors(3); companion object { fun fromChar(char: Char) = when (char) { 'A', 'X' -> Rock 'B', 'Y' -> Paper 'C', 'Z' -> Scissors else -> throw IllegalStateException() } } } private enum class Outcome(val score: Int) { Lose(0), Draw(3), Win(6); override fun toString(): String = when (this) { Win -> "beats" Lose -> "loses to" Draw -> "draws" } companion object { fun fromChar(char: Char) = when (char) { 'X' -> Lose 'Y' -> Draw 'Z' -> Win else -> throw IllegalStateException() } } } private data class Round(val theirMove: Hand, val yourMove: Hand) { constructor(theirChar: Char, yourChar: Char) : this( Hand.fromChar(theirChar), Hand.fromChar(yourChar) ) private val outcome: Outcome = when { theirMove == Rock && yourMove == Rock -> Draw theirMove == Paper && yourMove == Rock -> Lose theirMove == Scissors && yourMove == Rock -> Win theirMove == Rock && yourMove == Paper -> Win theirMove == Paper && yourMove == Paper -> Draw theirMove == Scissors && yourMove == Paper -> Lose theirMove == Rock && yourMove == Scissors -> Lose theirMove == Paper && yourMove == Scissors -> Win theirMove == Scissors && yourMove == Scissors -> Draw else -> throw IllegalStateException("Impossible") } val score: Int = yourMove.score + outcome.score override fun toString(): String { return "$yourMove $outcome $theirMove - score: $score (${yourMove.score} + ${outcome.score})" } } fun main() { fun part1(input: Sequence<String>): Int { return input.sumOf { line -> val (theirMove, _, yourMove) = line.toCharArray() val round = Round(theirMove, yourMove) // println("$line - $round") round.score } } fun part2(input: Sequence<String>): Int { return input.sumOf { line -> val (theirMove, _, outcome) = line.toCharArray() val theirHand = Hand.fromChar(theirMove) val yourHand = when (Outcome.fromChar(outcome)) { Lose -> when (theirHand) { Rock -> Scissors Paper -> Rock Scissors -> Paper } Draw -> theirHand Win -> when (theirHand) { Rock -> Paper Paper -> Scissors Scissors -> Rock } } val round = Round(theirHand, yourHand) // println("$line - $round") round.score } } println(part1(readInput("day02"))) println(part2(readInput("day02"))) }
0
Kotlin
0
0
100a50e280e383b784c3edcf65b74935a92fdfa6
3,033
aoc-2022
Apache License 2.0
src/Day02.kt
ThijsBoehme
572,628,902
false
{"Kotlin": 16547}
fun main() { fun scoreOfShape(shape: String): Int = when (shape) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> error("Unknown shape") } fun scoreOfOutcome(outcome: String): Int = when (outcome) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> error("Unknown result") } fun part1(input: List<String>) = input.sumOf { val (opponent, you) = it.split(" ") val scoreOfShape = scoreOfShape(you) val scoreOfOutcome = when (scoreOfShape(you) - scoreOfShape(opponent)) { -1, 2 -> 0 0 -> 3 1, -2 -> 6 else -> error("Unknown result") } return@sumOf scoreOfShape + scoreOfOutcome } fun part2(input: List<String>) = input.sumOf { val (opponent, outcome) = it.split(" ") val scoreOfOutcome = scoreOfOutcome(outcome) val scoreOfShape = when (scoreOfOutcome) { 0 -> (scoreOfShape(opponent) + 1) % 3 + 1 3 -> scoreOfShape(opponent) 6 -> scoreOfShape(opponent) % 3 + 1 else -> error("Unknown outcome") } return@sumOf scoreOfShape + scoreOfOutcome } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
707e96ec77972145fd050f5c6de352cb92c55937
1,532
Advent-of-Code-2022
Apache License 2.0
src/Day02/Day02.kt
AllePilli
572,859,920
false
{"Kotlin": 47397}
package Day02 import checkAndPrint import measureAndPrintTimeMillis import readInput fun main() { fun prepareInput(input: List<String>) = input.map { line -> line.split(" ").map(String::first) } fun part1(input: List<List<Char>>) = input.sumOf { (opponent, player) -> matchScore(player.toHand(), opponent.toHand()) } fun part2(input: List<List<Char>>) = input.sumOf { (opponent, outcome) -> val opponentHand = opponent.toHand() matchScore(outcome.toHand(opponentHand), opponentHand) } val testInput = prepareInput(readInput("Day02_test")) check(part1(testInput) == 15) check(part2(testInput) == 12) val input = prepareInput(readInput("Day02")) measureAndPrintTimeMillis { checkAndPrint(part1(input), 15337) } measureAndPrintTimeMillis { checkAndPrint(part2(input), 11696) } } private fun matchScore(player: Hand, opponent: Hand) = player.score + playerScore(player, opponent) private fun playerScore(player: Hand, opponent: Hand): Int = when { player.score == opponent.score -> 3 (player.score % 3) + 1 == opponent.score -> 0 else -> 6 } private fun Char.toHand(opponent: Hand) = when (this) { 'X' -> Hand.fromScore((opponent.score - 1).takeUnless { it == 0 } ?: 3) 'Y' -> Hand.fromScore(opponent.score) 'Z' -> Hand.fromScore((opponent.score % 3) + 1) else -> error("unknown hand: $this") } private fun Char.toHand() = when (this) { 'A', 'X' -> Hand.Rock 'B', 'Y' -> Hand.Paper 'C', 'Z' -> Hand.Scissors else -> error("unknown hand: $this") } private enum class Hand(val score: Int) { Rock(1), Paper(2), Scissors(3); companion object { fun fromScore(score: Int): Hand = values().find { it.score == score } ?: error("No Day02.Hand found for score $score") } }
0
Kotlin
0
0
614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643
1,863
AdventOfCode2022
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day15/day15.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day15 import eu.janvdb.aocutil.kotlin.readLines import kotlin.streams.asSequence //const val FILENAME = "input15-test.txt" const val FILENAME = "input15.txt" fun main() { val instructions = readLines(2023, FILENAME)[0].split(",") part1(instructions) part2(instructions) } private fun part1(instructions: List<String>) { val hashes = instructions.map { calculateHash(it) } println(hashes.sum()) } private fun part2(instructions: List<String>) { val boxes = instructions.fold(mapOf<Int, Map<String, Int>>()) { acc, it -> executeInstruction(acc, it) } val focusingPower = calculateFocusingPower(boxes) println(focusingPower) } fun executeInstruction(boxes: Map<Int, Map<String, Int>>, instruction: String): Map<Int, Map<String, Int>> { val label = instruction.replace(Regex("[-=].*"), "") val boxNumber = calculateHash(label) var box = boxes.getOrElse(boxNumber) { mapOf() } if (instruction.contains("-")) { box = box.minus(label) } else { val value = instruction.replace(Regex(".*="), "").toInt() box = box.plus(Pair(label, value)) } val result = if (box.isEmpty()) boxes.minus(boxNumber) else boxes + Pair(boxNumber, box) println("$instruction\t-> $result") return result } fun calculateFocusingPower(boxes: Map<Int, Map<String, Int>>): Int { val scores = boxes.flatMap { entry -> entry.value.entries.mapIndexed { index, entry2 -> Pair(entry2.key, (entry.key + 1) * (index + 1) * entry2.value) } } println(scores) return scores.sumOf { it.second } } fun calculateHash(input: String): Int { return input.chars().asSequence().fold(0) { acc, it -> (acc + it) * 17 % 256 } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,746
advent-of-code
Apache License 2.0
src/main/kotlin/day12/Day12.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day12 import java.util.* fun solveA(input: List<String>): Int { val heightMap = createHeightMap(input).also { it.initialize() } val start = heightMap.values.find { it.start } ?: throw Exception("No start exists!") val end = heightMap.values.find { it.end } ?: throw Exception("No end exists!") return calcShortestPath(start, end) } fun solveB(input: List<String>): Int { val heightMap = createHeightMap(input).also { it.initialize() } val end = heightMap.values.find { it.end } ?: throw Exception("No end exists!") return heightMap.values.filter { it.elevation == 1 }.minOf { start -> calcShortestPath(start, end) } } fun calcShortestPath(start: Square, end: Square): Int { start.shortestPath = 0 val compare: Comparator<Square> = compareBy<Square> { it.letter }.thenBy { it.shortestPath } val queue = PriorityQueue(compare).also { it.add(start) } while (!queue.contains(end) && queue.isNotEmpty()) { val current = queue.poll() current.moves.forEach { if (it.shortestPath > current.shortestPath + 1) it.shortestPath = current.shortestPath + 1 } queue.addAll(current.moves.filter { !queue.contains(it) && it.shortestPath >= current.shortestPath + 1 }) } return end.shortestPath } data class Position(val x: Int, val y: Int) { fun surrounding() = listOf( Position(x, y + 1), Position(x + 1, y), Position(x, y - 1), Position(x - 1, y) ) } data class Square(val letter: Char, val position: Position) { val elevation = when (letter) { 'S' -> lowestElevation 'E' -> highestElevation else -> letter.code - charCodeToElevationDifference } val start = letter == 'S' val end = letter == 'E' var shortestPath = Int.MAX_VALUE val moves = mutableListOf<Square>() fun calcPossibleMoves(squares: List<Square?>) = moves.addAll(squares.filterNotNull().filter { it.elevation <= elevation + 1 }) companion object { const val lowestElevation = 1 const val highestElevation = 26 const val charCodeToElevationDifference = 96 } } fun createHeightMap(input: List<String>) = input .flatMapIndexed { y, str -> str.mapIndexed { x, char -> Square(char, Position(x, y)) } } .associateBy { it.position } fun Map<Position, Square>.initialize() = this.entries.forEach { it.value.calcPossibleMoves(it.key.surrounding().map { pos -> this[pos] }) } //fun solveA(input: List<String>): Int { // // val heightMap = mutableMapOf<Position, Square>() // // input.forEachIndexed { y, s -> // s.forEachIndexed { x, c -> // val pos = Position(x, y) // val square = Square(c, pos) // heightMap[pos] = square // } // } // // heightMap.entries.forEach { // it.value.calcPossibleMoves(it.key.surrounding().map { pos -> heightMap[pos] }) // } // // val start = heightMap.values.find { it.start } ?: throw Exception("No start exists!") // val end = heightMap.values.find { it.end } ?: throw Exception("No end exists!") // start.shortestPath = 0 // // val compare: Comparator<Square> = compareBy<Square> { it.letter }.thenBy { it.shortestPath } // val queue = PriorityQueue(compare) // // queue.add(start) // // while (!queue.contains(end)) { // val current = queue.poll() // current.moves.forEach { // if (it.shortestPath > current.shortestPath + 1) it.shortestPath = current.shortestPath + 1 // } // queue.addAll(current.moves.filter { !queue.contains(it) && it.shortestPath >= current.shortestPath + 1 }) // } // // return end.shortestPath //} // //data class Position(val x: Int, val y: Int) { // fun surrounding() = listOf( // Position(x, y + 1), // Position(x + 1, y), // Position(x, y - 1), // Position(x - 1, y) // ) //} // //data class Square(val letter: Char, val position: Position) { // val elevation = when (letter) { // 'S' -> 1 // 'E' -> 26 // else -> letter.code - 96 // } // val start = letter == 'S' // val end = letter == 'E' // var shortestPath = Int.MAX_VALUE // // val moves = mutableListOf<Square>() // // fun calcPossibleMoves(squares: List<Square?>) = // moves.addAll( // squares.filterNotNull().filter { it.elevation <= elevation + 1 }) // // override fun toString(): String { // return "Square $letter: $position -> $shortestPath" // } //} // //fun solveB(input: List<String>): Int { // val heightMap = mutableMapOf<Position, Square>() // // input.forEachIndexed { y, s -> // s.forEachIndexed { x, c -> // val pos = Position(x, y) // val square = Square(c, pos) // heightMap[pos] = square // } // } // // heightMap.entries.forEach { // it.value.calcPossibleMoves(it.key.surrounding().map { pos -> heightMap[pos] }) // } // // val end = heightMap.values.find { it.end } ?: throw Exception("No end exists!") // // return heightMap.values.filter { it.elevation == 1 }.map { // val path = doStuff(it, end) // // heightMap.values.forEach { it.shortestPath = Int.MAX_VALUE } // path // }.min() //} // //fun doStuff(start: Square, end: Square): Int { // start.shortestPath = 0 // // val compare: Comparator<Square> = compareBy<Square> { it.letter }.thenBy { it.shortestPath } // val queue = PriorityQueue(compare) // // queue.add(start) // // while (!queue.contains(end) && queue.isNotEmpty()) { // val current = queue.poll() // current.moves.forEach { // if (it.shortestPath > current.shortestPath + 1) it.shortestPath = current.shortestPath + 1 // } // queue.addAll(current.moves.filter { !queue.contains(it) && it.shortestPath >= current.shortestPath + 1 }) // } // // return end.shortestPath //}
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
5,954
advent-of-code-2022
Apache License 2.0
src/main/kotlin/net/wrony/aoc2023/a1/Main.kt
kopernic-pl
727,133,267
false
{"Kotlin": 52043}
package net.wrony.aoc2023.a1 import arrow.core.flatten import kotlin.io.path.Path import kotlin.io.path.readText fun solution1a(input: String): Int { val lines = arrayListOf<Int>() fun findFirstDigit(s: String): Int = s.first { it.isDigit() }.digitToInt() fun findLastDigit(s: String): Int = s.last { it.isDigit() }.digitToInt() input.lines().forEach { lines.add(findFirstDigit(it) * 10 + findLastDigit(it)) } return lines.sum() } fun solution1b(input: String): Int { val wordsanddigits2digits: Map<String, Int> = 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 ) fun wordPositions(s: String): List<Pair<Int, Int>> { return wordsanddigits2digits.map { (word, digit) -> Regex(word).findAll(s).map { it.range.first to digit }.toList() }.flatten().sortedBy { it.first } } return input.lines().map { s -> s to wordPositions(s) } .map { (s, positions) -> s to positions.map { it.second } } .map { (s, digits) -> s to 10 * digits.first() + digits.last() }.sumOf { it.second } } fun main() { println(solution1a(Path("src/main/resources/1.txt").readText())) println(solution1b(Path("src/main/resources/1.txt").readText())) }
0
Kotlin
0
0
1719de979ac3e8862264ac105eb038a51aa0ddfb
1,530
aoc-2023-kotlin
MIT License
src/Day05.kt
peterfortuin
573,120,586
false
{"Kotlin": 22151}
import java.util.* data class MoveInstruction(val amount: Int, val from: Int, val to: Int) fun main() { fun parseInput(input: List<String>): Pair<List<Stack<Char>>, List<MoveInstruction>> { val stacks = listOf( Stack<Char>(), Stack<Char>(), Stack<Char>(), Stack<Char>(), Stack<Char>(), Stack<Char>(), Stack<Char>(), Stack<Char>(), Stack<Char>() ) val moveInstructions = mutableListOf<MoveInstruction>() input.forEach { line -> when { line.contains("[") -> { if (line.isNotEmpty() && line[1] != ' ') stacks[0].push(line[1]) if (line.length > 3 && line[5] != ' ') stacks[1].push(line[5]) if (line.length > 7 && line[9] != ' ') stacks[2].push(line[9]) if (line.length > 11 && line[13] != ' ') stacks[3].push(line[13]) if (line.length > 15 && line[17] != ' ') stacks[4].push(line[17]) if (line.length > 19 && line[21] != ' ') stacks[5].push(line[21]) if (line.length > 23 && line[25] != ' ') stacks[6].push(line[25]) if (line.length > 27 && line[29] != ' ') stacks[7].push(line[29]) if (line.length > 31 && line[33] != ' ') stacks[8].push(line[33]) } line.startsWith("move") -> { val parts = line.split(" ") val amount = parts[1].toInt() val from = parts[3].toInt() val to = parts[5].toInt() moveInstructions.add(MoveInstruction(amount, from, to)) } } } stacks.map { it.reverse() } return Pair(stacks, moveInstructions) } fun part1(input: List<String>): String { val (stacks, moveInstructions) = parseInput(input) moveInstructions.forEach { move -> val fromStack = stacks[move.from - 1] val toStack = stacks[move.to - 1] repeat(move.amount) { toStack.push(fromStack.pop()) } } return stacks.map<Stack<Char>, Any> { it.lastOrNull() ?: "" }.joinToString("") } fun part2(input: List<String>): String { val (stacks, moveInstructions) = parseInput(input) moveInstructions.forEach { move -> val fromStack = stacks[move.from - 1] val toStack = stacks[move.to - 1] val moveItems = mutableListOf<Char>() repeat(move.amount) { moveItems.add(fromStack.pop()) } moveItems.reverse() moveItems.forEach { item -> toStack.push(item) } } return stacks.map<Stack<Char>, Any> { it.lastOrNull() ?: "" }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println("Part 1 = ${part1(input)}") println("Part 2 = ${part2(input)}") }
0
Kotlin
0
0
c92a8260e0b124e4da55ac6622d4fe80138c5e64
3,234
advent-of-code-2022
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2020/Day24.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.addTo /** * --- Day 24: Lobby Layout --- * https://adventofcode.com/2020/day/24 */ class Day24 : Solver { // Ordered from shortest to longest key! private val directions = mapOf( "w" to XY(-2, 0), "e" to XY(2, 0), "ne" to XY(1, 1), "nw" to XY(-1, 1), "se" to XY(1, -1), "sw" to XY(-1, -1)) override fun solve(lines: List<String>): Result { var tiles = mutableSetOf<XY>() for (line in lines) processLine(line).apply { if (this !in tiles) tiles.add(this) else tiles.remove(this) } val resultA = tiles.size for (i in 1..100) { val newTiles = mutableSetOf<XY>() val min = XY(tiles.map { it.x }.min()!!, tiles.map { it.y }.min()!!) val max = XY(tiles.map { it.x }.max()!!, tiles.map { it.y }.max()!!) for (x in min.x - 2..max.x + 2) { for (y in min.y - 2..max.y + 2) { val count = directions.values.count { XY(x + it.x, y + it.y) in tiles } val pos = XY(x, y) if ((pos in tiles && (count != 0 && count <= 2)) || (pos !in tiles && count == 2)) { newTiles.add(pos) } } } tiles = newTiles } return Result("$resultA", "${tiles.size}") } private fun processLine(line: String): XY { val pos = XY(0, 0) var idx = 0 while (idx < line.length) { for (d in directions.keys) { // LinkedHashMap keeps order of keys! if (line.startsWith(d, idx)) { pos.addTo(directions[d]!!) idx += d.length break; } } } return pos } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,689
euler
Apache License 2.0
src/day_02/Day02.kt
BrumelisMartins
572,847,918
false
{"Kotlin": 32376}
package day_02 import readInput fun main() { fun getMatchScore(elfGesture: Gesture, myGesture: Gesture): Int { return if (myGesture.betterThan == elfGesture.id) { 6 } else if (myGesture == elfGesture) { 3 } else { 0 } } fun getTotalScore(listOfGestures: List<Pair<Gesture?, Gesture?>>): Int { var sum = 0 listOfGestures.forEach { val elfGesture = it.first val myGesture = it.second if (elfGesture == null || myGesture == null) return@forEach sum += getMatchScore(elfGesture, myGesture) + myGesture.score } return sum } fun convertStringListToGesturePairs( rawList: List<String>, useSecretElfCode: Boolean ): List<Pair<Gesture?, Gesture?>> { val listOfGestures = rawList.map { raw -> val newList = raw.split(" ") val elfGesture = newList.first() .toGesture() val myGesture = if (useSecretElfCode) { newList.last() .toGestureFromCode(elfGesture) } else { newList.last() .toGesture() } Pair(elfGesture, myGesture) } return listOfGestures } fun part1(input: List<String>): Int { val convertedList = convertStringListToGesturePairs(input, false) return getTotalScore(convertedList) } fun part2(input: List<String>): Int { val convertedList = convertStringListToGesturePairs(input, true) return getTotalScore(convertedList) } // test if implementation meets criteria from the description, like: val testInput = readInput("day_02/Day02_test") check(part1(testInput) == 15) val input = readInput("day_02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3391b6df8f61d72272f07b89819c5b1c21d7806f
1,906
aoc-2022
Apache License 2.0
src/Day07/Day07.kt
Trisiss
573,815,785
false
{"Kotlin": 16486}
fun main() { fun populateSizes(lines: List<String>): Map<String, Int> = buildMap { put("", 0) var cwd = "" for (line in lines) { val match = PATTERN.matchEntire(line) ?: continue match.groups[1]?.value?.let { dir -> cwd = when (dir) { "/" -> "" ".." -> cwd.substringBeforeLast('/', "") else -> if (cwd.isEmpty()) dir else "$cwd/$dir" } } ?: match.groups[2]?.value?.toIntOrNull()?.let { size -> var dir = cwd while (true) { put(dir, getOrElse(dir) { 0 } + size) if (dir.isEmpty()) break dir = dir.substringBeforeLast('/', "") } } } } fun part1(input: List<String>): Int = populateSizes(input).values.sumOf { if (it <= 10_0000) it else 0 } fun part2(input: List<String>): Int { val sizes = populateSizes(input) val total = sizes.getValue("") return sizes.values.filter { 70_000_000 - (total - it) >= 30_000_000 }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07/Day07_test") val p1result = part1(testInput) // println(p1result) check(p1result == 95437) val p2result = part2(testInput) // println(p2result) check(p2result == 24933642) val input = readInput("Day07/Day07") println(part1(input)) println(part2(input)) } private val PATTERN = """[$] cd (.*)|(\d+).*""".toRegex()
0
Kotlin
0
0
cb81a0b8d3aa81a3f47b62962812f25ba34b57db
1,607
AOC-2022
Apache License 2.0
src/main/kotlin/08-aug.kt
aladine
276,334,792
false
{"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511}
class Solution08Aug { private var ans = 0 private fun pathSumHelper(root: TreeNode, sum: Int, s: MutableMap<Int,Int>){ val v = root.`val` val newS = mutableMapOf<Int,Int>() s.forEach { newS[it.key+v] = it.value } newS[v] = newS.getOrDefault(v, 0)+ 1 if(newS.contains(sum)) { ans+= newS[sum]!! if(newS[sum]==1) newS.remove(sum) else newS[sum] = newS[sum]!!-1 } root.left?.let{ pathSumHelper(it, sum, newS) } root.right?.let{ pathSumHelper(it, sum, newS) } } // Path Sum III fun pathSum(root: TreeNode?, sum: Int): Int { if(root==null) return 0 val sumSet = mutableMapOf<Int,Int>() ans = 0 pathSumHelper(root, sum, sumSet) return ans } } // //fun main() { // val s = Solution08Aug() // s.pathSum() //[0,0,-3,3,2,null,11,3,-3,null,1] //0 //} /* fun pathSum(root: TreeNode?, sum: Int): Int { val preSum: HashMap<Int?, Int?> = HashMap<Any?, Any?>() preSum[0] = 1 return helper(root, 0, sum, preSum) } fun helper(root: TreeNode?, currSum: Int, target: Int, preSum: HashMap<Int?, Int>): Int { var currSum = currSum if (root == null) { return 0 } currSum += root.`val` var res = preSum.getOrDefault(currSum - target, 0) preSum[currSum] = preSum.getOrDefault(currSum, 0) + 1 res += helper(root.left, currSum, target, preSum) + helper(root.right, currSum, target, preSum) preSum[currSum] = preSum[currSum]!! - 1 return res }*/ /* fun pathSum(root: TreeNode?, target: Int): Int { val sumPath = mutableMapOf(0 to 1) fun pathSumHelper(node: TreeNode?, currentSum: Int): Int { node ?: return 0 val sum = currentSum + node.`val` var totalPath = sumPath[sum - target] ?: 0 sumPath.compute(sum) { _, value -> (value ?: 0) + 1 } totalPath += pathSumHelper(node.left, sum) + pathSumHelper(node.right, sum) sumPath.compute(sum) { _, value -> (value ?: 1) - 1 } return totalPath } return pathSumHelper(root, 0) } */ /* private fun preorder(node: TreeNode?, sum: Int, target: Int) { if(node == null) return var currSum = sum + node.`val` if(currSum == target) count++ if(map.contains(currSum - target)) { count += map[currSum - target]!! } map[currSum] = map.getOrDefault(currSum, 0) + 1 preorder(node.left, currSum, target) preorder(node.right, currSum, target) map[currSum] = map[currSum]!! - 1 } */
0
C++
1
1
54b7f625f6c4828a72629068d78204514937b2a9
2,683
awesome-leetcode
Apache License 2.0
src/year_2022/day_21/Day21.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_21 import readInput enum class Operation { PLUS, MINUS, MULTIPLY, DIVIDE, ; companion object { fun from(char: Char): Operation { return when (char) { '+' -> PLUS '-' -> MINUS '*' -> MULTIPLY '/' -> DIVIDE else -> throw IllegalArgumentException() } } } val char: String get() { return when (this) { PLUS -> "+" MINUS -> "-" MULTIPLY -> "*" DIVIDE -> "/" } } fun evaluate(a: Long, b: Long): Long { return when (this) { PLUS -> a + b MINUS -> a - b MULTIPLY -> a * b DIVIDE -> a / b } } fun evaluateInverse(a: Long, b: Long, aIsHumn: Boolean): Long { return when (this) { PLUS -> a - b MINUS -> if (aIsHumn) a + b else b - a MULTIPLY -> a / b DIVIDE -> a * b } } } sealed class Monkey(val id: String) { data class Number( val _id: String, val value: Long ): Monkey(id = _id) data class Operation( val _id: String, val monkeyAId: String, val operation: year_2022.day_21.Operation, val monkeyBId: String ): Monkey(id = _id) } sealed class Equation { data class Value( val monkey: Monkey.Number ): Equation() { override fun toString(): String { return "${monkey.value}" } } data class Evaluation(val e1: Equation, val operation: Operation, val e2: Equation): Equation() { override fun toString(): String { return "($e1 ${operation.char} $e2)" } } object Human: Equation() { override fun toString(): String { return "HUMAN_VALUE" } } fun solve(): Long { return when(this) { is Value -> monkey.value is Evaluation -> { operation.evaluate(e1.solve(), e2.solve()) } is Human -> { throw IllegalArgumentException("Cannot solve for human") } } } } class Day21(text: List<String>){ private val monkeys = parseMonkeys(text) /** * @return */ fun solutionOne(): Long { val monkeyYells = yell() return monkeyYells["root"] ?: -1 } /** * @return */ fun solutionTwo(): Long { val root = monkeys["root"] as Monkey.Operation // Left side has the monkey... so right side can be evaluated val rightEquation = getEquation(root.monkeyBId) val rightSolution = rightEquation.solve() val values = mutableMapOf<String, Long>() return solveForHumn(root.monkeyAId, rightSolution, monkeys, values) } private fun parseMonkeys(text: List<String>): Map<String, Monkey> { return text.map { line -> val split = line.split(": ") val id = split[0] val splitAgain = split[1].split(" ") if (splitAgain.size == 3) { Monkey.Operation( _id = id, monkeyAId = splitAgain[0], operation = Operation.from(splitAgain[1].first()), monkeyBId = splitAgain[2] ) } else { Monkey.Number( _id = id, value = Integer.parseInt(split[1]).toLong() ) } }.associateBy { monkey -> monkey.id } } private fun yell(): Map<String, Long> { val monkeyYells = mutableMapOf<String, Long>() val nonYelledMonkeys = monkeys.values .filterIsInstance<Monkey.Operation>() .toMutableSet() monkeys.values .filterIsInstance<Monkey.Number>() .forEach { monkey -> // println("Monkey ${monkey.id} yells ${monkey.value}") monkeyYells[monkey.id] = monkey.value } while (nonYelledMonkeys.isNotEmpty()) { val monkey = nonYelledMonkeys.first { monkey -> monkeyYells.contains(monkey.monkeyAId) && monkeyYells.contains(monkey.monkeyBId) } val aYell = monkeyYells[monkey.monkeyAId] val bYell = monkeyYells[monkey.monkeyBId] // println("Monkey ${monkey.id} checks ${monkey.monkeyAId} - gets value $aYell and ${monkey.monkeyBId} - gets value $bYell") if (aYell != null && bYell != null) { val value = monkey.operation.evaluate(aYell, bYell) // println("Monkey ${monkey.id} yells $value") monkeyYells[monkey.id] = value nonYelledMonkeys.remove(monkey) } } return monkeyYells } private fun getEquation(id: String): Equation { return when (val monkey = monkeys[id]!!) { is Monkey.Number -> { if (id == "humn") { Equation.Human } else { Equation.Value(monkey) } } is Monkey.Operation -> { Equation.Evaluation( e1 = getEquation(monkey.monkeyAId), operation = monkey.operation, e2 = getEquation(monkey.monkeyBId) ) } } } private fun solveForHumn(id: String, expectedValue: Long, monkeys: Map<String, Monkey>, values: MutableMap<String, Long>): Long { if (id == "humn") { return expectedValue } return when (val monkey = monkeys[id]!!) { is Monkey.Number -> monkey.value is Monkey.Operation -> { val (humnMonkey, otherMonkey) = whichMonkeyLeadsToHumn(monkey.monkeyAId, monkey.monkeyBId, monkeys) val knownValue = solveFor(otherMonkey, monkeys, values) val newExpectedValue = monkey.operation.evaluateInverse(expectedValue, knownValue, humnMonkey == monkey.monkeyAId) solveForHumn(humnMonkey, newExpectedValue, monkeys, values) } } } private fun whichMonkeyLeadsToHumn(lhs: String, rhs: String, monkeys: Map<String, Monkey>): Pair<String, String> { return if (leadsToHumn(lhs, monkeys)) { Pair(lhs, rhs) } else { Pair(rhs, lhs) } } private fun leadsToHumn(id: String, monkeys: Map<String, Monkey>): Boolean { if (id == "humn") { return true } return when (val monkey = monkeys[id]!!) { is Monkey.Number -> false is Monkey.Operation -> leadsToHumn(monkey.monkeyAId, monkeys) || leadsToHumn(monkey.monkeyBId, monkeys) } } private fun solveFor(id: String, monkeys: Map<String, Monkey>, values: MutableMap<String, Long>): Long { val value = values[id] if (value is Long) { return value } return when (val monkey = monkeys[id]!!) { is Monkey.Number -> monkey.value is Monkey.Operation -> { val lhs = values[monkey.monkeyAId] ?: solveFor(monkey.monkeyAId, monkeys, values) val rhs = values[monkey.monkeyBId] ?: solveFor(monkey.monkeyBId, monkeys, values) val result = monkey.operation.evaluate(lhs, rhs) values[id] = result result } } } } fun main() { val inputText = readInput("year_2022/day_21/Day21.txt") val day21 = Day21(inputText) val solutionOne = day21.solutionOne() println("Solution 1: $solutionOne") val solutionTwo = day21.solutionTwo() println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
7,894
advent_of_code
Apache License 2.0
src/day03/Day03.kt
violabs
576,367,139
false
{"Kotlin": 10620}
package day03 import readInput fun main() { test1("day-03-test-input-01", 157) test2("day-03-test-input-01", 70) } private fun test1(filename: String, expected: Int) { val input = readInput("day03/$filename") val actual: Int = checkRucksacksForDuplicateItems(input) println("EXPECT: $expected") println("ACTUAL: $actual") check(expected == actual) } private fun test2(filename: String, expected: Int) { val input = readInput("day03/$filename") val actual: Int = checkGroupRucksackBadges(input) println("EXPECT: $expected") println("ACTUAL: $actual") check(expected == actual) } val priority = ('a' .. 'z') + ('A' .. 'Z') fun checkRucksacksForDuplicateItems(ledger: List<String>): Int { return ledger .asSequence() .map(::Rucksack) .flatMap(Rucksack::findDuplicates) .map(priority::indexOf) .map(1::plus) .sum() } class Rucksack(contents: String) { private val capacity: Int = contents.length private val half = capacity / 2 private val firstCompartment: String = contents.substring(0 until half) private val secondCompartment: String = contents.substring(half until capacity) fun findDuplicates(): Sequence<Char> = firstCompartment .asSequence() .filter(secondCompartment::contains) .distinct() } fun checkGroupRucksackBadges(ledger: List<String>): Int { return ledger .asSequence() .chunked(3) .map(::ElfGroup) .map(ElfGroup::findBadgeSymbol) .map(priority::indexOf) .map(1::plus) .sum() } class ElfGroup(rucksacks: List<String>) { private val sortedSacks: List<String> = rucksacks.sortedBy(String::length) private val smallestSack = sortedSacks[0] private val sack2 = sortedSacks[1] private val sack3 = sortedSacks[2] fun findBadgeSymbol(): Char = smallestSack .firstOrNull { sack2.contains(it) && sack3.contains(it) } ?: throw Exception("Missing badge") }
0
Kotlin
0
0
be3d6bb2aef1ebd44bbd8e62d3194c608a5b3cc1
2,052
AOC-2022
Apache License 2.0
src/Day04.kt
Oli2861
572,895,182
false
{"Kotlin": 16729}
fun getPairs(lines: List<String>): List<Pair<IntRange, IntRange>> = lines.map { getPairs(it) } fun getPairs(line: String): Pair<IntRange, IntRange> { val numbers: List<Int> = line.split(Regex("[^0-9]+")).map { Integer.parseInt(it) } return Pair(IntRange(numbers[0], numbers[1]), IntRange(numbers[2], numbers[3])) } fun isFullyContained(pair: Pair<IntRange, IntRange>): Boolean { val (first, second) = pair val secondFullyContainedInFirst = first.contains(second.first) && first.contains(second.last) val firstFullyContainedInSecond = second.contains(first.first) && second.contains(first.last) return secondFullyContainedInFirst || firstFullyContainedInSecond } fun isOverlapping(pair: Pair<IntRange, IntRange>): Boolean { val (first, second) = pair val secondOverlapsFirst = first.contains(second.first) || first.contains(second.last) val firstOverlapsSecond = second.contains(first.first) || second.contains(first.last) return secondOverlapsFirst || firstOverlapsSecond } fun amountOfPairsMatchingCondition(lines: List<String>, condition: (Pair<IntRange, IntRange>) -> Boolean): Int = getPairs(lines).map { condition(it) }.filter { it }.size fun amountOfContainedPairs(lines: List<String>): Int = amountOfPairsMatchingCondition(lines, ::isFullyContained) fun amountOfOverlappingPairs(lines: List<String>): Int = amountOfPairsMatchingCondition(lines, ::isOverlapping) fun main() { val input = readInput("Day04_test") val result = amountOfContainedPairs(input) println(result) check(result == 556) val result2 = amountOfOverlappingPairs(input) println(result2) check(result2 == 876) }
0
Kotlin
0
0
138b79001245ec221d8df2a6db0aaeb131725af2
1,666
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day16.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import java.lang.Integer.max import java.math.BigInteger fun main() { val input = {}.javaClass.getResource("input-16.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val testInput = {}.javaClass.getResource("input-16-1.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val test = Day16(testInput) val day = Day16(input) println(test.part1()) println(test.part2()) println(day.part1()) println(day.part2()) } class Day16(input: List<String>) { private val valves: Map<String, Valve> private val paths: Map<Valve, Map<Valve, Int>> init { valves = input.associate { val name = it.substringAfter("Valve ").substringBefore(" has") val rate = it.substringAfter("=").substringBefore(";").toInt() name to Valve(name, rate = rate) } paths = Graph(input.associate { val name = it.substringAfter("Valve ").substringBefore(" has") val edges = it.substringAfter("to valve").split(", ") valves[name]!! to edges.associate { valves[it.filter { it.isUpperCase() }]!! to 1 } }).findAllShortestPath().map { (k, v) -> k to v.filter { it.key.rate > 0 } }.toMap() } fun part1(): Int { val volcano = Volcano(paths, valves["AA"]!!) volcano.findHighestDeltaP() println(volcano.counter) return volcano.pressure } fun part2(): Int { val volcano = Volcano(paths, valves["AA"]!!, 26) volcano.findHighestDeltaP(secondPass = true) println(volcano.counter) return volcano.pressure } } class Volcano(private val paths: Map<Valve, Map<Valve, Int>>, private val start: Valve, private val timeToBlow: Int = 30) { var pressure = 0 var counter: BigInteger = BigInteger.ZERO fun findHighestDeltaP(from: Valve = start, cache: Set<Valve> = mutableSetOf(), deltaT: Int = 0, deltaP: Int = 0, secondPass: Boolean = false) { pressure = max(pressure, deltaP) counter++ paths[from]!! .filter { (destination, distance) -> (!cache.contains(destination) && deltaT + distance + 1 < timeToBlow) } .forEach() { (destination, distance) -> findHighestDeltaP( from = destination, cache = cache + destination, deltaT = deltaT + 1 + distance, deltaP = deltaP + (timeToBlow - deltaT - distance - 1) * destination.rate, secondPass ) } if (secondPass) findHighestDeltaP(start, cache, deltaP = deltaP) } } data class Valve(val name: String, var rate: Int = 0)
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
2,700
aoc202xkotlin
The Unlicense
src/test/kotlin/de/tek/adventofcode/y2022/util/algorithms/SetAlgorithmsTest.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.util.algorithms import io.kotest.core.spec.style.StringSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder class SubsetsTest : StringSpec({ "Given set of integers, combinations returns all subsets." { val set = setOf(1, 2, 3) set.subsets() shouldContainExactlyInAnyOrder listOf( emptySet(), setOf(1), setOf(2), setOf(3), setOf(1, 2), setOf(1, 3), setOf(2, 3), setOf(1, 2, 3) ) } }) class PermutationsTest : StringSpec({ "Given set of integers, permutations returns all permutations of that set." { val set = setOf(3, 2, 1) set.permutations().map { it.first }.toList() shouldContainExactlyInAnyOrder listOf( listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1) ) } "Given set of integers, permutations returns an empty set as second components." { val set = setOf(3, 2, 1) set.permutations().map { it.second }.toList() shouldContainExactlyInAnyOrder List(6) { emptySet() } } "Given set of integers and pruneBy as sum is bigger than x, permutations returns only expected permutations of the set." { forAll( row( setOf(3, 2, 1), 3, listOf( listOf(1, 2), listOf(1), listOf(2, 1), listOf(2), listOf(3) ) ), row( setOf(4, 3, 2, 1), 6, listOf( listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1), listOf(1, 4), listOf(4, 1), listOf(2, 4), listOf(4, 2), listOf(4) ) ) ) { set, limit, expectedResult -> set.permutations { it.sum() > limit }.map { it.first } .toList() shouldContainExactlyInAnyOrder expectedResult } } "Given set of integers and pruneBy as sum is bigger than x, permutations returns as second components the elements" + "in the set that are not part of the permutation." { forAll( row( setOf(3, 2, 1), 3, listOf( setOf(3), setOf(2, 3), setOf(3), setOf(1, 3), setOf(1, 2), ) ), row( setOf(4, 3, 2, 1), 6, listOf( emptySet(), emptySet(), emptySet(), emptySet(), emptySet(), emptySet(), setOf(2, 3), setOf(2, 3), setOf(1, 3), setOf(1, 3), setOf(1, 2, 3) ) ) ) { set, limit, expectedResult -> set.permutations { it.sum() > limit }.map { it.second } .toList() shouldContainExactlyInAnyOrder expectedResult } } })
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
3,727
advent-of-code-2022
Apache License 2.0
2023/src/main/kotlin/day22.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Cuboid import utils.MutableIntSpace import utils.Parser import utils.Point3i import utils.Solution import utils.Vec4i import utils.bounds import utils.cut import utils.map import utils.mapItems fun main() { Day22.run() } object Day22 : Solution<List<Cuboid>>() { override val name = "day22" override val parser = Parser.lines.mapItems { val (start, end) = it.cut("~").map(::parseVec4i) Cuboid(start, end) } fun parseVec4i(input: String): Vec4i { val (x, y, z) = input.split(",").map { it.toInt() } return Point3i(x, y, z) } override fun part1(): Int { val restsOn = getRestsGraph() val safeToDisintegrate = mutableSetOf<Int>() safeToDisintegrate.addAll(input.indices) restsOn.forEach { ints -> if (ints.size == 1) { // sole support for some brick safeToDisintegrate.remove(ints.first()) } } return safeToDisintegrate.size } override fun part2(): Int { val restsOn = getRestsGraph() // flip the restsOn graph val supports = Array(input.size) { mutableSetOf<Int>() } restsOn.forEachIndexed { index, supportingBricks -> supportingBricks.forEach { support -> supports[support] += index } } val supportingBricks = restsOn.filter { it.size == 1 }.map { it.first() }.toSet() val painted = Array(input.size) { mutableSetOf<Int>() } supportingBricks.forEach { supportBrick -> val queue = ArrayDeque(supports[supportBrick].filter { restsOn[it].size == 1 }) while (queue.isNotEmpty()) { val brick = queue.removeFirst() painted[supportBrick] += brick queue.addAll(supports[brick].filter { restsOn[it].all { b -> b in painted[supportBrick] } }) } } val sum = painted.sumOf { it.size } return sum } private fun getRestsGraph(): Array<Set<Int>> { val bounds = input.flatMap { listOf(it.start, it.end) }.bounds.second val space = MutableIntSpace(bounds.x + 1, bounds.y + 1, bounds.z + 1) { -1 } val sortedBricks = input.sortedBy { minOf(it.start.z, it.end.z) } val restsOn = Array<Set<Int>>(sortedBricks.size) { emptySet() } sortedBricks.forEachIndexed { index, brick -> var z = minOf(brick.start.z, brick.end.z) while (z > 1) { restsOn[index] = brick.projection.map { space[Point3i(it.x, it.y, z - 1)] }.filter { it != -1 }.toSet() if (restsOn[index].isNotEmpty()) { // existing brick breaks the fall break } z-- } val zoff = z - minOf(brick.start.z, brick.end.z) // place brick for (p in brick.units) { space[p + Point3i(0, 0, zoff)] = index } } return restsOn } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,707
aoc_kotlin
MIT License
src/Day02.kt
haraldsperre
572,671,018
false
{"Kotlin": 17302}
enum class Hand(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3) } fun Hand.beats(): Hand { return when (this) { Hand.ROCK -> Hand.SCISSORS Hand.PAPER -> Hand.ROCK Hand.SCISSORS -> Hand.PAPER } } fun Hand.beatenBy(): Hand { return when (this) { Hand.ROCK -> Hand.PAPER Hand.PAPER -> Hand.SCISSORS Hand.SCISSORS -> Hand.ROCK } } fun getHand(input: Char): Hand { return when (input) { 'A', 'X' -> Hand.ROCK 'B', 'Y' -> Hand.PAPER 'C', 'Z' -> Hand.SCISSORS else -> throw Exception("Invalid input") } } fun scoreMatch(opponent: Hand, you: Hand): Int { return when (opponent) { you.beats() -> 6 you.beatenBy() -> 0 else -> 3 } } fun main() { fun part1(input: List<String>): Int { return input.sumOf { match -> val (opponent, you) = (getHand(match[0]) to getHand(match[2])) scoreMatch(opponent, you) + you.value } } fun part2(input: List<String>): Int { return input.sumOf { match -> val opponent = getHand(match[0]) val you = when (match[2]) { 'X' -> opponent.beats() 'Y' -> opponent 'Z' -> opponent.beatenBy() else -> throw Exception("Invalid input") } scoreMatch(opponent, you) + you.value } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c4224fd73a52a2c9b218556c169c129cf21ea415
1,706
advent-of-code-2022
Apache License 2.0
src/day07/Day07.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day07 import readInput fun main(){ val fileSystem = readInput("day07") val directory = parseFileSystem(Directory(name = "root"), fileSystem) println(partOne(directory)) val totalSpace = 70000000 val unusedSpaceNeeded = 30000000 println(partTwo(directory, totalSpace, unusedSpaceNeeded).calculateSize()) } private fun partTwo(directory: Directory, totalDiskSize: Int, spaceNeededSize: Int): Directory { val allDirectories = directory.getAllDirectories() val directorySize = directory.calculateSize() val spaceAvailable = totalDiskSize - directorySize val spaceToMakeUp = spaceNeededSize - spaceAvailable val directoriesSuitableForDeletion = allDirectories.filter { it.calculateSize() >= spaceToMakeUp } return directoriesSuitableForDeletion.minBy { it.calculateSize() } } private fun partOne(directory: Directory): Int { val filter = directory.getAllDirectories().filter { it.calculateSize() <= 100000 } return filter.sumOf { it.calculateSize() } } private fun parseFileSystem(rootDirectory: Directory, fileSystem: List<String>): Directory { var workingDirectory = rootDirectory fileSystem.drop(1).forEach { terminalOutput -> if (terminalOutput.substring(0, 4) == "$ cd") { if (terminalOutput.substringAfter("$ cd ") == "..") { if (workingDirectory.parentDirectory != null) { workingDirectory = workingDirectory.parentDirectory!! } } else { val directoryName = terminalOutput.substringAfter("$ cd ") if (workingDirectory.subdirectories.contains(directoryName)) { workingDirectory = workingDirectory.subdirectories[directoryName]!! } } } // Handle adding subdirectories or files if (terminalOutput.substring(0, 3) == "dir") { val directoryName = terminalOutput.substringAfter("dir ") val childDirectory = Directory(name = directoryName) childDirectory.parentDirectory = workingDirectory workingDirectory.subdirectories[directoryName] = childDirectory } else if (terminalOutput.first().isDigit()) { val file = terminalOutput.split(" ") val fileSize = file.first() val fileName = file.last() workingDirectory.files.add(File(fileName, fileSize.toInt())) } } return rootDirectory } data class Directory( val name: String, val files: MutableList<File> = mutableListOf(), val subdirectories: MutableMap<String, Directory> = mutableMapOf()){ var parentDirectory: Directory? = null fun calculateSize() : Int { return files.sumOf { it.size } + if(subdirectories.isNotEmpty()) subdirectories.values.sumOf { it.calculateSize() } else 0 } fun getAllDirectories(): List<Directory>{ val result = mutableListOf<Directory>() result.add(this) this.subdirectories.forEach { (_, value) -> result.addAll(value.getAllDirectories()) } return result } } data class File(val name: String, val size: Int)
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
3,166
advent-of-code-kotlin-2022
Apache License 2.0