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/questions/DegreeOfAnArray.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.util.* /** * Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. * Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. * * [Source](https://leetcode.com/problems/degree-of-an-array/) */ @UseCommentAsDocumentation private fun findShortestSubArray(nums: IntArray): Int { val counts = TreeMap<Int, MutableList<Int>>() val priorityList = PriorityQueue<ValueWithOccurrence> { o1, o2 -> o2.count - o1.count } for (i in 0..nums.lastIndex) { val value = nums[i] counts[value] = counts.getOrDefault(value, mutableListOf()).also { it.add(i) } priorityList.add(ValueWithOccurrence(value, counts[value]!!.size)) } val highestOccurringElement = priorityList.remove() val degree = highestOccurringElement.count val candidates = mutableListOf<Int>() candidates.add(highestOccurringElement.value) // find other highest occurring element while (priorityList.isNotEmpty()) { val nextElement = priorityList.remove() if (nextElement.count == degree) { candidates.add(nextElement.value) } else { break } } var result = Integer.MAX_VALUE for (i in candidates) { val range = counts[i]!! // find the smallest subarray result = minOf(result, range.last() - range.first() + 1) } return result } private data class ValueWithOccurrence(val value: Int, val count: Int) fun main() { findShortestSubArray(intArrayOf(1, 1, 3, 3, 2, 2, 2, 3, 1)) shouldBe 3 // The input array has a degree of 2 because both elements 1 and 2 appear twice. // Of the subarrays that have the same degree: // [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] // The shortest length is 2. So return 2. findShortestSubArray(intArrayOf(1, 2, 2, 3, 1)) shouldBe 2 // The degree is 3 because the element 2 is repeated 3 times. // So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6. findShortestSubArray(intArrayOf(1, 2, 2, 3, 1, 4, 2)) shouldBe 6 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,315
algorithms
MIT License
src/Day04.kt
davedupplaw
573,042,501
false
{"Kotlin": 29190}
fun main() { fun part1(input: List<String>): Int { return input .asSequence() .map { it.split(",", "-").map { x -> x.toInt() } } .map { listOf(it[0]..it[1], it[2]..it[3]) } .filter { (it[1].first in it[0] && it[1].last in it[0]) || (it[0].first in it[1] && it[0].last in it[1]) } .count() } fun part2(input: List<String>): Int { return input .asSequence() .map { it.split(",", "-").map { x -> x.toInt() } } .map { listOf(it[0]..it[1], it[2]..it[3]) } .filter { it[1].first in it[0] || it[1].last in it[0] || it[0].first in it[1] || it[0].last in it[1] } .count() } val test = readInput("Day04.test") val part1test = part1(test) println("part1 test: $part1test") check(part1test == 2) val part2test = part2(test) println("part2 test: $part2test") check(part2test == 4) val input = readInput("Day04") val part1 = part1(input) println("Part1: $part1") val part2 = part2(input) println("Part2: $part2") }
0
Kotlin
0
0
3b3efb1fb45bd7311565bcb284614e2604b75794
1,212
advent-of-code-2022
Apache License 2.0
src/Day07.kt
kthun
572,871,866
false
{"Kotlin": 17958}
class Folder( val name: String, val subFolders: MutableMap<String, Folder> = mutableMapOf(), var parent: Folder? = null, var myFiles: MutableList<MyFile> = mutableListOf() ) { fun addSubFolder(folder: Folder) { subFolders[folder.name] = folder folder.parent = this folders[folder.fullPath()] = folder } fun size(): Int { return myFiles.sumOf { it.size } + subFolders.values.sumOf { it.size() } } fun fullPath(): String { return if (parent == null) { name } else { parent!!.fullPath() + "/" + name } } fun toString(indent: Int = 0): String { val sb = StringBuilder() sb.append(" ".repeat(indent)) sb.append("- $name (dir, size=${size()})") sb.appendLine() for (folder in subFolders.values.sortedBy { it.name }) { sb.append(folder.toString(indent + 2)) } for (file in myFiles.sortedBy { it.name }) { sb.append(" ".repeat(indent + 2)) sb.append("- ${file.name} (file, size=${file.size})") sb.appendLine() } return sb.toString() } override fun toString() = toString(0) } var folders = mutableMapOf<String, Folder>() data class MyFile(val name: String, val size: Int) fun main() { fun parseFileStructure(input: List<String>): Folder { folders.clear() val root = Folder("/") folders["/"] = root var currentDir = root input.forEach { line -> when { line == "$ ls" -> {} // Skip line.startsWith("dir") -> {} // Skip line.startsWith("$ cd /") -> currentDir = root line.startsWith("$ cd ..") -> currentDir = currentDir.parent!! line.startsWith("$ cd") -> { val name = line.substringAfterLast(" ") val folder = Folder(name) currentDir.addSubFolder(folder) currentDir = folder } else -> { val (fileSizeString, fileName) = line.split(" ") currentDir.myFiles.add(MyFile(fileName, fileSizeString.toInt())) } } } return root } fun part1(input: List<String>): Int { val root = parseFileStructure(input) // println(root) val maxFolderSize = 100_000 return folders.values .filter { it.size() <= maxFolderSize } .sumOf { it.size() } } fun part2(input: List<String>): Int { val root = parseFileStructure(input) // println(root) val diskSpace = 70_000_000 val freeSpace = diskSpace - root.size() val spaceNeeded = 30_000_000 - freeSpace return folders.map { it.value.size() } .filter { it >= spaceNeeded } .minByOrNull { it } ?: 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") val input = readInput("Day07") check(part1(testInput) == 95437) println(part1(input)) check(part2(testInput) == 24933642) println(part2(input)) }
0
Kotlin
0
0
5452702e4e20ef2db3adc8112427c0229ebd1c29
3,253
aoc-2022
Apache License 2.0
src/Day12.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
import java.util.* fun main() { class Node( val height: Int, val neighbors: MutableSet<Node> = mutableSetOf(), ) : Comparable<Node> { var distance = Int.MAX_VALUE override fun compareTo(other: Node) = distance.compareTo(other.distance) } fun convertHeight(height: Char) = when (height) { 'S' -> 0 'E' -> 'z' - 'a' else -> height - 'a' } fun parse(input: List<String>, invert: Boolean): Triple<Node, Node, List<Node>> { lateinit var start: Node lateinit var end: Node val graph = input.map { line -> line.toCharArray().map { height -> Node(convertHeight(height)).also { if (height == 'S') start = it; if (height == 'E') end = it } } } for (y in graph.indices) { for (x in graph[y].indices) { val node = graph[y][x] fun addEdgeIfAllowed(y: Int, x: Int) { val neighbor = graph.getOrNull(y)?.getOrNull(x) ?: return if (neighbor.height <= node.height + 1) { if (!invert) { node.neighbors += neighbor } else { neighbor.neighbors += node } } } addEdgeIfAllowed(y - 1, x) addEdgeIfAllowed(y + 1, x) addEdgeIfAllowed(y, x - 1) addEdgeIfAllowed(y, x + 1) } } return Triple(start, end, graph.flatten()) } fun part1(input: List<String>): Int { val (start, end) = parse(input, false) start.distance = 0 val unvisited = PriorityQueue<Node>().apply { add(start) } val visited = mutableSetOf<Node>() while (unvisited.isNotEmpty()) { val node = unvisited.poll() for (neighbor in node.neighbors) { if (neighbor !in visited && neighbor.distance > node.distance + 1) { unvisited.remove(neighbor) neighbor.distance = node.distance + 1 unvisited.add(neighbor) if (neighbor == end) return neighbor.distance } } visited += node } return 0 } fun part2(input: List<String>): Int { val (_, end, graph) = parse(input, true) end.distance = 0 val unvisited = PriorityQueue<Node>().apply { add(end) } val visited = mutableSetOf<Node>() while (unvisited.isNotEmpty()) { val node = unvisited.poll() for (neighbor in node.neighbors) { if (neighbor !in visited && neighbor.distance > node.distance + 1) { unvisited.remove(neighbor) neighbor.distance = node.distance + 1 unvisited.add(neighbor) } } visited += node } return graph.filter { it.height == 0 }.minOf { it.distance } } // 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
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
3,404
AdventOfCode2022
Apache License 2.0
src/main/kotlin/dk/lessor/Day11.kt
aoc-team-1
317,571,356
false
{"Java": 70687, "Kotlin": 34171}
package dk.lessor val chairs: (Char) -> Int = { if (it == '#') 1 else 0 } fun main() { val map = readFile("day_11.txt").map { it.toList() } println(gameOfChairs(map)) println(gameOfVisibleChairs(map)) } fun gameOfChairs(chairMap: List<List<Char>>): Int { var oldMap = chairMap.map { it.toMutableList() }.toMutableList() while (true) { val newMap = oldMap.map { it.toMutableList() }.toMutableList() for (y in 0..oldMap.lastIndex) { val row = oldMap[y] for (x in 0..row.lastIndex) { val type = row[x] if (type == '.') continue if (type == 'L' && !neighbours(oldMap, x, y).any { it == '#' }) newMap[y][x] = '#' else if (type == '#' && neighbours(oldMap, x, y).sumBy { chairs(it) } >= 4) newMap[y][x] = 'L' } } if (newMap == oldMap) break oldMap = newMap } return oldMap.flatten().sumBy { chairs(it) } } fun gameOfVisibleChairs(chairMap: List<List<Char>>): Int { var oldMap = chairMap.map { it.toMutableList() }.toMutableList() while (true) { val newMap = oldMap.map { it.toMutableList() }.toMutableList() for (y in 0..oldMap.lastIndex) { val row = oldMap[y] for (x in 0..row.lastIndex) { val type = row[x] if (type == '.') continue if (type == 'L' && !visibleChairs(oldMap, x, y).any { it == '#' }) newMap[y][x] = '#' else if (type == '#' && visibleChairs(oldMap, x, y).sumBy { chairs(it) } >= 5) newMap[y][x] = 'L' } } if (newMap == oldMap) break oldMap = newMap } return oldMap.flatten().sumBy { chairs(it) } } fun neighbours(chairMap: List<List<Char>>, x: Int, y: Int): List<Char> { val n = chairMap.getOrNull(x, y - 1) val ne = chairMap.getOrNull(x + 1, y - 1) val e = chairMap.getOrNull(x + 1, y) val se = chairMap.getOrNull(x + 1, y + 1) val s = chairMap.getOrNull(x, y + 1) val sw = chairMap.getOrNull(x - 1, y + 1) val w = chairMap.getOrNull(x - 1, y) val nw = chairMap.getOrNull(x - 1, y - 1) return listOfNotNull(n, ne, e, se, s, sw, w, nw) } fun visibleChairs(chairMap: List<List<Char>>, x: Int, y: Int): List<Char> { val n = chairMap.walk(x to y, walkColumn = { it - 1 }) val ne = chairMap.walk(x to y, { it + 1 }, { it - 1 }) val e = chairMap.walk(x to y, walkRow = { it + 1 }) val se = chairMap.walk(x to y, { it + 1 }, { it + 1 }) val s = chairMap.walk(x to y, walkColumn = { it + 1 }) val sw = chairMap.walk(x to y, { it - 1 }, { it + 1 }) val w = chairMap.walk(x to y, walkRow = { it - 1 }) val nw = chairMap.walk(x to y, { it - 1 }, { it - 1 }) return listOfNotNull(n, ne, e, se, s, sw, w, nw) } fun List<List<Char>>.walk(initial: Pair<Int, Int>, walkRow: (Int) -> Int = { it }, walkColumn: (Int) -> Int = { it }): Char? { var (x, y) = initial var current: Char? = '.' while (current != null && current == '.') { x = walkRow(x) y = walkColumn(y) current = getOrNull(x, y) } return current } fun List<List<Char>>.getOrNull(x: Int, y: Int): Char? { return getOrNull(y)?.getOrNull(x) }
0
Java
0
0
48ea750b60a6a2a92f9048c04971b1dc340780d5
3,263
lessor-aoc-comp-2020
MIT License
src/Day03.kt
kecolk
572,819,860
false
{"Kotlin": 22071}
fun main() { fun Char.toPriority(): Int { return when { this.isLowerCase() -> this - 'a' + 1 else -> this - 'A' + 27 } } fun String.toPriorities() = this.toCharArray().map { it.toPriority() }.toSet() fun getErrorPriority(rucksack: String): Int { val compartment1 = rucksack.take(rucksack.length / 2).toPriorities() val compartment2 = rucksack.substring(rucksack.length / 2).toPriorities() return compartment1.intersect(compartment2).firstOrNull() ?: 0 } fun getGroupBadgePriority(group: List<String>): Int { require(group.size == 3) val rucksacks = group.map { rucksack -> rucksack.toPriorities() } return rucksacks[0].intersect(rucksacks[1]).intersect(rucksacks[2]).firstOrNull() ?: 0 } fun part1(input: List<String>): Int = input.sumOf { getErrorPriority(it) } fun part2(input: List<String>): Int = input.chunked(3).sumOf { getGroupBadgePriority(it) } val testInput = readTextInput("Day03_test") val input = readTextInput("Day03") check(part1(testInput) == 157) check(part2(testInput) == 70) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
72b3680a146d9d05be4ee209d5ba93ae46a5cb13
1,196
kotlin_aoc_22
Apache License 2.0
src/Day21.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
private enum class Operator(val apply: (Long, Long) -> Long) { PLUS(Long::plus), MINUS(Long::minus), TIMES(Long::times), DIV(Long::div) } private sealed interface MonkeyNumber { data class Constant(val value: Long) : MonkeyNumber data class Operation(val monkey1: String, val monkey2: String, val operator: Operator) : MonkeyNumber } fun main() { fun String.toOperator() = when (this) { "+" -> Operator.PLUS "-" -> Operator.MINUS "*" -> Operator.TIMES "/" -> Operator.DIV else -> error("$this is no operator") } fun readMonkeys(input: List<String>) = input.associate { line -> val (name, operation) = line.split(": ") name to if (operation.isNumber()) { MonkeyNumber.Constant(operation.toLong()) } else { val (m1, op, m2) = operation.split(' ') MonkeyNumber.Operation(m1, m2, op.toOperator()) } } fun part1(input: List<String>): Long { val monkeys = readMonkeys(input) fun evaluate(monkey: String): Long = monkeys.getValue(monkey).let { when (it) { is MonkeyNumber.Constant -> it.value is MonkeyNumber.Operation -> it.operator.apply(evaluate(it.monkey1), evaluate(it.monkey2)) } } return evaluate("root") } fun part2(input: List<String>): Long { val monkeys = readMonkeys(input) fun hasHuman(monkey: String): Boolean = monkey == "humn" || monkeys.getValue(monkey).let { it is MonkeyNumber.Operation && (hasHuman(it.monkey1) || hasHuman(it.monkey2)) } fun evaluate(monkey: String): Long = monkeys.getValue(monkey).let { when (it) { is MonkeyNumber.Constant -> it.value is MonkeyNumber.Operation -> it.operator.apply(evaluate(it.monkey1), evaluate(it.monkey2)) } } fun solveFor(monkey: String, result: Long): Long { val operation = monkeys.getValue(monkey) as MonkeyNumber.Operation return if (hasHuman(operation.monkey1)) { val operand = evaluate(operation.monkey2) val subResult = when (operation.operator) { Operator.PLUS -> result - operand Operator.MINUS -> result + operand Operator.TIMES -> result / operand Operator.DIV -> result * operand } if (operation.monkey1 == "humn") { subResult } else { solveFor(operation.monkey1, subResult) } } else { val operand = evaluate(operation.monkey1) val subResult = when (operation.operator) { Operator.PLUS -> result - operand Operator.MINUS -> operand - result Operator.TIMES -> result / operand Operator.DIV -> operand / result } if (operation.monkey2 == "humn") { subResult } else { solveFor(operation.monkey2, subResult) } } } val rootOperation = monkeys.getValue("root") as MonkeyNumber.Operation return if (hasHuman(rootOperation.monkey1)) { val result = evaluate(rootOperation.monkey2) solveFor(rootOperation.monkey1, result) } else { val result = evaluate(rootOperation.monkey1) solveFor(rootOperation.monkey2, result) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
3,891
advent-of-code-22
Apache License 2.0
15/src/main/kotlin/se/nyquist/PathFinder.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist import java.io.File import java.util.* fun main() { val lines = File("input.txt").readLines() exercise1(lines) exercise2(lines) } private fun exercise1(lines: List<String>) { val map = lines.map { it.toCharArray().map { c -> c.digitToInt() }.toTypedArray() }.toTypedArray() val finder = PathFinder(map) val route = finder.find() val points = route.route.joinToString(",") { "(${it.first},${it.second})" } println("Min cost: ${route.cost} for route: $points") } // ( private fun exercise2(lines: List<String>) { val map = lines.map { it.toCharArray().map { c -> c.digitToInt() }.toTypedArray() }.toTypedArray() val extendedMap = (0 until 5*map.size) .map { rowFactor -> (0 until 5) .flatMap { columnnFactor -> map[rowFactor % map.size].map { col -> (col - 1 + (rowFactor/map.size + columnnFactor)) % 9 + 1 }}.toTypedArray()}.toTypedArray() val finder = PathFinder(extendedMap) val route = finder.find() val points = route.route.joinToString(",") { "(${it.first},${it.second})" } println("Min cost: ${route.cost} for route: $points") } data class Route(val route: List<Pair<Int,Int>>, val cost: Long) { override fun toString(): String { return "Route(cost=$cost)" } } class PathFinder(private val map : Array<Array<Int>>, private val bestPath : MutableMap<Pair<Int,Int>, Route> = mutableMapOf()) { fun find(): Route { val startpos = Pair(0,0) val endpos = Pair(map[map.lastIndex].lastIndex, map.lastIndex) val routes = routes(endpos, Route(listOf(startpos),0)) return routes.sortedBy { it.cost }.first() } private fun routes(endpos: Pair<Int, Int>, initalRoute: Route) : List<Route> { val comparator : Comparator<Route> = compareBy{ it.cost } val routes = PriorityQueue<Route>(comparator) routes.add(initalRoute) val result = mutableListOf<Route>() while (routes.isNotEmpty()) { val route = routes.remove() val current = route.route.last() if (current == endpos) { result.add(route) } else { routes.addAll(getNewRoutes(current, endpos, route)) } } return result } private fun getNewRoutes( current: Pair<Int, Int>, endpos: Pair<Int, Int>, route: Route ): Collection<Route> { val candidates = mutableListOf<Pair<Int, Int>>() if (current.first < endpos.first) { candidates.add(Pair(current.first + 1, current.second)) } if (current.second < endpos.second) { candidates.add(Pair(current.first, current.second + 1)) } if (current.first > 0) { candidates.add(Pair(current.first - 1, current.second)) } if (current.second > 0) { candidates.add(Pair(current.first, current.second - 1)) } return candidates .filter { !bestPath.containsKey(it) || (bestPath.containsKey(it) && bestPath.getValue(it).cost > route.cost + getCost(it)) } .map { createRoute(route, it) }.toList() } private fun createRoute( route: Route, current: Pair<Int, Int>, ) : Route { val coordinates = route.route.toMutableList() coordinates.add(current) val newCost = route.cost + getCost(current) val newRoute = Route(coordinates, newCost) bestPath[current] = newRoute return newRoute } private fun getCost(it: Pair<Int, Int>): Int { return map[it.first][it.second] } }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
3,763
adventofcode2021
Apache License 2.0
src/Day12.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
private sealed interface Point : Comparable<Point> { val elevation: Int override fun compareTo(other: Point): Int = elevation.compareTo(other.elevation) } private object StartPoint : Point { override val elevation: Int get() = 0 override fun toString(): String = "S" } private object EndPoint : Point { override val elevation: Int get() = 25 override fun toString(): String = "E" } private class NormalPoint(override val elevation: Int) : Point { init { check(elevation in 0..25) } override fun toString(): String = ('a' + elevation).toString() } fun main() { data class Coordinate(val row: Int, val col: Int) fun Coordinate.neighbors() = listOf(copy(row = row - 1), copy(row = row + 1), copy(col = col - 1), copy(col = col + 1)) fun readHeightMap(input: List<String>) = Array(input.size) { row -> Array(input[row].length) { col -> input[row][col].let { when (it) { 'S' -> StartPoint 'E' -> EndPoint else -> NormalPoint(it - 'a') } } } } fun Point.canReach(other: Point) = other.elevation <= elevation + 1 fun findStartCoordinate(heightMap: Array<Array<Point>>): Coordinate { heightMap.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, point -> if (point == StartPoint) { return Coordinate(rowIndex, colIndex) } } } error("no StartPoint") } fun findShortestPathToEnd(heightMap: Array<Array<Point>>, startCoordinate: Coordinate): Int? { fun Coordinate.isValid() = row in heightMap.indices && col in heightMap.first().indices val priorityQueue = AdaptablePriorityQueue<Int, Coordinate>() val distances = Array(heightMap.size) { row -> IntArray(heightMap[row].size) { Int.MAX_VALUE } } distances[startCoordinate.row][startCoordinate.col] = 0 val locators = Array(heightMap.size) { row -> Array(heightMap[row].size) { col -> priorityQueue.insert(distances[row][col], Coordinate(row, col)) } } while (!priorityQueue.isEmpty()) { val (distance, coordinate) = priorityQueue.removeMin() if (distance == Int.MAX_VALUE) return null if (heightMap[coordinate.row][coordinate.col] == EndPoint) { return distance } coordinate.neighbors() .filter { it.isValid() && heightMap[coordinate.row][coordinate.col].canReach(heightMap[it.row][it.col]) } .forEach { if (distances[it.row][it.col] == Int.MAX_VALUE) { val entry = locators[it.row][it.col] priorityQueue.replaceKey(entry, distance + 1) distances[it.row][it.col] = distance + 1 } } } error("EndPoint not found") } fun part1(input: List<String>): Int { val heightMap = readHeightMap(input) val startCoordinate = findStartCoordinate(heightMap) return findShortestPathToEnd(heightMap, startCoordinate)!! } fun part2(input: List<String>): Int { val heightMap = readHeightMap(input) val startPoints = buildList { heightMap.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, point -> if (point.elevation == 0) { add(Coordinate(rowIndex, colIndex)) } } } } return startPoints.mapNotNull { findShortestPathToEnd(heightMap, it) }.min() } // 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
afbcec6a05b8df34ebd8543ac04394baa10216f0
4,063
advent-of-code-22
Apache License 2.0
src/Day11.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
import kotlin.math.floor data class Item(var worry: Long) class Monkey { var id: Int = 0 var items = mutableListOf<Item>() lateinit var opValue: (Long) -> Long var divisibleBy: Long = 0 var divTrue: Int = 0 var divFalse: Int = 0 var inspected = 0L companion object { fun parseMonkey(input: List<String>): Monkey { val m = Monkey() m.id = input[0][input[0].length - 2].digitToInt() m.items = input[1].substringAfter(": ").split(",").map { Item(it.trim().toLong()) }.toMutableList() val op = input[2].substringAfter(" old ").split(" ") if (op[0] == "*") { if (op[1] == "old") m.opValue = { a -> a * a } else { m.opValue = { a -> a * op[1].toLong() } } } else { m.opValue = { a -> a + op[1].toLong() } } m.divisibleBy = input[3].substringAfter(" by ").toLong() m.divTrue = input[4].substringAfter("monkey ").toInt() m.divFalse = input[5].substringAfter(" monkey ").toInt() return m } } fun inspects(item: Item) { item.worry = opValue(item.worry) inspected++ } fun tests(item: Item): Int { if(item.worry % divisibleBy == 0L) { return divTrue } else { return divFalse } } } fun main() { fun part1(input: List<String>): Long { val m = input.chunkBy { it.isBlank() } val monkeys = m.map { Monkey.parseMonkey(it) } repeat(20) { monkeys.forEach { while(it.items.isNotEmpty()) { val cur = it.items.removeAt(0) it.inspects(cur) cur.worry = floor(cur.worry.toDouble() / 3.0).toLong() monkeys[it.tests(cur)].items.add(cur) } } } val insps = monkeys.map { it.inspected }.sortedDescending().take(2) return insps[0] * insps[1] } fun part2(input: List<String>): Long { val m = input.chunkBy { it.isBlank() } val monkeys = m.map { Monkey.parseMonkey(it) } val modBy = monkeys.map { it.divisibleBy }.reduce {p, e -> p * e} println(modBy) repeat(10000) { monkeys.forEach { while(it.items.isNotEmpty()) { val cur = it.items.removeAt(0) it.inspects(cur) cur.worry = cur.worry % modBy monkeys[it.tests(cur)].items.add(cur) } } } val insps = monkeys.map { it.inspected }.sortedDescending().take(2) return insps[0] * insps[1] } //val input = readInput("Day11_test") //check(part1(input) == 8) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
2,955
aoc-2022
Apache License 2.0
2021/src/main/kotlin/day21.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems fun main() { Day21.run() } object Day21 : Solution<Day21.State>() { override val name = "day21" override val parser = Parser.lines .mapItems { it.split(":").last().trim() } .map { State( true, it.first().toInt() - 1, it.last().toInt() - 1, 0, 0 ) } data class State( val p1Rolls: Boolean, // 0-1, 2 values val p1Pos: Int, // 0-9, 10 values val p2Pos: Int, // 0-9, 10 values val p1Score: Int, // 0-21, 22 values val p2Score: Int // 0-21, 22 values ) private fun State.withRoll(roll: Int): State { if (p1Rolls) { // p1 rolls val newP1Pos = (p1Pos + roll) % 10 return copy( p1Rolls = false, p1Pos = newP1Pos, p1Score = p1Score + newP1Pos + 1 ) } else { // p2 rolls val newP2Pos = (p2Pos + roll) % 10 return copy( p1Rolls = true, p2Pos = newP2Pos, p2Score = p2Score + newP2Pos + 1 ) } } private fun playDeterministic(state: State, round: Int): State { val roll = (round * 3 + 1 + round * 3 + 2 + round * 3 + 3) return state.withRoll(roll) } val cache = mutableMapOf<State, Pair<Long, Long>>() private fun playQuantum(round: Int, state: State): Pair<Long, Long> { val cached = cache[state] if (cached != null) { return cached } if (state.p1Score >= 21) { return 1L to 0L } else if (state.p2Score >= 21) { return 0L to 1L } val rolls = (1 .. 3).flatMap { r1 -> (1 .. 3).flatMap { r2 -> (1 .. 3).map { r3 -> r1 + r2 + r3 } } } val answ = rolls.map { playQuantum(round + 1, state.withRoll(it)) }.reduce { p1, p2 -> p1.first + p2.first to p1.second + p2.second } cache[state] = answ return answ } override fun part1(input: State): Int { val lastRound = generateSequence(input to 0) { (state, round) -> playDeterministic(state, round) to round + 1 } .takeWhile { it.first.p1Score < 1000 && it.first.p2Score < 1000 } .last() val winning = playDeterministic(lastRound.first, lastRound.second) return ((lastRound.second + 1) * 3) * minOf(winning.p1Score, winning.p2Score) } override fun part2(input: State): Number? { val winCounts = playQuantum(0, input) return maxOf(winCounts.first, winCounts.second) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,467
aoc_kotlin
MIT License
src/Day08.kt
cvb941
572,639,732
false
{"Kotlin": 24794}
fun main() { fun part1(input: List<String>): Int { val rows = input.size val columns = input.first().length val field = Array(rows) { IntArray(columns) } input.forEachIndexed() { rowIndex, row -> row.forEachIndexed() { columnIndex, column -> field[rowIndex][columnIndex] = column.digitToInt() } } var count = 0 field.forEachIndexed() { rowIndex, row -> row.forEachIndexed() { columnIndex, tree -> val leftOk = row.toList().subList(0, columnIndex).all { it < tree } val rightOk = row.toList().subList(columnIndex + 1, row.size).all { it < tree } val topOk = field.toList().subList(0, rowIndex).all { it[columnIndex] < tree } val bottomOk = field.toList().subList(rowIndex + 1, field.size).all { it[columnIndex] < tree } if (leftOk || rightOk || topOk || bottomOk) count++ } } return count } fun part2(input: List<String>): Int { val rows = input.size val columns = input.first().length val field = Array(rows) { IntArray(columns) } input.forEachIndexed() { rowIndex, row -> row.forEachIndexed() { columnIndex, column -> field[rowIndex][columnIndex] = column.digitToInt() } } var best = 0 field.forEachIndexed() { rowIndex, row -> row.forEachIndexed() { columnIndex, tree -> // Krajne nechceme lebo su za 0 a sekcia dolu s nimi pocita zle if (rowIndex == 0 || rowIndex == rows - 1 || columnIndex == 0 || columnIndex == columns - 1) return@forEachIndexed val left = row.toList().subList(0, columnIndex).drop(1).reversed().takeWhile { it < tree }.count() + 1 val right = row.toList().subList(columnIndex + 1, row.size).dropLast(1).takeWhile { it < tree }.count() + 1 val top = field.toList().subList(0, rowIndex).drop(1).reversed().takeWhile { it[columnIndex] < tree }.count() + 1 val bottom = field.toList().subList(rowIndex + 1, field.size).dropLast(1).takeWhile { it[columnIndex] < tree }.count() + 1 val score = left * right * top * bottom if (score > best) best = score } } return best } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fe145b3104535e8ce05d08f044cb2c54c8b17136
2,695
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/aoc2016/day4/GetARoom.kt
arnab
75,525,311
false
null
package aoc2016.day4 data class Room(val encryptedName: String, val sectorId: Int, val checkSum: String) { val name: String by lazy { decryptName() } val computedCheckSum: String by lazy { computeCheckSum() } private fun decryptName(): String = encryptedName .split("-") .map { w -> w.map { c -> rotateBy(c, sectorId) } } .map { w -> w.joinToString("") } .joinToString(" ") private fun rotateBy(c: Char, n: Int): Char { val indexAfterRotation = (aToz.indexOf(c) + n) % aToz.size return aToz[indexAfterRotation] } private fun computeCheckSum(): String { val letters = encryptedName.filter(Char::isLetter) val frequenciesByLetter: Map<Char, Int> = letters.fold(mutableMapOf(), { part, letter -> part.put(letter, (part[letter] ?: 0) + 1) part }) val lettersByFrequency: Map<Int, List<Char>> = frequenciesByLetter.toList().fold(mutableMapOf(), { part, (letter, frequency) -> part.put(frequency, ( part[frequency] ?: emptyList() ).plus(letter)) part }) val lettersSortedByFrequencyThanAlphabetic = lettersByFrequency.toList() .sortedByDescending { it.first } .map { it.second } .map { it.sorted() } .flatten() return lettersSortedByFrequencyThanAlphabetic.take(5).joinToString("") } fun isReal(): Boolean = checkSum == computedCheckSum companion object { private val aToz: List<Char> = ('a'..'z').toList() // e.g. aaaaa-bbb-z-y-x-123[abxyz] private val roomPattern = Regex("""([\w-]+)-(\d+)\[(\w+)\]""") fun from(data: String): Room? { val matches = roomPattern.matchEntire(data) val (name, sector, checkSum) = matches?.destructured ?: return null return Room(encryptedName = name, sectorId = sector.toInt(), checkSum = checkSum) } } } object GetARoom { fun filterValidRooms(data: String): List<Room> = data .lines() .map(String::trim) .filter(String::isNotBlank) .map { Room.from(it) } .filterNotNull() .filter(Room::isReal) fun sumOfValidRoomSectorIds(data: String) = filterValidRooms(data).sumBy(Room::sectorId) }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,382
adventofcode
MIT License
src/Day16.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File import java.util.* import kotlin.math.max import kotlin.system.measureTimeMillis // Advent of Code 2022, Day 16, Proboscidea Volcanium data class ValveData(val name: String, val index: Int, val rate: Int, val tunnels: List<String>) data class State(val currLocn: ValveData, val time: Int, val totalRelease: Int, val valvesOn: Set<ValveData>) data class State2(val currLocn: List<ValveData?>, val time: List<Int>, val totalRelease: Int, val valvesOn: Set<ValveData>) fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() fun scoreUpperBound(allValves: Set<ValveData>, valvesOn: Set<ValveData>, time: Int, currRelease: Int, part1: Boolean, maxTime: Int) : Int { check(allValves.size >= valvesOn.size) var score = currRelease val valvesOff = (allValves - valvesOn).sortedByDescending { it.rate }.toMutableList() var currTime = time while (currTime < maxTime && valvesOff.isNotEmpty()) { var nextValve = valvesOff.removeFirst() score += (maxTime - currTime) * nextValve.rate if (!part1 && valvesOff.isNotEmpty()) { nextValve = valvesOff.removeFirst() // simultaneous elephant valve score += (maxTime - currTime) * nextValve.rate } currTime++ } return score } fun parse(input: String): Pair<MutableMap<String, ValveData>, Array<IntArray>> { val valves = input.split("\n") .map { it.split(" ") .drop(1) // initial empty }.mapIndexed { idx, it -> ValveData(it[0], idx, it[3].split("=", ";")[1].toInt(), it.subList(8, it.size).map { if (it.last() == ',') it.dropLast(1) else it }) }.associateBy { it.name }.toMutableMap() // Floyd-Warshall val dist = Array(valves.keys.size) { IntArray(valves.size) { Int.MAX_VALUE / 3 } } // div by 3 so we don't overflow for (i in 0 until valves.keys.size) { dist[i][i] = 0 } for (v in valves.values) { for (next in v.tunnels) { dist[v.index][valves[next]!!.index] = 1 } } for (k in 0 until valves.keys.size) { for (i in 0 until valves.keys.size) { for (j in 0 until valves.keys.size) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j] } } } } return Pair(valves, dist) } fun part1(input: String, MAX_TIME: Int): Int { val (valves, dist) = parse(input) // We always start from Valve AA val indexAA = valves["AA"]!!.index val queue = valves.values.filter {it.rate != 0}.map { val time = dist[indexAA][it.index] + 1 // takes 1 min to turn on valve State(it, time, (MAX_TIME - time) * it.rate, setOf(it)) }.toMutableList() val relevantValves = valves.values.filter { it.rate != 0 }.toSet() // var maxTime = 0 var maxRelease = 0 while (queue.isNotEmpty()) { val state = queue.removeFirst() if (state.time > MAX_TIME) continue val maxPossible = scoreUpperBound(relevantValves, state.valvesOn, state.time, state.totalRelease, true, MAX_TIME) if (maxPossible < maxRelease) continue // if (state.time > maxTime) { // maxTime = state.time // println("time is $maxTime, queue size is ${queue.size}") // } // if (state.totalRelease > maxRelease) println("max release = ${state.totalRelease}") maxRelease = max(state.totalRelease, maxRelease) val valvesOff = relevantValves - state.valvesOn val nextVisits = valvesOff.map { val time = dist[state.currLocn.index][it.index] + 1 + state.time // takes 1 min to turn on valve State(it, time, state.totalRelease + (MAX_TIME - time) * it.rate, state.valvesOn + setOf(it)) } queue.addAll(nextVisits) } return maxRelease } fun part2(input: String, MAX_TIME: Int): Int { val (valves, dist) = parse(input) // We always start from Valve AA val indexAA = valves["AA"]!!.index val nextValves = valves.values.filter {it.rate != 0} val queue = PriorityQueue {t1: State2, t2: State2 -> (t2.totalRelease - t1.totalRelease) } // val queue = mutableListOf<State2>() // v -> Node B and e -> Node C has the same result as v->C and e->B, so only create half the possible travels for (vIdx in nextValves.indices) { val v = nextValves[vIdx] val time0 = dist[indexAA][v.index] + 1 // takes 1 min to turn on valve if (time0 > MAX_TIME) continue //!FIX but e travel may be OK? have handle case where 1 traveller stuck & other isn't val rel0 = (MAX_TIME - time0) * v.rate for (eIdx in vIdx+1..nextValves.lastIndex) { val e = nextValves[eIdx] check(v != e) val time1 = dist[indexAA][e.index] + 1 // takes 1 min to turn on valve if (time1 > MAX_TIME) continue val rel1 = (MAX_TIME - time1) * e.rate queue.add(State2(listOf(v, e), listOf(time0, time1), rel0 + rel1, setOf(v, e) )) } } val relevantValves = valves.values.filter { it.rate != 0 }.toSet() var maxTime = 0 var maxRelease = 0 while (queue.isNotEmpty()) { var state = queue.remove() //!FIX but what if only 1 time is over - continue with other time? if (state.time.min() > MAX_TIME) continue // don't count the person/elephant who has exceeded time, but the other one keeps moving if (state.time[0] > MAX_TIME) { // or should it be >= ?? state = state.copy( currLocn = listOf(null, state.currLocn[0]) ) } if (state.time[1] > MAX_TIME) { state = state.copy( currLocn = listOf(state.currLocn[1], null) ) } //!FIX have to fix upperbound to deal with simultaneous movement - add 2 valves per minute val treatAsPart1 = state.currLocn.filterNotNull().size != 2 val maxPossible = scoreUpperBound(relevantValves, state.valvesOn, state.time.min(), state.totalRelease, treatAsPart1, MAX_TIME) if (maxPossible < maxRelease) continue if (state.time.min() > maxTime) { maxTime = state.time.max() println("time is $maxTime, queue size is ${queue.size}") } if (state.totalRelease > maxRelease) { println("max release = ${state.totalRelease}, queue size is ${queue.size}, valves on ${state.valvesOn.map { it.name }}") } maxRelease = max(state.totalRelease, maxRelease) val valvesOff = relevantValves - state.valvesOn val vTrips = if (state.currLocn[0] == null ) emptyList() else { valvesOff.filter {v -> val time0 = dist[state.currLocn[0]!!.index][v.index] + 1 // takes 1 min to turn on valve state.time[0] + time0 < MAX_TIME } } val eTrips = if (state.currLocn[1] == null ) emptyList() else { valvesOff.filter {e -> val time1 = dist[state.currLocn[1]!!.index][e.index] + 1 // takes 1 min to turn on valve state.time[1] + time1 < MAX_TIME } } if (vTrips.isEmpty() && eTrips.isEmpty()) continue if (vTrips.isEmpty()) { for (e in eTrips) { val time1 = dist[state.currLocn[1]!!.index][e.index] + 1 // takes 1 min to turn on valve val rel1 = (MAX_TIME - (state.time[1] + time1)) * e.rate queue.add(State2(listOf(null, e), listOf(MAX_TIME, time1 + state.time[1]), state.totalRelease + rel1, state.valvesOn + setOf(e))) } } if (eTrips.isEmpty()) { for (v in vTrips) { val time0 = dist[state.currLocn[0]!!.index][v.index] + 1 // takes 1 min to turn on valve val rel0 = (MAX_TIME - (state.time[0] + time0)) * v.rate queue.add(State2(listOf(v, null), listOf(time0 + state.time[0], MAX_TIME), state.totalRelease + rel0 , state.valvesOn + setOf(v) )) } } if (vTrips.isEmpty() || eTrips.isEmpty()) continue for (v in vTrips) { val time0 = dist[state.currLocn[0]!!.index][v.index] + 1 // takes 1 min to turn on valve if (state.time[0] + time0 >= MAX_TIME) continue val rel0 = (MAX_TIME - (state.time[0] + time0)) * v.rate for (e in eTrips) { if (v == e) continue // val time1 = if (state.currLocn[0] != null) { // } else 0 // val time2 = if (state.currLocn[1] != null) { val time1 = dist[state.currLocn[1]!!.index][e.index] + 1 // takes 1 min to turn on valve if (state.time[1] + time1 >= MAX_TIME) continue // } else 0 // val rel1 = if (time1 != 0) (MAX_TIME - time1) * v.rate else 0 // val rel2 = if (time2 != 0) (MAX_TIME - time2) * e.rate else 0 val rel1 = (MAX_TIME - (state.time[1] + time1)) * e.rate queue.add(State2(listOf(v, e), listOf(time0 + state.time[0], time1 + state.time[1]), state.totalRelease + rel0 + rel1, state.valvesOn + setOf(v, e) )) } } } return maxRelease } val testInput = readInputAsOneLine("Day16_test") var timeInMillis = measureTimeMillis { check(part1(testInput, 30) == 1651) } println("time for test input, part 1 is $timeInMillis ms") timeInMillis = measureTimeMillis { check(part2(testInput, 26) == 1707) // should be 1707 for 26 min } println("time for test input, part 2 is $timeInMillis ms") println("\nNow real input") timeInMillis = measureTimeMillis { val input = readInputAsOneLine("Day16") println(part1(input, 30)) } // Part 1 time is 1 min for real input println("time for real input part 1 is $timeInMillis ms") timeInMillis = measureTimeMillis { val input = readInputAsOneLine("Day16") println(part2(input, 26)) // 2206 is too low } println("time for real input part 2 is $timeInMillis ms") // 77 sec }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
11,066
AdventOfCode2022
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day12.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution object Day12 : AdventSolution(2018, 12, "Subterranean Sustainability") { override fun solvePartOne(input: String): Int { val (initial, rules) = parse(input) val g = 20 return generateSequence(initial) { ("....$it....").windowedSequence(5) { w -> rules[w] }.joinToString("") } .drop(g) .first() .mapIndexed { index, c -> if (c == '#') index - 2 * g else 0 } .sum() } override fun solvePartTwo(input: String): Long { val (initial, rules) = parse(input) val gen = 200 val generations = generateSequence(initial) { prev -> ("...$prev...") .windowedSequence(5) { rules[it]!! } .joinToString("") } val scores = generations.mapIndexed { i, v -> v.mapIndexed { index, c -> if (c == '#') index - i else 0 }.sum() } val stableScores = scores .drop(gen) .take(5) .toList() //stabilized? check(stableScores.zipWithNext(Int::minus).distinct().size == 1) return stableScores[0] + (50_000_000_000 - gen) * (stableScores[1] - stableScores[0]) } private fun parse(input: String): Pair<String, Map<String, Char>> { val lines = input.lines() val initial = lines[0].substringAfter("initial state: ") val rules = lines.drop(2).map { it.split(" => ") }.associate { (cfg, n) -> cfg to n[0] } return initial to rules } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,608
advent-of-code
MIT License
src/main/kotlin/com/hjk/advent22/Day14.kt
h-j-k
572,485,447
false
{"Kotlin": 26661, "Racket": 3822}
package com.hjk.advent22 object Day14 { fun part1(input: List<String>): Int = process(toRocks(input)) fun part2(input: List<String>): Int = toRocks(input).let { rocks -> val floor = Point2d(x = 0, y = rocks.maxOf { it.y } + 2) rocks.fold(Int.MAX_VALUE to Int.MIN_VALUE) { (min, max), rock -> min.coerceAtMost(rock.x) to max.coerceAtLeast(rock.x) }.let { (min, max) -> process(rocks + (floor.copy(x = min - 200)..floor.copy(x = max + 200))) } } private fun toRocks(input: List<String>): Set<Point2d> = input.flatMap { line -> line.split(" -> ") .map { point -> point.split(",").let { (x, y) -> Point2d(x = x.toInt(), y = y.toInt()) } } .fold(listOf<Point2d>()) { acc, point -> acc + (acc.lastOrNull()?.let { it..point } ?: listOf(point)) } }.toSet() private operator fun Point2d.rangeTo(other: Point2d): List<Point2d> = when { this.x == other.x -> (minOf(this.y, other.y) until maxOf(this.y, other.y)).map { this.copy(y = it) } this.y == other.y -> (minOf(this.x, other.x) until maxOf(this.x, other.x)).map { this.copy(x = it) } else -> throw RuntimeException() } + other private fun process(rocks: Set<Point2d>): Int { val source = Point2d(x = 500, y = 0) val sand = mutableSetOf<Point2d>() while (source !in sand) findEndPosition(source, rocks + sand)?.let { sand += it } ?: break return sand.size } private fun findEndPosition(source: Point2d, obstacles: Set<Point2d>): Point2d? { val end = obstacles.asSequence().filter { it.x == source.x && it.y >= source.y }.minByOrNull { it.y } val (left, right) = end?.let { it.copy(x = it.x - 1) to it.copy(x = it.x + 1) } ?: return null return when { left in obstacles && right in obstacles -> end.let { it.copy(y = it.y - 1) } left !in obstacles -> findEndPosition(left, obstacles) right !in obstacles -> findEndPosition(right, obstacles) else -> null } } }
0
Kotlin
0
0
20d94964181b15faf56ff743b8646d02142c9961
2,105
advent22
Apache License 2.0
src/day09/Day09.kt
henrikrtfm
570,719,195
false
{"Kotlin": 31473}
package day09 import utils.Resources.resourceAsListOfString typealias Point = Pair<Int, Int> fun main(){ val tailNeighbors = sequenceOf(-1 to 0, 0 to -1, 0 to 1, 1 to 0, -1 to 1, -1 to -1, 1 to 1, 1 to -1) val headNeighbours = sequenceOf(-1 to 0, 0 to -1, 0 to 1, 1 to 0) val diagonals = sequenceOf(-1 to 1, -1 to -1, 1 to -1, 1 to 1) val input = resourceAsListOfString("src/day09/Day09_test.txt").map { Move.parse(it) } val visited: MutableSet<Point> = mutableSetOf() var head = Point(0,0) var tail = Point(0,0) val knots = MutableList(9) {Point(0,0)} fun simulateOneKnot(move: Move){ move.steps.forEach { head += move.direction when((tailNeighbors.map { it + tail }.toList()+tail).contains(head)){ true -> {} false -> { tail = (tailNeighbors.map { it+tail }.toSet() intersect headNeighbours.map { it2 -> it2 + head }.toSet()).first() } } visited.add(tail) } } fun simulateTenKnots(move: Move){ move.steps.forEach { head += move.direction for((index, knot) in knots.withIndex()){ val myHead = knots.getOrNull(index-1) ?: head when((tailNeighbors.map { it + knot }.toList()+knot).contains(myHead)){ true -> break false -> { knots[index] = (tailNeighbors.map { it+knot }.toSet() intersect headNeighbours.map { it2 -> it2 + myHead }.toSet()).firstOrNull() ?: (diagonals.map { self -> self+knot }.toSet() intersect diagonals.map { head -> head + myHead }.toSet()).first() } } if(index==knots.lastIndex){ visited.add(knot) } } } } fun part1(input: List<Move>): Int{ input.forEach { simulateOneKnot(it) } return visited.size } fun part2(input: List<Move>): Int { input.forEach { simulateTenKnots(it) } return visited.size + 1 } println(part1(input)) //println(part2(input)) } private operator fun Point.plus(that: Point): Point = Point(this.first + that.first, this.second + that.second) data class Move( val direction: Point, val steps: IntRange ) { companion object { fun parse(input: String): Move { val direction = when (input.substringBefore(" ")) { "U" -> Point(1, 0) "R" -> Point(0, 1) "L" -> Point(0, -1) "D" -> Point(-1, 0) else -> Point(0,0) } val steps = 1..input.substringAfter(" ").toInt() return Move(direction, steps) } } }
0
Kotlin
0
0
20c5112594141788c9839061cb0de259f242fb1c
2,812
aoc2022
Apache License 2.0
src/day05/Day05.kt
skempy
572,602,725
false
{"Kotlin": 13581}
package day05 import readInputAsList data class CrateInstruction(val quantity: Int, val source: Int, val target: Int) fun main() { fun findStacksOfCrates( input: List<String>, ): MutableMap<Int, MutableList<Char>> { val stacks = mutableMapOf<Int, MutableList<Char>>() val stackPosition = mutableListOf<Int>() input.first { line -> line.filterNot { it.isWhitespace() }.all { char -> char.isDigit() } } .forEachIndexed { index, char -> if (!char.isWhitespace()) { stackPosition.add(index) } } stackPosition.forEachIndexed { index1, charPosition -> stacks[index1] = input.takeWhile { it.contains('[') } .mapNotNull { it.getOrNull(charPosition) } .filter { !it.isWhitespace() } .toMutableList() } return stacks } fun parseInstructions( input: List<String>, ): List<CrateInstruction> { return input.dropWhile { !it.startsWith("move") }.map { instruction -> val res = "move (\\d+) from (\\d) to (\\d)".toRegex().find(instruction)!!.groupValues CrateInstruction(res[1].toInt(), res[2].toInt() - 1, res[3].toInt() - 1) } } fun part1(input: List<String>): String { val stacks = findStacksOfCrates(input) parseInstructions(input).forEach { instruction -> repeat(instruction.quantity) { val crateToMove = stacks[instruction.source]?.take(1)!!.single() stacks[instruction.source]?.remove(crateToMove) stacks[instruction.target]?.add(0, crateToMove) } } return String(stacks.map { it.value.first() }.toCharArray()) } fun part2(input: List<String>): String { val stacks = findStacksOfCrates(input) parseInstructions(input).forEach { crateInstruction -> val crateToMove = stacks[crateInstruction.source]?.take(crateInstruction.quantity)!! crateToMove.forEach { stacks[crateInstruction.source]?.remove(it) } stacks[crateInstruction.target]?.addAll(0, crateToMove) } return String(stacks.filter { it.value.isNotEmpty() }.map { it.value.first() }.toCharArray()) } // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day05", "_test") println("Test Part1: ${part1(testInput)}") check(part1(testInput) == "CMZ") val input = readInputAsList("Day05") println("Actual Part1: ${part1(input)}") check(part1(input) == "VGBBJCRMN") println("Test Part2: ${part2(testInput)}") check(part2(testInput) == "MCD") println("Actual Part2: ${part2(input)}") check(part2(input) == "LBBVJBRMH") }
0
Kotlin
0
0
9b6997b976ea007735898083fdae7d48e0453d7f
2,872
AdventOfCode2022
Apache License 2.0
src/Day07.kt
remidu
573,452,090
false
{"Kotlin": 22113}
class Node(val name: String, var size: Int, val children: ArrayList<Node>, var parent: Node?) { fun addChild(name: String, size: Int) { this.size += size this.children.add(Node(name, size, ArrayList(), this)) } fun addChild(node: Node) { this.children.add(node) } } fun main() { fun goBack(node: Node): Node { val parentNode = node.parent if (parentNode != null) { parentNode.size += node.size return parentNode } return node } fun listFolders(node: Node, list: ArrayList<Node>): ArrayList<Node> { if (node.children.size > 0) { list.add(node) for (child in node.children) { listFolders(child, list) } } return list } fun getAllFolders(input: List<String>): ArrayList<Node> { var currentFolder = Node("root", 0, ArrayList(), null) for (line in input) { if (line == "$ cd /") { continue } else if (line == "$ ls") { continue } else if (line == "$ cd ..") { currentFolder = goBack(currentFolder) } else if (line.startsWith("$ cd")) { val node = Node(line.split(" ")[2], 0, ArrayList(), currentFolder) currentFolder.addChild(node) currentFolder = node } else if (line.first().isDigit()) { currentFolder.addChild(line.split(" ")[1], line.split(" ")[0].toInt()) } } while (currentFolder.name != "root") { currentFolder = goBack(currentFolder) } return listFolders(currentFolder, ArrayList()) } fun part1(input: List<String>): Int { val folders = getAllFolders(input) return folders.filter { f -> f.size <= 100000 }.sumOf { f -> f.size } } fun part2(input: List<String>): Int { val folders = getAllFolders(input) val max = 70000000 val necessary = 30000000 val used = folders.filter { f -> f.name == "root" }.map { f -> f.size }.first() val unused = max - used val possibleFolders = folders.filter { f -> f.size > necessary - unused } return possibleFolders.minBy { f -> f.size }.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Data_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Data") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ecda4e162ab8f1d46be1ce4b1b9a75bb901bc106
2,597
advent-of-code-2022
Apache License 2.0
src/main/day03/Day03.kt
rolf-rosenbaum
543,501,223
false
{"Kotlin": 17211}
package day03 import readInput import second fun part1(input: List<String>): Int { val points = addClaims(input) return points.count { it.value.size > 1 } } private fun addClaims(input: List<String>): MutableMap<Point, MutableSet<Claim>> { val points = mutableMapOf<Point, MutableSet<Claim>>() input.forEach { line -> val claim = line.toClaim() (claim.startPoint.first until (claim.startPoint.first + claim.width)).forEach { x -> (claim.startPoint.second until (claim.startPoint.second + claim.height)).forEach { y -> if (points.containsKey(x to y)) { points[x to y]!!.add(claim) } else { points[x to y] = mutableSetOf(claim) } } } } return points } fun part2(input: List<String>): Int { val claims: MutableMap<Claim, MutableList<Point>> = mutableMapOf() input.forEach { line -> val claim = line.toClaim() (claim.startPoint.first until (claim.startPoint.first + claim.width)).forEach { x -> (claim.startPoint.second until (claim.startPoint.second + claim.height)).forEach { y -> if (claims.containsKey(claim)) { claims[claim]!!.add(x to y) } else { claims[claim] = mutableListOf(x to y) } } } } val singularClaim = claims.filter { (claim, points) -> (claims - claim).all { (_, pointsList) -> pointsList.intersect(points.toSet()).isEmpty() } } return singularClaim.keys.first().id.toInt() } private fun String.toClaim(): Claim { val foo = split(" @ ") val id = foo.first().substring(1) val split = foo[1].split(": ") val pos = split.first() val startPoint = pos.split(",").first().toInt() to pos.split(",").second().toInt() val sizeX = split.second().split("x").first().toInt() val sizeY = split.second().split("x").second().toInt() return Claim(id, startPoint, sizeX, sizeY) } fun main() { val input = readInput("main/day03/Day03") println(part1(input)) println(part2(input)) } typealias Point = Pair<Int, Int> data class Claim( val id: String, val startPoint: Point, val width: Int, val height: Int ) { val size get() = width * height }
0
Kotlin
0
0
dfd7c57afa91dac42362683291c20e0c2784e38e
2,388
aoc-2018
Apache License 2.0
2022/src/main/kotlin/day16_attempt2.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parse import utils.Parser import utils.Solution import utils.mapItems import utils.times fun main() { Day16A2.run() } object Day16A2 : Solution<List<Day16A2.Valve>>() { override val name = "day16" override val parser = Parser.lines .mapItems { it.replace("tunnel leads to valve", "tunnels lead to valves") } .mapItems(::parseValve) @Parse("Valve {name} has flow rate={flowRate}; tunnels lead to valves {r ', ' out}") data class Valve(val name: String, val flowRate: Int, val out: List<String>) private fun computeDistMap(input: List<Valve>): Array<IntArray> { val inf = input.size * 4 // something large enough val distMap = Array(input.size) { IntArray(input.size) { inf } } // populate initial edges input.forEachIndexed { i, valve -> valve.out.forEach { target -> val j = input.indexOfFirst { it.name == target } distMap[i][j] = 1 distMap[j][i] = 1 } } for (k in input.indices) { for (i in input.indices) { for (j in input.indices) { if (distMap[i][j] > distMap[i][k] + distMap[k][j]) { distMap[i][j] = distMap[i][k] + distMap[k][j] } } } } return distMap } // state space 16 * 16 * 2^15 * 26 * 26, too big? data class StateKey(val loc1: Int, val loc2: Int, val remainingValves: List<Int>, val time1: Int, val time2: Int) class Context( val valves: List<Valve>, val distMap: Array<IntArray>, val cache: MutableMap<StateKey, Int>, val maxTime: Int, ) private fun bestScore( ctx: Context, time1: Int, location1: Int, time2: Int, location2: Int, remainingValves: List<Int>, root: Boolean, ): Int { // nothing to open if (remainingValves.isEmpty()) { return 0 } // out of time if (time1 >= ctx.maxTime && time2 >= ctx.maxTime) { return 0 } val key = StateKey(location1, location2, remainingValves, time1, time2) val cached = ctx.cache[key] if (cached != null) { return cached } val opts = if (remainingValves.size == 1) { setOf(remainingValves[0] to null, null to remainingValves[0]) } else { (remainingValves * remainingValves).filter { (a, b) -> a != b } .map { (a, b) -> a.takeIf { time1 + ctx.distMap[location1][a] < ctx.maxTime } to b.takeIf { time2 + ctx.distMap[location2][b] < ctx.maxTime } }.toSet() } var cur = 0 val score = opts.maxOfOrNull { (open1, open2) -> var remaining = remainingValves var pressure1 = 0 var t1 = time1 var l1 = location1 if (open1 != null) { val travel1 = ctx.distMap[location1][open1] pressure1 = (ctx.maxTime - (time1 + travel1)) * ctx.valves[open1].flowRate remaining = remaining.filter { it != open1 } t1 = time1 + travel1 + 1 l1 = open1 } var pressure2 = 0 var t2 = time2 var l2 = location2 if (open2 != null) { val travel2 = ctx.distMap[location2][open2] pressure2 = (ctx.maxTime - (time2 + travel2)) * ctx.valves[open2].flowRate remaining = remaining.filter { it != open2 } t2 += travel2 + 1 l2 = open2 } if (root) { println("$cur / ${opts.size}") } if (pressure1 == 0 && pressure2 == 0) 0 else { pressure1 + pressure2 + bestScore(ctx, t1, l1, t2, l2, remaining, false) }.also { cur++ } } ?: 0 ctx.cache[key] = score return score } override fun part1(input: List<Valve>): Int { val start = input.indexOfFirst { it.name == "AA" } val context = Context( valves = input, distMap = computeDistMap(input), cache = mutableMapOf(), maxTime = 30, ) return bestScore(context, 1, start, context.maxTime, start, input.indices.filter { input[it].flowRate > 0 }, true) } override fun part2(input: List<Valve>): Any? { val start = input.indexOfFirst { it.name == "AA" } val context = Context( valves = input, distMap = computeDistMap(input), cache = mutableMapOf(), maxTime = 26, ) return bestScore(context, 1, start, 1, start, input.indices.filter { input[it].flowRate > 0 }, true) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
4,292
aoc_kotlin
MIT License
2022/src/day15/day15.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day15 import GREEN import RESET import printTimeMillis import readInput import kotlin.math.* data class Point(val x: Long, val y: Long) data class Area(val center: Point, val dist: Long) { fun xRangeForY(yPos: Long): Range? { val sizeOfRange = dist - abs(center.y - yPos) val minX = center.x - sizeOfRange val maxX = center.x + sizeOfRange if (minX > maxX) return null // out of range return Range(minX, maxX) } } data class Range(val start: Long, val end: Long) { /** * 5..15 minus 16..20 = 5..15 * 5..15 minus 3..4 = 5..15 * 5..15 minus 10..20 = 5..9 * 5..15 minus 0..7 = 8..15 * 5..15 minus 8..10 = 5..7 AND 11..15 * 5..15 minus 4..16 = EMPTY */ fun minus(other: Range): List<Range>? { if (other.start <= start && other.end >= end) return null if (other.start > end) return listOf(this) if (other.end < start) return listOf(this) return listOf( Range(start, min(end, other.start) - 1), Range(other.end + 1, end) ).filterNot { it.isEmpty() } } private fun isEmpty() = end - start < 0 fun hasOneItem() = start == end } fun String.toPoints() = split(": ").let { val sensor = it[0].split(" ").let { Point(it[2].substringAfter('=').dropLast(1).toLong(), it[3].substringAfter('=').toLong()) } val closest = it[1].split(" ").let { Point(it[4].substringAfter('=').dropLast(1).toLong(), it[5].substringAfter('=').toLong()) } listOf(sensor, closest) } fun part1(input: List<String>, rowToLookFor: Long): Int { val uniquesX = mutableSetOf<Long>() val beaconX = mutableSetOf<Long>() for (line in input) { val p = line.toPoints() val dist = abs(p[0].x - p[1].x) + abs(p[0].y - p[1].y) // Manhattan dist val area = Area(p.first(), dist) area.xRangeForY(rowToLookFor)?.let {// We have a hit for this row for (x in (it.start..it.end)) uniquesX.add(x) } // Storing the X positions of beacons at pos.y == y if (p[1].y == rowToLookFor) beaconX.add(p[1].x) } uniquesX.removeAll(beaconX) return uniquesX.size } fun part2(input: List<String>, maxValue: Long): Long { val points = input.map { it.toPoints() } for (y in 0L..maxValue) { // For each possible Y pos var possibleX = mutableListOf(Range(0, maxValue)) // Start with the whole line being possible for (p in points) { val dist = abs(p[0].x - p[1].x) + abs(p[0].y - p[1].y) // Manhattan dist val area = Area(p.first(), dist) val range = area.xRangeForY(y) ?: continue val newPossibilities = mutableListOf<Range>() for (previousRange in possibleX) { previousRange.minus(range)?.let { newRanges -> // Remove the ranges from the possibles ones newPossibilities.addAll(newRanges) } } if (possibleX.isEmpty()) break // We already exhausted this line with the previous sensors possibleX = newPossibilities } possibleX.firstOrNull()?.let { onlyRange -> if (onlyRange.hasOneItem()) { return onlyRange.start * 4000000L + y } } } throw IllegalStateException("Beacon not found :(") } fun main() { val testInput = readInput("day15_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput, 10L) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput, 20) + RESET) } val input = readInput("day15.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input, 2000000L) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input, 4000000L) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
3,811
advent-of-code
Apache License 2.0
src/Day02.kt
hufman
573,586,479
false
{"Kotlin": 29792}
enum class Move(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun fromStr(input: String): Move { return when(input) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> throw IllegalArgumentException(input) } } } fun contest(other: Move): ContestResult { if (this == other) return ContestResult.DRAW if ((this == ROCK && other == PAPER) || (this == PAPER && other == SCISSORS) || (this == SCISSORS && other == ROCK)) return ContestResult.WIN return ContestResult.LOSS } } enum class ContestResult(val points: Int) { WIN(6), DRAW(3), LOSS(0); companion object { fun fromStr(input: String): ContestResult { return when(input) { "X" -> LOSS "Y" -> DRAW "Z" -> WIN else -> throw IllegalArgumentException(input) } } } } fun main() { fun parse_part1(input: List<String>): List<Pair<Move, Move>> { return input.map { it.split(" ", limit=2) }.filter { it.size == 2 }.map { Pair(Move.fromStr(it[0]), Move.fromStr(it[1])) } } fun score_move(left: Move, right: Move): Int { return right.points + left.contest(right).points } fun part1(input: List<String>): Int { return parse_part1(input) .map { score_move(it.first, it.second) } .sum() } fun plan_move(left: Move, result: ContestResult): Move { if (result == ContestResult.DRAW) return left return if (result == ContestResult.WIN) { when (left) { Move.ROCK -> Move.PAPER Move.PAPER -> Move.SCISSORS Move.SCISSORS -> Move.ROCK } } else { // LOSS when (left) { Move.ROCK -> Move.SCISSORS Move.PAPER -> Move.ROCK Move.SCISSORS -> Move.PAPER } } } fun parse_part2(input: List<String>): List<Pair<Move, ContestResult>> { return input.map { it.split(" ", limit=2) }.filter { it.size == 2 }.map { Pair(Move.fromStr(it[0]), ContestResult.fromStr(it[1])) } } fun part2(input: List<String>): Int { return parse_part2(input) .map { score_move(it.first, plan_move(it.first, it.second)) } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1bc08085295bdc410a4a1611ff486773fda7fcce
2,348
aoc2022-kt
Apache License 2.0
src/main/kotlin/dev/siller/aoc2022/Day08.kt
chearius
575,352,798
false
{"Kotlin": 41999}
package dev.siller.aoc2022 import kotlin.math.max private val example = """ 30373 25512 65332 33549 35390 """.trimIndent() private fun part1(input: List<String>): Int = input .flatMap { l -> l.toList().map { c -> c.digitToInt() } } .let { forest -> val height = input.size val width = forest.size / height val treeCount = forest.size val edges = 2 * width + 2 * (height - 2) edges + forest.indices .toList() .filterNot { i -> i < width || i >= treeCount - width || i % width == 0 || i % width == width - 1 } .map { index -> val treeHeight = forest[index] val currentRow = index / width val currentColumn = index % width val visible = (0 until currentRow) .map { row -> forest[row * width + currentColumn] } .all { h -> h < treeHeight } || (currentRow + 1 until height) .map { row -> forest[row * width + currentColumn] } .all { h -> h < treeHeight } || (0 until currentColumn) .map { column -> forest[currentRow * width + column] } .all { h -> h < treeHeight } || (currentColumn + 1 until width) .map { column -> forest[currentRow * width + column] } .all { h -> h < treeHeight } visible } .count { visible -> visible } } private fun part2(input: List<String>): Int = input .flatMap { l -> l.toList().map { c -> c.digitToInt() } } .let { forest -> val height = input.size val width = forest.size / height val treeCount = forest.size forest.indices .toList() .filterNot { i -> i < width || i >= treeCount - width || i % width == 0 || i % width == width - 1 } .map { index -> val treeHeight = forest[index] val currentRow = index / width val currentColumn = index % width val up = currentRow - max( 0, (0 until currentRow) .map { row -> forest[row * width + currentColumn] } .indexOfLast { h -> h >= treeHeight } ) val down = height - currentRow - 1 - max( 0, (currentRow + 1 until height) .reversed() .map { row -> forest[row * width + currentColumn] } .indexOfLast { h -> h >= treeHeight } ) val left = currentColumn - max( 0, (0 until currentColumn) .map { column -> forest[currentRow * width + column] } .indexOfLast { h -> h >= treeHeight } ) val right = width - currentColumn - 1 - max( 0, (currentColumn + 1 until width) .reversed() .map { column -> forest[currentRow * width + column] } .indexOfLast { h -> h >= treeHeight } ) up * left * down * right } .max() } fun aocDay08() = aocTaskWithExample( day = 8, part1 = ::part1, part2 = ::part2, exampleInput = example, expectedOutputPart1 = 21, expectedOutputPart2 = 8 ) fun main() { aocDay08() }
0
Kotlin
0
0
e070c0254a658e36566cc9389831b60d9e811cc5
3,735
advent-of-code-2022
MIT License
src/Day08.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
fun main() { data class Pos(val row: Int, val column: Int) { fun moveLeft() = Pos(row, column - 1) fun moveRight() = Pos(row, column + 1) fun moveUp() = Pos(row - 1, column) fun moveDown() = Pos(row + 1, column) } class Forest(private val trees: List<String>) { val rows: Int = trees.size val columns: Int = trees.first().length operator fun get(pos: Pos): Int { return trees[pos.row][pos.column].digitToInt() } operator fun contains(pos: Pos): Boolean { return pos.column in 0 until columns && pos.row in 0 until rows } } fun goIntoForest(forest: Forest, from: Pos, action: (Pos) -> Pos): Sequence<Pos> = generateSequence(from, action).drop(1).takeWhile { it in forest } fun seenFromDirection(forest: Forest, direction: Sequence<Pos>, pos: Pos) = direction.all { forest[it] < forest[pos] } fun checkVisibility(forest: Forest, pos: Pos): Boolean { val leftRange = goIntoForest(forest, pos, Pos::moveLeft) val rightRange = goIntoForest(forest, pos, Pos::moveRight) val upRange = goIntoForest(forest, pos, Pos::moveUp) val downRange = goIntoForest(forest, pos, Pos::moveDown) return listOf(leftRange, rightRange, upRange, downRange) .any { direction -> seenFromDirection(forest, direction, pos) } } fun positionsFor(forest: Forest): Sequence<Pos> = sequence { for (row in 0 until forest.rows) { for (column in 0 until forest.columns) { yield(Pos(row, column)) } } } fun part1(input: List<String>): Int { val forest = Forest(input) return positionsFor(forest).count { checkVisibility(forest, it) } } fun countVisibleTrees(forest: Forest, direction: Sequence<Pos>, viewPos: Pos): Int { var count = 0 for (pos in direction) { count += 1 if (forest[pos] >= forest[viewPos]) break } return count } fun ratePosition(forest: Forest, pos: Pos): Int { val leftRange = goIntoForest(forest, pos, Pos::moveLeft) val rightRange = goIntoForest(forest, pos, Pos::moveRight) val upRange = goIntoForest(forest, pos, Pos::moveUp) val downRange = goIntoForest(forest, pos, Pos::moveDown) val numberOfTreesFromSides = listOf(leftRange, rightRange, upRange, downRange) .map { direction -> countVisibleTrees(forest, direction, pos) } return numberOfTreesFromSides.fold(1, Int::times) } fun part2(input: List<String>): Int { val forest = Forest(input) return positionsFor(forest).maxOf { ratePosition(forest, it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
3,051
aoc2022
Apache License 2.0
kotlin/app/src/main/kotlin/coverick/aoc/day12/hillClimbing.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day12 import java.util.PriorityQueue import java.util.HashSet import readResourceFile val INPUT_FILE = "hillClimbing-input.txt" typealias Coordinate = Pair<Int,Int> class Hill(val heightMap:List<CharArray>, val startHeights: Set<Char>, val end:Char){ var startPos: HashSet<Coordinate> = HashSet<Coordinate>() var endPos: Coordinate = Coordinate(0,0) val unvisited = HashSet<Coordinate>() // determine start and end coordinates on grid init { for(i in 0..heightMap.size-1){ for(j in 0..heightMap.get(i).size - 1){ if(startHeights.contains(heightMap.get(i).get(j))){ startPos.add(Coordinate(i,j)) } else if (heightMap.get(i).get(j) == end){ endPos = Coordinate(i,j) } unvisited.add(Coordinate(i,j)) } } println("All starting points: ${startPos}") } // replace heights of start and end with 'a' and 'z' respectively init { startPos.forEach{ heightMap.get(it.first).set(it.second, 'a') } heightMap.get(endPos.first).set(endPos.second, 'z') } fun getHeight(c:Coordinate) : Char { return heightMap.get(c.first).get(c.second) } fun isValidCoordinate(c:Coordinate): Boolean { return c.first >= 0 && c.first < heightMap.size && c.second >= 0 && c.second < heightMap.get(0).size } fun isValidMove(from:Coordinate, to:Coordinate): Boolean { val fromHeight = getHeight(from) val toHeight = getHeight(to) return toHeight - fromHeight <= 1 } // return only unvisited adjacent nodes not including diagonals fun getNextMoves(c:Coordinate) : List<Coordinate>{ return hashSetOf( Coordinate(c.first + 1, c.second), Coordinate(c.first - 1, c.second), Coordinate(c.first, c.second - 1), Coordinate(c.first, c.second + 1) ).filter{ isValidCoordinate(it) && isValidMove(c,it)} } fun getShortestPathToEnd(): Int? { return startPos.map{bfs(it)}.sortedWith(compareBy{it}).first() } fun bfs(curNode: Coordinate): Int { // keep track of visited nodes val visited = HashSet<Coordinate>() val distances = HashMap<Coordinate, Int>() // order by current distance from origin point val q = PriorityQueue<Coordinate>(compareBy{distances.getOrDefault(it, Int.MAX_VALUE)}) distances.put(curNode, 0) visited.add(curNode) var result = Int.MAX_VALUE q.add(curNode) while(q.size > 0){ val current = q.poll() val neighbors = getNextMoves(current) for(neighbor in neighbors){ if(neighbor == endPos){ if(distances.getOrDefault(current, Int.MAX_VALUE) < result){ result = distances.getOrDefault(current, Int.MAX_VALUE) + 1 } } else if(!visited.contains(neighbor)){ distances.put(neighbor, distances.getOrDefault(current, 0)+1) visited.add(neighbor) q.add(neighbor) } } } return result } } fun part1():Int?{ val heightMap = readResourceFile(INPUT_FILE).map{it.toCharArray()} val hill = Hill(heightMap, setOf('S'), 'E') return hill.getShortestPathToEnd() } fun part2(): Int?{ val heightMap = readResourceFile(INPUT_FILE).map{it.toCharArray()} val hill = Hill(heightMap, setOf('S','a'), 'E') return hill.getShortestPathToEnd() } fun solution(){ println("Hill Climbing Algorithm Part 1: ${part1()}") println("Hill Climbing Algorithm Part 2: ${part2()}") }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
3,817
adventofcode2022
Apache License 2.0
src/com/github/frozengenis/day2/Puzzle.kt
FrozenSync
159,988,833
false
null
package com.github.frozengenis.day2 import java.io.File import java.util.* fun main() { val boxes = File("""src\com\github\frozengenis\day2\input.txt""") .let(::parseToBoxes) val checksum = calculateChecksum(boxes) val commonLetters = findCommonLetters(boxes) StringBuilder("Advent of Code 2018 - Day 2").appendln().appendln() .appendln("Checksum: $checksum") .appendln("Common letters: $commonLetters") .let(::print) } private fun parseToBoxes(inputFile: File): List<Box> { val scanner = Scanner(inputFile) val result = mutableListOf<Box>() while (scanner.hasNext()) { scanner.next() .let(::Box) .let(result::add) } return result } private fun calculateChecksum(boxes: List<Box>): Int = boxes .fold(Pair(0, 0)) { acc, e -> accumulateFrequencyCounts(acc, e) } .let { it.first * it.second } private fun accumulateFrequencyCounts(acc: Pair<Int, Int>, box: Box): Pair<Int, Int> { val appearances = checkForFrequenciesIn(box.id) if (!appearances.first && !appearances.second) return acc val frequencyOfTwoCount = if (appearances.first) acc.first + 1 else acc.first val frequencyOfThreeCount = if (appearances.second) acc.second + 1 else acc.second return acc.copy(frequencyOfTwoCount, frequencyOfThreeCount) } /** * Returns a [Pair] with the following conditions: * - the first value is true if [boxId] contains a letter with a frequency of two; false otherwise * - the second value is true if [boxId] contains a letter with a frequency of three; false otherwise. */ private fun checkForFrequenciesIn(boxId: String): Pair<Boolean, Boolean> { val scanner = Scanner(boxId).useDelimiter("") val frequencyOfChars = mutableMapOf<Char, Int>() while (scanner.hasNext()) { val char = scanner.next()[0] val frequency = frequencyOfChars.getOrDefault(char, defaultValue = 0) if (frequency > 3) continue frequencyOfChars[char] = frequency + 1 } return Pair(frequencyOfChars.values.contains(2), frequencyOfChars.values.contains(3)) } private fun findCommonLetters(boxes: List<Box>) = boxes .let(::findPair) .let { it.first.id.filterCommon(it.second.id) } private fun findPair(boxes: List<Box>): Pair<Box, Box> { val result = boxes.filter { box1 -> boxes.any { box1.id.hasDistanceOf(1, it.id) } } if (result.size != 2) throw IllegalArgumentException("Invalid input") return Pair(result[0], result[1]) }
0
Kotlin
0
0
ec1e3472990a36b4d2a2270705253c679bee7618
2,543
advent-of-code-2018
The Unlicense
src/Day18.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
data class XYZ(val x: Int, val y: Int, val z: Int) fun getImmediateSurrounding(cube: XYZ): List<XYZ> { val rel = listOf(XYZ(-1, 0, 0), XYZ(1, 0, 0), XYZ(0, -1, 0), XYZ(0, 1, 0), XYZ(0, 0, -1), XYZ(0, 0, 1)) return rel.map { coordinate -> XYZ(cube.x + coordinate.x, cube.y + coordinate.y, cube.z + coordinate.z) } } fun toCubes(input: List<String>): List<XYZ> = input.map { it.split(",") }.map { trio -> XYZ(trio[0].toInt(), trio[1].toInt(), trio[2].toInt()) } const val CUBE_SIDES = 6 fun main() { fun part1(input: List<String>): Int { val cubes = toCubes(input) toCubes(input).sumOf { cube -> (CUBE_SIDES - getImmediateSurrounding(cube).filter { surroundingCube -> cubes.contains( surroundingCube ) }.size) } } /** * A cube is reachable for steam when: * - cube is on the edge of the 3d matrix * - cube has at least one ImmediateSurrounding cube that is reachable. */ fun part2(input: List<String>): Int { val cubes = toCubes(input) toCubes(input).sumOf { cube -> (CUBE_SIDES - getImmediateSurrounding(cube).filter { surroundingCube -> cubes.contains( surroundingCube ) }.size) } } val testInput = readInput("Day18_test") //println(part1(testInput)) println(part2(testInput)) val input = readInput("Day18") //println(part1(input)) //println(part2(input)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
1,541
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day11/day11.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day11 class Ferry(private var seats: List<String>, private val tolerance: Int, closeNeighbourhood: Boolean = true) { companion object { const val EMPTY = 'L' const val OCCUPIED = '#' } private val checker = when (closeNeighbourhood) { true -> CloseNeighbourChecker() false -> FarNeighbourChecker() } fun getSeat(y: Int, x: Int): Char { return seats[y][x] } abstract inner class NeighbourChecker { abstract fun check(y: Int, x: Int, direction: Pair<Int, Int>): Boolean } inner class CloseNeighbourChecker : NeighbourChecker() { override fun check(y: Int, x: Int, direction: Pair<Int, Int>): Boolean { val ny = y + direction.first val nx = x + direction.second return ny >= 0 && ny < seats.size && nx >= 0 && nx < seats[0].length && getSeat(ny, nx) == OCCUPIED } } inner class FarNeighbourChecker : NeighbourChecker() { override fun check(y: Int, x: Int, direction: Pair<Int, Int>): Boolean { var ny = y + direction.first var nx = x + direction.second while (ny >= 0 && ny < seats.size && nx >= 0 && nx < seats[0].length) { when (getSeat(ny, nx)) { OCCUPIED -> return true EMPTY -> return false } ny += direction.first nx += direction.second } return false } } private fun countNeighbours(y: Int, x: Int): Int { val directions = generateDirections() var count = 0 for (dir in directions) { if (checker.check(y, x, dir)) { count += 1 } } return count } private fun generateDirections(): MutableList<Pair<Int, Int>> { val directions = mutableListOf<Pair<Int, Int>>() for (dy in -1..1) { for (dx in -1..1) { if (dy == 0 && dx == 0) continue directions.add(Pair(dy, dx)) } } return directions } fun step(): Boolean { val newSeats = seats.mapIndexed { rowId, row -> row.mapIndexed { colId, seat -> val occupied = countNeighbours(rowId, colId) when (seat) { EMPTY -> if (occupied == 0) OCCUPIED else EMPTY OCCUPIED -> if (occupied >= tolerance) EMPTY else OCCUPIED else -> seat } }.joinToString("") }.toList() val changed = newSeats == seats seats = newSeats return changed } fun countOccupied(): Int { return seats.map { it.filter { seat -> seat == OCCUPIED }.count() }.sum() } override fun toString(): String { return "count : ${countOccupied()}\n${seats.joinToString("\n")}\n" } } fun solve(ferry: Ferry): Int { var afterStep = ferry.countOccupied() var beforeStep: Int do { beforeStep = afterStep ferry.step() afterStep = ferry.countOccupied() } while (beforeStep != afterStep) return beforeStep } fun main() { val seats = {}::class.java.getResource("/day11.in") .readText() .split("\n") println("Answer part 1: ${solve(Ferry(seats, 4))}") println("Answer part 2: ${solve(Ferry(seats, 5, false))}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
3,441
advent-of-code-2020
Do What The F*ck You Want To Public License
leetcode2/src/leetcode/unique-paths.kt
hewking
68,515,222
false
null
package leetcode import kotlin.math.max import kotlin.math.min /** * 62. 不同路径 * https://leetcode-cn.com/problems/unique-paths/ * 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 说明:m 和 n 的值均不超过 100。 示例 1: 输入: m = 3, n = 2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2. 向右 -> 向下 -> 向右 3. 向下 -> 向右 -> 向右 示例 2: 输入: m = 7, n = 3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object UniquePaths { class Solution { /** * 解法: * 牛批大佬小学数学解法 * https://leetcode-cn.com/problems/unique-paths/solution/xiao-xue-ti-java-by-biyu_leetcode/ */ fun uniquePaths(m: Int, n: Int): Int { if (m <= 0 || n <= 0) { return 0 } val more = max(m, n) val less = min(m, n) val dp = IntArray(less) dp.fill(1) for (i in 1 until more) { for (j in 1 until less) { dp[j] += dp[j - 1] } } return dp[less - 1] } /** * 解法2: * 动态规划: * 可以看到到达右下角记为二维数组中的dp[m,n] * 到达那个位置的路线数等于到达它上方的点的路线数 加上 到达它左边的路线数。 * 即 dp[m,n]= dp[m,n-1] + dp[m-1,n],即是状态转移公式,接下来找 * 自顶向下的解法。 然后拓展到自底向上的解法 * https://leetcode-cn.com/problems/unique-paths/solution/cde-di-gui-qiu-jie-by-rose-chen/ */ val paths = Array<IntArray>(101){ IntArray(101) } fun uniquePaths2(m: Int, n: Int): Int { if(m <= 0 || n <= 0) { return 0 } if (m ==1 || n == 1) return 1 if (m == 2 && n == 2) return 2 if (m == 3 && n == 2 || n == 3 && m == 2) return 3 if (paths[m][n] > 0) { return paths[m][n] } paths[m][n-1] = uniquePaths2(m,n-1) paths[m-1][n-1] = uniquePaths2(m-1,n) return paths[m][n-1] + paths[m-1][n-1] } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,784
leetcode
MIT License
src/y2015/Day06.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.getRange import util.printMatrix import util.readInput import kotlin.math.max data class Light(var on: Boolean = false, var brightness: Int = 0) { fun toggle() { on = !on } fun turnOn() { on = true } fun turnOff() { on = false } fun increase() { brightness += 1 } fun decrease() { brightness = max(brightness - 1, 0) } fun jump() { increase() increase() } } data class Switch( val instruction: String, val startRow: Int, val stopRow: Int, val startCol: Int, val stopCol: Int ) object Day06 { private fun parse(input: List<String>): List<Switch> { return input.map { line -> val (ins, start, _, stop) = line.split(' ').takeLast(4) val (rowStart, colStart) = start.split(',').map { it.toInt() } val (rowStop, colStop) = stop.split(',').map { it.toInt() } Switch( ins, rowStart, rowStop, colStart, colStop ) } } fun part1(input: List<String>): Int { val parsed = parse(input) val lightGrid = List(1000) { List(1000) {Light()} } parsed.forEach { getRange(lightGrid, it.startRow, it.startCol, it.stopRow, it.stopCol).map { light -> when (it.instruction) { "on" -> light.turnOn() "off" -> light.turnOff() else -> light.toggle() } } } printMatrix(lightGrid) { if (it.on) "*" else " " } return lightGrid.flatten().filter { it.on }.size } fun part2(input: List<String>): Int { val parsed = parse(input) val lightGrid = List(1000) { List(1000) {Light()} } parsed.forEach { getRange(lightGrid, it.startRow, it.startCol, it.stopRow, it.stopCol).map { light -> when (it.instruction) { "on" -> light.increase() "off" -> light.decrease() else -> light.jump() } } } printMatrix(lightGrid) { it.brightness.toString() } return lightGrid.flatten().sumOf { it.brightness } } } fun main() { val testInput = """ turn on 0,0 through 999,999 toggle 0,0 through 999,0 turn off 499,499 through 500,500 """.trimIndent().split("\n") println("------Tests------") println(Day06.part1(testInput)) println(Day06.part2(testInput)) println("------Real------") val input = readInput("resources/2015/day06") println(Day06.part1(input)) println(Day06.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,803
advent-of-code
Apache License 2.0
src/day5/puzzle05.kt
brendencapps
572,821,792
false
{"Kotlin": 70597}
package day5 import Puzzle import PuzzleInput import java.io.File import java.lang.Integer.min import java.util.* import kotlin.math.max data class Move(val crate: Int, val from: Int, val to: Int) class Day5PuzzleInput(val stacks: List<Vector<Char>>, private val moves: String, expectedResult: String? = null) : PuzzleInput<String>(expectedResult) { fun doMoves(op: (stacks: List<Vector<Char>>, move: Move) -> Unit) { val inputParser = "move (\\d+) from (\\d+) to (\\d+)".toRegex() File(moves).readLines().forEach { action -> val (crates, from, to) = inputParser.find(action)!!.destructured op(stacks, Move(crates.toInt(), from.toInt() - 1, to.toInt() - 1)) } } } class Day5PuzzleSolutionPuzzle1 : Puzzle<String, Day5PuzzleInput>() { override fun solution(input: Day5PuzzleInput): String { input.doMoves { stacks, move -> for(i in 1 ..move.crate) { if(stacks[move.from].isNotEmpty()) { stacks[move.to].add(stacks[move.from].removeLast()) } } } return input.stacks.map { stack -> if(stack.isNotEmpty()) { stack.last() } else { " " } }.joinToString("") } } class Day5PuzzleSolutionPuzzle2 : Puzzle<String, Day5PuzzleInput>() { override fun solution(input: Day5PuzzleInput): String { input.doMoves { stacks, move -> val start = max(0, stacks[move.from].size - move.crate) val end = min(stacks[move.from].size - 1, start + move.crate) for(i in start .. end) { stacks[move.to].add(stacks[move.from].removeAt(start)) } } return input.stacks.map { stack -> if(stack.isNotEmpty()) { stack.last() } else { " " } }.joinToString("") } } fun day5Puzzle() { val inputDir = "inputs/day5" Day5PuzzleSolutionPuzzle1().solve(Day5PuzzleInput(getExampleStart(), "$inputDir/example.txt", "CMZ")) Day5PuzzleSolutionPuzzle1().solve(Day5PuzzleInput(getInputStart(), "$inputDir/input.txt", "TWSGQHNHL")) Day5PuzzleSolutionPuzzle2().solve(Day5PuzzleInput(getExampleStart(), "$inputDir/example.txt", "MCD")) Day5PuzzleSolutionPuzzle2().solve(Day5PuzzleInput(getInputStart(), "$inputDir/input.txt", "JNRSCDWPP")) } fun getInputStart(): List<Vector<Char>> { return listOf("LNWTD", "CPH", "WPHNDGMJ", "CWSNTQL", "PHCN", "THNDMWQB", "MBRJGSL", "ZNWGVBRT", "WGDNPL").map {Vector(it.toList()) } } fun getExampleStart(): List<Vector<Char>> { return mutableListOf("ZN", "MCD", "P").map{ Vector(it.toList()) } }
0
Kotlin
0
0
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
2,827
aoc_2022
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day14/Day14.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pietromaggi.aoc2021.day14 import com.pietromaggi.aoc2021.readInput data class Rule(val a: Char, val b: Char) fun parseInput(input: List<String>): Pair<String, Map<Rule, Char>> { val template = input[0].trim() val rules = mutableMapOf<Rule, Char>() input.takeLastWhile { it.isNotBlank() } .map { line -> val (a, b) = line.split(" -> ") rules[Rule(a[0], a[1])] = b[0] } return Pair(template, rules) } fun compute(input: List<String>, steps: Int): Long { val (template, rules) = parseInput(input) var polymer = mutableMapOf<Rule, Long>() template.zipWithNext().forEach { (first, second) -> val rule = Rule(first, second) polymer[rule] = polymer.getOrDefault(rule, 0) + 1 } for (step in 1..steps) { val temp = mutableMapOf<Rule, Long>() polymer.forEach { (rule, count) -> val newElement = rules[rule]!! val rule1 = Rule(rule.a, newElement) val rule2 = Rule(newElement, rule.b) temp[rule1] = temp.getOrDefault(rule1, 0) + count temp[rule2] = temp.getOrDefault(rule2, 0) + count } polymer = temp } val polymerFrequency = mutableMapOf<Char, Long>() polymer.forEach { (rule, value) -> polymerFrequency[rule.a] = polymerFrequency.getOrDefault(rule.a, 0) + value polymerFrequency[rule.b] = polymerFrequency.getOrDefault(rule.b, 0) + value } polymerFrequency[template.first()] = polymerFrequency[template.first()]!! + 1 polymerFrequency[template.last()] = polymerFrequency[template.last()]!! + 1 val finalCount = polymerFrequency.map { (_, value) -> value / 2 }.sorted() return finalCount.last() - finalCount.first() } fun main() { val input = readInput("Day14") println(compute(input, 10)) println(compute(input, 40)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
2,472
AdventOfCode
Apache License 2.0
src/Day15.kt
zsmb13
572,719,881
false
{"Kotlin": 32865}
import kotlin.math.abs fun main() { data class Beacon(val x: Int, val y: Int) data class Sensor(val x: Int, val y: Int, val beaconDist: Int) fun dist(x1: Int, y1: Int, x2: Int, y2: Int): Int { return abs(x1 - x2) + abs(y1 - y2) } fun parse(testInput: List<String>): List<List<Int>> = testInput.map { line -> val format = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() format.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() } } fun part1(testInput: List<String>, xRange: IntRange, yRange: IntRange): Int { val input = parse(testInput) val sensors = input.map { (x, y, bx, by) -> Sensor(x, y, dist(x, y, bx, by)) } val beacons = input.map { (_, _, bx, by) -> Beacon(bx, by) } fun isValid(x: Int, y: Int): Boolean { return beacons.any { b -> x == b.x && y == b.y } || sensors.all { s -> dist(s.x, s.y, x, y) > s.beaconDist } } return xRange.sumOf { x -> yRange.count { y -> !isValid(x, y) } } } /** * Generate all points that are just out-of-reach for the given sensor. * * Shout-out to <NAME> (Nohus) for the idea * https://kotlinlang.slack.com/archives/C87V9MQFK/p1671087279597559?thread_ts=1671080400.425969&cid=C87V9MQFK */ fun Sensor.pointsOutOfReach(): Sequence<Beacon> { val tooFar = beaconDist + 1 return sequence { for (i in 0..tooFar) { yield(Beacon(x + i, y - tooFar + i)) yield(Beacon(x + tooFar - i, y - i)) yield(Beacon(x - i, y - tooFar + i)) yield(Beacon(x - tooFar + i, y - i)) } } } fun part2(testInput: List<String>, xRange: IntRange, yRange: IntRange): Long { val sensors = parse(testInput).map { (x, y, bx, by) -> Sensor(x, y, dist(x, y, bx, by)) } fun isValid(x: Int, y: Int) = sensors.all { s -> dist(s.x, s.y, x, y) > s.beaconDist } sensors.forEach { s -> s.pointsOutOfReach() .filter { it.x in xRange && it.y in yRange } .forEach { (x, y) -> if (isValid(x, y)) { return x.toLong() * 4_000_000 + y.toLong() } } } error("Beacon not found") } val testInput = readInput("Day15_test") check(part1(testInput = testInput, xRange = -50..50, yRange = 10..10) .also(::println) == 26) check(part2(testInput = testInput, xRange = 0..20, yRange = 0..20) .also(::println) == 56000011L) val input = readInput("Day15") check(part1(testInput = input, xRange = -1_000_000..5_000_000, yRange = 2_000_000..2_000_000) .also(::println) == 5100463) check(part2(testInput = input, xRange = 0..4_000_000, yRange = 0..4_000_000) .also(::println) == 11557863040754L) }
0
Kotlin
0
6
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
3,057
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day7.kt
bfrengley
318,716,410
false
null
package aoc2020.day7 import aoc2020.util.loadTextResource const val bagTypePattern = "([a-z]+ [a-z]+) bags?" val outerBagRegex = Regex(bagTypePattern) val innerBagRegex = Regex("(\\d+) $bagTypePattern") data class Rule(val outer: String, val inners: List<Pair<String, Int>>) fun main(args: Array<String>) { val rawRules = loadTextResource("/day7.txt").lines() val rules = rawRules.map(::parseRule) print("Part 1: ") val rules1 = bottomUpRules(rules) println(containingBags("shiny gold", rules1).size) print("Part 2: ") println(containedBags("shiny gold", rules.map { (outer, inner) -> Pair(outer, inner) }.toMap())) } fun parseRule(rule: String): Rule = rule.split("contain").let { (outerRaw, innersRaw) -> outerBagRegex.find(outerRaw)!!.groupValues[1].let { outer -> val inners = innerBagRegex.findAll(innersRaw).map { val (_, count, bagType) = it.groupValues Pair(bagType, count.toInt()) }.toList() Rule(outer, inners) } } fun bottomUpRules(rules: List<Rule>): Map<String, Set<String>> = rules // extract (outer, inner) pairs from the rules .flatMap { (outer, inners) -> inners.map { Pair(outer, it.first) } } // group them by the inner bag type (inner -> List<(outer, inner)>) .groupBy { it.second } // get the inners and convert them to a set .mapValues { (_, value) -> value.map { it.first }.toSet() } fun containingBags(innerBag: String, rules: Map<String, Set<String>>): Set<String> = when (val outers = rules[innerBag]) { null -> setOf() else -> outers .map { containingBags(it, rules) } .fold(outers) { acc, allOuters -> acc.union(allOuters) } } fun containedBags(outerBag: String, rules: Map<String, List<Pair<String, Int>>>): Int { fun containedBagsRec(outerBag_: String, rules_: Map<String, List<Pair<String, Int>>>): Int = 1 + (rules_[outerBag_] ?.map { (bagType, count) -> count * containedBagsRec(bagType, rules_) } ?.sum() ?: 1) return containedBagsRec(outerBag, rules) - 1 }
0
Kotlin
0
0
088628f585dc3315e51e6a671a7e662d4cb81af6
2,176
aoc2020
ISC License
src/Day11.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
fun main() { val input = readInput("Day11") printTime { println(Day11.part1(input)) } printTime { println(Day11.part2(input)) } } class Day11 { companion object { fun part1(input: List<String>): Long { val monkeys = input.toMonkeys() monkeys.playKeepAway { it.floorDiv(3) } return monkeys.getMonkeyBusiness() } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val commonMod = monkeys.map { it.divideBy }.lcm().toInt() monkeys.playKeepAway(10000) { it % commonMod } return monkeys.getMonkeyBusiness() } } } data class Monkey( val divideBy: Long, val trueTo: Int, val falseTo: Int, val items: MutableList<Long> = mutableListOf(), val operation: (Long) -> Long ) { var inspections = 0L } fun Long.doOperation(charOperator: Char, x: Long) = when (charOperator) { '+' -> this + x '*' -> this * x else -> throw IllegalArgumentException("Not supported") } fun List<String>.toMonkeys(): List<Monkey> { return this.chunked(7).map { val items: MutableList<Long> = it[1].substring(18).split(", ").map { item -> item.toLong() }.toMutableList() val (operator, operand) = it[2].substring(23).split(" ") val operation: (Long) -> Long = { old: Long -> old.doOperation( operator.toCharArray().first(), if (operand == "old") old else operand.toLong() ) } val divideBy = it[3].substring(21).toLong() val trueTo = it[4].substring(29).toInt() val falseTo = it[5].substring(30).toInt() Monkey(divideBy, trueTo, falseTo, items, operation) } } fun List<Monkey>.playKeepAway(rounds: Int = 20, escalationPrevention: (Long) -> Long) { repeat(rounds) { for (monkey in this) { for (item in monkey.items) { monkey.inspections++ val worry = escalationPrevention(monkey.operation(item)) val toMonkey = if (worry isDivisibleBy monkey.divideBy) monkey.trueTo else monkey.falseTo this[toMonkey].items.add(worry) } monkey.items.clear() } } } fun List<Monkey>.getMonkeyBusiness() = this.map { it.inspections }.sortedDescending().take(2).product()
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
2,352
advent-of-code-22
Apache License 2.0
src/year2023/day14/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2023.day14 import year2023.solveIt fun main() { val day = "14" val expectedTest1 = 136L val expectedTest2 = 64L fun getColumn(chars: List<Char>): Long { var total = 0L var lastSupport = 0 for (index in chars.indices) { if (chars[index] == 'O') { total += chars.size - lastSupport lastSupport++ } if (chars[index] == '#') { lastSupport = index + 1 } } return total } fun rotate(input: List<String>): List<String> { val temp = input.map { it.reversed() } return input[0].indices.map { i -> temp.map { it[i] }.joinToString("") } } fun sort(v: List<Char>): String { val map = (listOf(0) + v.mapIndexedNotNull { index, c -> if (c == '#') index else null } + v.size).zipWithNext { a, b -> v.subList(a, b) }.map { it.filter { c -> c == '#' } + it.filter { c -> c != '#' }.sortedDescending() } val joinToString = map.flatten().joinToString("") return joinToString } fun part1(input: List<String>): Long { val rotate = rotate(input) val columns = rotate.map { sort(it.toList()) } val map = columns.map { getColumn(it.toList()) } return map.sum() } fun printIt(current: List<String>) { current.forEach { println(it) } println() println() } fun getIt(chars: List<Char>): Long { return chars.mapIndexedNotNull{index, c -> if(c=='O'){chars.size-index } else null}.sum().toLong() } fun part2(input: List<String>): Long { val cycleCache = mutableMapOf<List<String>, List<String>>() val cache = mutableMapOf<String, String>() var current = input; repeat(1000000000) { current = cycleCache.getOrPut(current) { var v = current; v = rotate(v).map { sort(it.toList()) } v = rotate(rotate(rotate(v))).map { sort(it.toList()) } v = rotate(rotate(rotate(v))).map { sort(it.toList()) } v = rotate(rotate(rotate(v))).map { sort(it.toList()) } rotate(rotate(v)) } // println(rotate(current).sumOf { getIt(it.toList()) }) //printIt(current) } return rotate(current).sumOf { getIt(it.toList()) } } solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test") }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
2,525
adventOfCode
Apache License 2.0
src/main/kotlin/day03/engine.kt
cdome
726,684,118
false
{"Kotlin": 17211}
package day03 import java.io.File import kotlin.text.StringBuilder fun main() { val lines = File("src/main/resources/day03-engine").readLines() println("Sum of part numbers: ${engineSum(lines)}") println("Sum of gear ratios: ${gears(lines)}") } fun gears(lines: List<String>): Int { val emptyLine = ".".repeat(lines[0].length) val extendedLines = listOf(emptyLine) + lines + emptyLine val numbers: List<List<Pair<IntRange, Int>>> = rangeNumbers(extendedLines) return extendedLines.mapIndexed { lineNo, line -> line.mapIndexed { charNo, char -> if (char == '*') { val gearedParts = getAdjacentNumbers(charNo, numbers[lineNo - 1]) + getAdjacentNumbers(charNo, numbers[lineNo + 1]) + getAdjacentNumbers(charNo, numbers[lineNo]) if (gearedParts.size == 2) gearedParts[0] * gearedParts[1] else 0 } else 0 } }.flatten().sum() } fun getAdjacentNumbers(position: Int, line: List<Pair<IntRange, Int>>) = line .filter { (range, _) -> range.contains(position) || range.contains(position + 1) || range.contains(position - 1) } .map { (_, number) -> number } private fun rangeNumbers(lines: List<String>) = lines.map { line -> var inNumber = false val rowRanges = mutableListOf<Pair<IntRange, Int>>() val actualNumber = StringBuilder() var beginning = -1 line.forEachIndexed { index, c -> if (c.isDigit()) actualNumber.append(c) if (c.isDigit() && !inNumber) { beginning = index inNumber = true } if ((!c.isDigit() || index == line.length - 1) && inNumber) { rowRanges.add(beginning..<index to actualNumber.toString().toInt()) actualNumber.clear() inNumber = false } } rowRanges } fun engineSum(lines: List<String>): Int { val emptyLine = ".".repeat(lines[0].length + 2) return lines .mapIndexed { id, line -> fun extendLine(line: String) = StringBuilder(".").append(line).append(".").toString() val above = if (id == 0) emptyLine else extendLine(lines[id - 1]) val below = if (id == lines.size - 1) emptyLine else extendLine(lines[id + 1]) processLine(extendLine(line), above, below) } .flatten() .sum() } fun processLine(line: String, above: String, below: String): List<Int> { val lineNumbers = mutableListOf<Int>() val actualNumber = StringBuilder() var wasSymbol = false line.forEachIndexed() { position, char -> val charAbove = above[position] val charBelow = below[position] fun isSymbol(char: Char) = !char.isDigit() && char != '.' fun hasSymbol() = isSymbol(char) || isSymbol(charAbove) || isSymbol(charBelow) if (!char.isDigit() && (actualNumber.isNotEmpty() && (wasSymbol || hasSymbol()))) lineNumbers.add( actualNumber.toString().toInt() ) if (char.isDigit()) actualNumber.append(char) if (!char.isDigit()) actualNumber.clear() if (hasSymbol()) wasSymbol = true if (char == '.' && !isSymbol(charAbove) && !isSymbol(charBelow)) wasSymbol = false } return lineNumbers }
0
Kotlin
0
0
459a6541af5839ce4437dba20019b7d75b626ecd
3,268
aoc23
The Unlicense
y2017/src/main/kotlin/adventofcode/y2017/Day10.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day10 : AdventSolution(2017, 10, "Knot Hash") { override fun solvePartOne(input: String): String { val lengths = input.split(",").map { it.toInt() } val list = knot(lengths) return (list[0] * list[1]).toString() } override fun solvePartTwo(input: String): String { val denseHash = knotHash(input) return denseHash.joinToString("") { it.toString(16).padStart(2, '0') } } } fun knotHash(input: String): List<Int> { val lengths = input.map { it.code } + listOf(17, 31, 73, 47, 23) val rounds = (1..64).flatMap { lengths } val sparseHash = knot(rounds) return sparseHash.chunked(16) { it.reduce(Int::xor) } } private fun knot(lengths: List<Int>): List<Int> { val initial = (0..255).toList() val list = lengths.foldIndexed(initial) { skip, list, length -> val knot = list.drop(length) + list.take(length).reversed() knot.rotateLeft(skip) } //undo all previous rotations val rotation = lengths.withIndex() .sumOf { (i, l) -> i + l } % list.size return list.rotateLeft(list.size - rotation) } private fun List<Int>.rotateLeft(n: Int) = drop(n % size) + take(n % size)
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,174
advent-of-code
MIT License
src/Day08.kt
maximilianproell
574,109,359
false
{"Kotlin": 17586}
fun main() { fun part1(input: TreeData): Int { val (trees, width, height) = input // That's the border of the map, which is always visible. val visibleEdge = width * 2 + height * 2 - 4 // Minus the corners var insideVisible = 0 val startIndex = width + 1 val endIndex = width * height - 1 - width - 1 // Minus the edge fun isEdge(index: Int): Boolean { return index < width || // first row index >= (width * height - width) || // last row (index + 1) % width == 0 || // right edge index % width == 0 // left edge } for (i in startIndex..endIndex) { if (isEdge(i)) continue val thisTree = trees[i] val columnIndex = i % width val rowIndex = i / height val treesRight = trees.subList(i + 1, i + (width - columnIndex)) val treesLeft = trees.subList(rowIndex * width, i) val treesUp = trees .subList(columnIndex, i) .getEveryNthElement(width) val treesDown = trees .subList(i + width, trees.size) .getEveryNthElement(width) if (treesRight.all { it < thisTree } || treesLeft.all { it < thisTree } || treesUp.all { it < thisTree } || treesDown.all { it < thisTree }) { insideVisible++ } } println("visible because on edge: $visibleEdge") val visibleFromOutside = insideVisible println("visible from outside: $visibleFromOutside") return visibleEdge + visibleFromOutside } fun part2(input: List<String>): String { return "" } fun parseData(input: List<String>): TreeData { val width = input.first().length val height = input.size val treesList = input.flatMap { line -> line.toCharArray().map { it.digitToInt() } } val trees = arrayListOf(*treesList.toTypedArray()) return TreeData( trees = trees, arrayWidth = width, arrayHeight = height, ) } val testInput = """ 30373 25512 65332 33549 35390 """.trimIndent().lines() val input = readInput("Day08") // val input = testInput val treeData = parseData(input) println(part1(treeData)) println(part2(input)) } private data class TreeData( val trees: ArrayList<Int>, val arrayWidth: Int, val arrayHeight: Int, ) private fun <E> List<E>.getEveryNthElement(stepSize: Int): List<E> { return buildList { for (index in this@getEveryNthElement.indices step stepSize) { add(this@getEveryNthElement[index]) } } }
0
Kotlin
0
0
371cbfc18808b494ed41152256d667c54601d94d
2,832
kotlin-advent-of-code-2022
Apache License 2.0
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day08.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 object Day08 { fun numberOfVisibleTrees(input: String): Int { val trees = trees(input) return trees(input) .flatMap { (rowIndex, row) -> row.map { (columnIndex, tree) -> val hiddenFromTheLeft = row.take(columnIndex) .any { (_, otherTree) -> otherTree >= tree } val hiddenFromTheRight = row.drop(columnIndex + 1) .any { (_, otherTree) -> otherTree >= tree } val hiddenFromTheTop = trees.take(rowIndex) .any { (_, otherRow) -> otherRow[columnIndex].value >= tree } val hiddenFromTheBottom = trees.drop(rowIndex + 1) .any { (_, otherRow) -> otherRow[columnIndex].value >= tree } return@map !( hiddenFromTheLeft && hiddenFromTheRight && hiddenFromTheTop && hiddenFromTheBottom ) } }.count { visible -> visible } } fun highestScenicScore(input: String): Int { val trees = trees(input) return trees.flatMap { (rowIndex, row) -> row.map { (columnIndex, tree) -> val scenicScoreFromTheLeft = row.take(columnIndex) .reversed() .takeWhileInclusive { (_, otherTree) -> otherTree < tree } .count() val scenicScoreFromTheRight = row.drop(columnIndex + 1) .takeWhileInclusive { (_, otherTree) -> otherTree < tree } .count() val scenicScoreFromTheTop = trees.take(rowIndex) .reversed() .takeWhileInclusive { (_, otherRow) -> otherRow[columnIndex].value < tree } .count() val scenicScoreFromTheBottom = trees.drop(rowIndex + 1) .takeWhileInclusive { (_, otherRow) -> otherRow[columnIndex].value < tree } .count() return@map scenicScoreFromTheLeft * scenicScoreFromTheRight * scenicScoreFromTheTop * scenicScoreFromTheBottom } }.max() } private fun trees(input: String) = input .lines() .filter { it.isNotBlank() } .map { it .map { height -> height.digitToInt() } .withIndex() .toList() } .withIndex() .toList() private fun <T> Iterable<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = predicate(it) result } } }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
2,935
advent-of-code
MIT License
src/y2023/Day19.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.split import util.timingStatistics object Day19 { data class MachinePart( val x: Int, val m: Int, val a: Int, val s: Int ) { fun rating(): Int = x + m + a + s } data class RuleResult( val accepted: Boolean?, val reference: String? ) { companion object { fun fromString(str: String): RuleResult { return when (str) { "A" -> RuleResult(true, null) "R" -> RuleResult(false, null) else -> RuleResult(null, str) } } } } private fun parse(input: List<String>): Pair<MutableMap<String, List<(MachinePart) -> RuleResult>>, List<MachinePart>> { val (workflowsInput, machinePartsInput) = input.split { it.isBlank() } val workflows: MutableMap<String, List<(MachinePart) -> RuleResult>> = mutableMapOf() workflowsInput.forEach { val (name, rules) = it.split('{', '}') val ruleList = rules.split(',').map { rule -> if (':' !in rule) { { _: MachinePart -> RuleResult.fromString(rule) } } else { val (condition, result) = rule.split(':') val field = condition[0] val op = condition[1] val value = condition.drop(2).toInt() val refFun = when (field) { 'x' -> { part: MachinePart -> part.x } 'm' -> { part: MachinePart -> part.m } 'a' -> { part: MachinePart -> part.a } 's' -> { part: MachinePart -> part.s } else -> throw IllegalArgumentException("Unknown field $field") } val compFun = when (op) { '<' -> { a: Int, b: Int -> a < b } '>' -> { a: Int, b: Int -> a > b } else -> throw IllegalArgumentException("Unknown operator $op") } { part: MachinePart -> if (compFun(refFun(part), value)) { RuleResult.fromString(result) } else { RuleResult(null, null) } } } } workflows[name] = ruleList } val machineParts = machinePartsInput.map { line -> val (x, m, a, s) = line.dropLast(1).split('=', ',').chunked(2).map { it[1] } MachinePart(x.toInt(), m.toInt(), a.toInt(), s.toInt()) } return workflows to machineParts } fun part1(input: List<String>): Int { val (workflows, parts) = parse(input) return parts.filter { part -> var currentWorkflow = workflows["in"]!! var currentResult = currentWorkflow.first()(part) while (currentResult.accepted == null) { currentResult = currentWorkflow.map { it(part) }.first { it.accepted != null || it.reference != null } if (currentResult.accepted == null) { currentWorkflow = workflows[currentResult.reference!!]!! } } currentResult.accepted!! }.sumOf { it.rating() } } data class SearchSpace( val x: List<LongRange>, val m: List<LongRange>, val a: List<LongRange>, val s: List<LongRange>, val rules: List<Rule>, var ruleIdx: Int ) { fun size(): Long { return sumOfRanges(x) * sumOfRanges(m) * sumOfRanges(a) * sumOfRanges(s) } fun splitBy(field: Char, splitAt: Int): Pair<SearchSpace, SearchSpace> { val toSplit = when (field) { 'x' -> x 'm' -> m 'a' -> a 's' -> s else -> throw IllegalArgumentException("Unknown field $field") } val splitIdx = toSplit.indexOfFirst { splitAt in it } if (splitIdx == -1) { val (before, after) = toSplit.partition { it.last < splitAt } return splitTo(field, before, after) } else { val (before, after) = toSplit.take(splitIdx) to toSplit.drop(splitIdx + 1) val splitRange = toSplit[splitIdx] val (beforeSplit, afterSplit) = splitRange.first..splitAt to (splitAt + 1)..splitRange.last return splitTo(field, before + listOf(beforeSplit), listOf(afterSplit) + after) } } private fun splitTo( field: Char, before: List<LongRange>, after: List<LongRange> ) = when (field) { 'x' -> copy(x = before) to copy(x = after) 'm' -> copy(m = before) to copy(m = after) 'a' -> copy(a = before) to copy(a = after) 's' -> copy(s = before) to copy(s = after) else -> throw IllegalArgumentException("Unknown field $field") } } private fun sumOfRanges(ranges: List<LongRange>) = ranges.sumOf { it.last - it.first + 1 } data class Rule( val ref: Char?, val splitAt: Int?, val results: Pair<RuleResult, RuleResult?>, ) fun parse2(input: List<String>): MutableMap<String, List<Rule>> { val workflowsInput = input.takeWhile { it.isNotBlank() } val workflows: MutableMap<String, List<Rule>> = mutableMapOf() workflowsInput.forEach { line -> val (name, rules) = line.split('{', '}') workflows[name] = rules.split(',').map { rule -> if (':' !in rule) { Rule( ref = null, splitAt = null, results = RuleResult.fromString(rule) to null ) } else { val (condition, result) = rule.split(':') val field = condition[0] val op = condition[1] val value = condition.drop(2).toInt() val (split, results) = when (op) { '<' -> value - 1 to (RuleResult.fromString(result) to RuleResult(null, null)) '>' -> value to (RuleResult(null, null) to RuleResult.fromString(result)) else -> throw IllegalArgumentException("Unknown operator $op") } Rule( ref = field, splitAt = split, results = results ) } } } return workflows } fun part2(input: List<String>): Long { val workflows = parse2(input) val start = SearchSpace( x = listOf(1L..4000), m = listOf(1L..4000), a = listOf(1L..4000), s = listOf(1L..4000), rules = workflows["in"]!!, ruleIdx = 0 ) val acceptedSpaces = mutableListOf<SearchSpace>() var frontier = listOf(start) while (frontier.isNotEmpty()) { frontier = frontier.flatMap { space -> val rule = space.rules[space.ruleIdx++] val ref = rule.ref if (ref == null) { val ruleResult = rule.results.first listOfNotNull(updatedSearchSpaces(ruleResult, acceptedSpaces, space, workflows)) } else { val splitAt = rule.splitAt!! val (result1, result2) = rule.results val (space1, space2) = space.splitBy(ref, splitAt) listOfNotNull( updatedSearchSpaces(result1, acceptedSpaces, space1, workflows), updatedSearchSpaces(result2!!, acceptedSpaces, space2, workflows) ) } } } return acceptedSpaces.sumOf { it.size() } } private fun updatedSearchSpaces( ruleResult: RuleResult, acceptedSpaces: MutableList<SearchSpace>, space: SearchSpace, workflows: MutableMap<String, List<Rule>> ): SearchSpace? { if (ruleResult.accepted == true) { acceptedSpaces.add(space) } return if (ruleResult.accepted != null) { null } else if (ruleResult.reference == null) { space } else { space.copy(rules = workflows[ruleResult.reference]!!, ruleIdx = 0) } } } fun main() { val testInput = """ px{a<2006:qkq,m>2090:A,rfg} pv{a>1716:R,A} lnx{m>1548:A,A} rfg{s<537:gd,x>2440:R,A} qs{s>3448:A,lnx} qkq{x<1416:A,crn} crn{x>2662:A,R} in{s<1351:px,qqz} qqz{s>2770:qs,m<1801:hdj,R} gd{a>3333:R,R} hdj{m>838:A,pv} {x=787,m=2655,a=1222,s=2876} {x=1679,m=44,a=2067,s=496} {x=2036,m=264,a=79,s=2244} {x=2461,m=1339,a=466,s=291} {x=2127,m=1623,a=2188,s=1013} """.trimIndent().split("\n") println("------Tests------") println(Day19.part1(testInput)) println(Day19.part2(testInput)) println("------Real------") val input = readInput(2023, 19) println("Part 1 result: ${Day19.part1(input)}") println("Part 2 result: ${Day19.part2(input)}") timingStatistics { Day19.part1(input) } timingStatistics { Day19.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
9,655
advent-of-code
Apache License 2.0
src/Day11.kt
Fenfax
573,898,130
false
{"Kotlin": 30582}
import java.util.function.Function fun main() { fun firstNumberFromString(s: String): Long? { return s.dropWhile { !it.isDigit() }.takeWhile { it.isDigit() }.toLongOrNull() } fun parseMonkeys(input: List<String>): List<Monkey> { val monkeys = input.splitWhen { it == "" } val monkeyMap = monkeys.map { val number = firstNumberFromString(it[2]) firstNumberFromString(it[0]) to Monkey( firstNumberFromString(it[0]) ?: 0, ArrayDeque(it[1].split(":")[1].split(",").map { s -> s.trim().toLong() }), when { it[2].contains("+") -> { i: Long -> i + (number!!) } it[2].contains("*") -> { i: Long -> i * (number ?: i) } else -> throw NotImplementedError() }, firstNumberFromString(it[3]) ?: 0 ) } monkeys.forEach { val monkey = monkeyMap[firstNumberFromString(it[0])?.toInt()!!] monkey.second.successMonkey = monkeyMap[firstNumberFromString(it[4])?.toInt()!!].second monkey.second.failMonkey = monkeyMap[firstNumberFromString(it[5])?.toInt()!!].second } return monkeyMap.map { it.second } } fun solve(monkeys: List<Monkey>, rounds: Int, divide: Long): Long { val commonMultiple = monkeys.map { it.checkNumber }.reduce{ acc, l -> acc * l } for (unused in (1..rounds)) { monkeys.forEach { it.checkItems(divide, commonMultiple) } } return monkeys.asSequence() .sortedByDescending { it.checkedItems } .take(2) .map { it.checkedItems } .reduce { acc, i -> acc * i } } val input = readInput("Day11") println(solve(parseMonkeys(input), 20, 3)) println(solve(parseMonkeys(input), 10_000,1)) } data class Monkey( val number: Long, val holdingItems: ArrayDeque<Long>, val newFunction: Function<Long, Long>, val checkNumber: Long, var successMonkey: Monkey? = null, var failMonkey: Monkey? = null, var checkedItems: Long = 0 ) { fun checkItems(divide: Long, commonMultiple: Long) { while (!holdingItems.isEmpty()) { val item = newFunction.apply(holdingItems.removeFirst()) / (divide) if (item.mod(checkNumber) == 0L) successMonkey?.holdingItems?.add(item.mod(commonMultiple)) else failMonkey?.holdingItems?.add(item.mod(commonMultiple)) checkedItems += 1 } } override fun toString(): String { return "Monkey(number=$number, checkedItems =$checkedItems)" } }
0
Kotlin
0
0
28af8fc212c802c35264021ff25005c704c45699
2,813
AdventOfCode2022
Apache License 2.0
src/Day02.kt
jandryml
573,188,876
false
{"Kotlin": 6130}
import java.security.InvalidParameterException private enum class GameMove(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun evaluateGameResult(otherPlayerMove: GameMove): GameResult = when { this == otherPlayerMove -> GameResult.TIE this == ROCK && otherPlayerMove == SCISSORS -> GameResult.WIN this == SCISSORS && otherPlayerMove == PAPER -> GameResult.WIN this == PAPER && otherPlayerMove == ROCK -> GameResult.WIN else -> GameResult.LOSE } } private enum class GameResult(val score: Int) { WIN(6), TIE(3), LOSE(0); } private fun mapGameMove(rawInput: String): GameMove { return when (rawInput) { "A", "X" -> GameMove.ROCK "B", "Y" -> GameMove.PAPER "C", "Z" -> GameMove.SCISSORS else -> { throw InvalidParameterException() } } } private fun mapExpectedResult(rawInput: String): GameResult { return when (rawInput) { "X" -> GameResult.LOSE "Y" -> GameResult.TIE "Z" -> GameResult.WIN else -> { throw InvalidParameterException() } } } private fun resolvePlayerMove(otherPlayerMove: GameMove, expectedResult: GameResult): GameMove { return when (expectedResult) { GameResult.WIN -> when (otherPlayerMove) { GameMove.PAPER -> GameMove.SCISSORS GameMove.ROCK -> GameMove.PAPER GameMove.SCISSORS -> GameMove.ROCK } GameResult.LOSE -> when (otherPlayerMove) { GameMove.PAPER -> GameMove.ROCK GameMove.ROCK -> GameMove.SCISSORS GameMove.SCISSORS -> GameMove.PAPER } GameResult.TIE -> otherPlayerMove } } private fun calculateScore(input: List<String>, resolveRoundScore: (List<String>) -> Int): Int { var score = 0 input.forEach { score += resolveRoundScore(it.split(" ")) } return score } private fun part1(input: List<String>): Int { return calculateScore(input) { val playerMove = mapGameMove(it[1]) val gameResult = playerMove.evaluateGameResult(mapGameMove(it[0])) playerMove.score + gameResult.score } } private fun part2(input: List<String>): Int { return calculateScore(input) { val expectedResult = mapExpectedResult(it[1]) val playerMove = resolvePlayerMove(mapGameMove(it[0]), expectedResult) expectedResult.score + playerMove.score } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
90c5c24334c1f26ee1ae5795b63953b22c7298e2
2,774
Aoc-2022
Apache License 2.0
2023/src/day19/Day19.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day19 import java.io.File import java.lang.IllegalArgumentException fun main() { val input = File("src/day19/day19.txt").readLines() val workflowStrings = input.takeWhile { it.isNotEmpty() } val partStrings = input.takeLastWhile { it.isNotEmpty() } val workflows = getWorkflows(workflowStrings) val parts = partStrings.map{Part.parsePart(it)} println(getSumTotalAccept(parts,workflows)) } fun getSumTotalAccept(parts: List<Part>, workflows: Map<String, Workflow>) : Int { val startFlow = workflows["in"] return parts.filter {startFlow?.isAccepted(it, workflows) == Status.ACCEPT}.sumOf {part -> part.getTotalValue()} } data class Part(val x : Int, val m : Int, val a : Int, val s : Int) { companion object { private val PART = Regex("""\{x=(\d+),m=(\d+),a=(\d+),s=(\d+)\}""") fun parsePart(input : String) : Part { val match = PART.find(input) return if (match != null) { val (x, m, a, s) = match.destructured return Part(x.toInt(), m.toInt(), a.toInt(), s.toInt()) } else { throw IllegalArgumentException("invalid part input $input") } } } fun getValue(category : String) :Int { return when (category) { "x" -> x "m" -> m "a" -> a "s" -> s else -> throw IllegalArgumentException("Unknown category $category") } } fun getTotalValue() : Int { return x + m + a + s } } enum class Status { UNKNOWN, ACCEPT, REJECT } abstract class Rule { abstract fun checkRule(part: Part, workflows : Map<String, Workflow>) : Status } class RejectRule : Rule() { override fun checkRule(part: Part, workflows : Map<String, Workflow>) : Status { return Status.REJECT } } class AcceptRule : Rule() { override fun checkRule(part: Part, workflows : Map<String, Workflow>) : Status { return Status.ACCEPT } } class NameRule(val name : String) : Rule() { override fun checkRule(part: Part, workflows : Map<String, Workflow>) : Status { return workflows[name]!!.isAccepted(part, workflows) } } class ThresholdRule(val category : String, val threshold : Int, val greater : Boolean, val resultTrue : String) : Rule() { companion object { private val RULE = Regex("""(\w)([<>]+)(\d+):(\w+)""") fun parseRule(input : String) : ThresholdRule { val match = RULE.find(input) if (match != null) { val (cat, great, thresh, result) = match.destructured return ThresholdRule(cat, thresh.toInt(), great == ">", result) } else { throw IllegalArgumentException("Invalid threshold rule $input") } } } override fun checkRule(part: Part, workflows : Map<String, Workflow>) : Status { val catValue = part.getValue(category) val thresholdMet = (greater && catValue > threshold) || (!greater && catValue < threshold) return if (thresholdMet) { when (resultTrue) { "R" -> Status.REJECT "A" -> Status.ACCEPT else -> workflows[resultTrue]!!.isAccepted(part, workflows) } } else { Status.UNKNOWN } } } class Workflow(val input: String) { val name : String val rules : List<Rule> init { name = input.takeWhile { it != '{' } val ruleStrings = input.substring(name.length + 1, input.length - 1).split(",") val parseRules = ruleStrings.map{ when (it) { "R" -> RejectRule() "A" -> AcceptRule() else -> if (it.contains(":")) ThresholdRule.parseRule(it) else NameRule(it) } } rules = parseRules.toList() } fun isAccepted(part:Part, workflows: Map<String, Workflow>) : Status { rules.forEach { when (it.checkRule(part, workflows)) { Status.ACCEPT -> return Status.ACCEPT Status.REJECT -> return Status.REJECT else -> {} } } return Status.UNKNOWN } } fun getWorkflows(input: List<String>) : Map<String, Workflow> { return input.map {Workflow(it)}.associateBy { it.name } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
4,372
adventofcode
Apache License 2.0
src/aoc2023/Day08.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { fun part1(lines: List<String>): Int { val steps = lines[0].map { if (it == 'R') 1 else 0 } val regex = "(\\w{3}) = \\((\\w{3}), (\\w{3})\\)".toRegex() val instructions = lines.subList(2, lines.size).map { val groups = regex.find(it)!!.groupValues Pair(groups[1], listOf(groups[2], groups[3])) }.groupBy({ it.first }, { it.second }) var instruction = "AAA" var stepIndex = 0 var stepCount = 0 while (instruction != "ZZZ") { instruction = instructions[instruction]!!.flatten()[steps[stepIndex]] stepCount += 1 stepIndex += 1 stepIndex %= steps.size } return stepCount } fun ghostCycle(ghostStart: String, steps: List<Int>, instructions: Map<String, List<List<String>>>): Long { var instruction = ghostStart var stepIndex = 0 var stepCount = 0L while (!instruction.endsWith('Z')) { instruction = instructions[instruction]!!.flatten()[steps[stepIndex]] stepCount += 1 stepIndex += 1 stepIndex %= steps.size } return stepCount } fun findLeastCommonMultiple(a: Long, b: Long): Long { val larger = if (a > b) a else b val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return maxLcm } fun findLeastCommonMultipleOfListOfNumbers(numbers: List<Long>): Long { var result = numbers[0] for (i in 1 until numbers.size) { result = findLeastCommonMultiple(result, numbers[i]) } return result } fun part2(lines: List<String>): Long { val steps = lines[0].map { if (it == 'R') 1 else 0 } val regex = "(\\w{3}) = \\((\\w{3}), (\\w{3})\\)".toRegex() val instructions = lines.subList(2, lines.size).map { val groups = regex.find(it)!!.groupValues Pair(groups[1], listOf(groups[2], groups[3])) }.groupBy({ it.first }, { it.second }) var startNodes = instructions.keys.filter { it.endsWith('A') } var ghostCycles = startNodes.map { ghostCycle(it, steps, instructions) } return findLeastCommonMultipleOfListOfNumbers(ghostCycles) } println(part1(readInput("aoc2023/Day08_test"))) println(part1(readInput("aoc2023/Day08"))) println(part2(readInput("aoc2023/Day08_test_2"))) println(part2(readInput("aoc2023/Day08"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
2,657
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2021/Day05.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2021 import aoc2022.parsedBy import aoc2022.takeWhilePlusOne import utils.InputUtils import kotlin.math.sign data class Coord(val x: Int, val y: Int) { // Unit in the direction of the other one fun directionTo(other: Coord): Coord = Coord(other.x - x, other.y - y).normalise() fun normalise() = Coord(x = x.sign, y = y.sign) operator fun plus(other: Coord) = Coord(x = x + other.x, y = y+other.y) } data class Line(val start: Coord, val end: Coord) { fun allPoints(): Sequence<Coord> { val direction = start.directionTo(end) return generateSequence(start) { it + direction }.takeWhilePlusOne { it != end } } fun isHorizOrVertical() = start.x == end.x || start.y == end.y } fun main() { val testInput = """0,9 -> 5,9 8,0 -> 0,8 9,4 -> 3,4 2,2 -> 2,1 7,0 -> 7,4 6,4 -> 2,0 0,9 -> 2,9 3,4 -> 1,4 0,0 -> 8,8 5,5 -> 8,2""".split("\n") fun parse(input: List<String>): Sequence<Line> { return input.parsedBy("(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex()) { val (x1, y1, x2, y2) = it.destructured.toList().map { it.toInt() } Line(Coord(x1, y1), Coord(x2, y2)) } } fun part1(input: List<String>): Int { val counts = parse(input) .filter { it.isHorizOrVertical() } .flatMap { it.allPoints() }.groupingBy { it }.eachCount() return counts.filter { (_, count) -> count > 1 }.count() } fun part2(input: List<String>): Int { val counts = parse(input) .flatMap { it.allPoints() }.groupingBy { it }.eachCount() return counts.filter { (_, count) -> count > 1 }.count() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 5) val puzzleInput = InputUtils.downloadAndGetLines(2021, 5) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,045
aoc-2022-kotlin
Apache License 2.0
src/day07/Day07.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day07 import readInput private const val DAY_ID = "07" private sealed class Filesystem( open val name: String, open val parent: Directory? ) private data class File( override val name: String, val size: Int, override val parent: Directory? ) : Filesystem(name, parent) private data class Directory( override val name: String, override val parent: Directory?, val children: MutableMap<String, Filesystem> = mutableMapOf() ) : Filesystem(name, parent) fun main() { fun parseInput(input: List<String>, idx: Int, current: Directory?) { if (current == null || idx >= input.size) { return } val line = input[idx] if (line.startsWith("$")) { val command = line.removePrefix("$ ") if (command == "ls") { parseInput(input, idx + 1, current) } else { // format: cd <directory> val dir = command.removePrefix("cd ") parseInput(input, idx + 1, if (dir == "..") current.parent else current.children[dir] as? Directory) } } else { if (line.startsWith("dir")) { // format: dir <directory> val dir = line.removePrefix("dir ") current.children[dir] = Directory(dir, current) } else { // format: <size> <file> val (size, file) = line.split(" ") current.children[file] = File(file, size.toInt(), current) } parseInput(input, idx + 1, current) } } fun buildFilesystem(input: List<String>): Directory = Directory("/", null).also { parseInput(input, 1, it) } fun traverseFilesystem(root: Directory, onDirectory: (dirSize: Int) -> Unit): Int { fun dfs(current: Filesystem): Int = when (current) { is File -> current.size is Directory -> current.children.values.sumOf { dfs(it) }.also { size -> onDirectory(size) } } return dfs(root) } fun part1(input: List<String>): Int { val thresholdSize = 100000 val root = buildFilesystem(input) var sum = 0 traverseFilesystem(root) { dirSize -> if (dirSize <= thresholdSize) { sum += dirSize } } return sum } fun part2(input: List<String>): Int { val diskSize = 70000000 val updateSize = 30000000 val root = buildFilesystem(input) val dirSizes = mutableListOf<Int>() val usedSize = traverseFilesystem(root) { dirSize -> dirSizes += dirSize } val unusedSize = diskSize - usedSize val needSize = updateSize - unusedSize return dirSizes.asSequence() .filter { dirSize -> dirSize >= needSize } .min() } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = 1348005 println(part2(input)) // answer = 12785886 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
3,237
aoc-2022-in-kotlin
Apache License 2.0
src/Day11.kt
zirman
572,627,598
false
{"Kotlin": 89030}
import kotlin.system.measureTimeMillis data class Monkey( var items: MutableList<Long>, val operator: String, val operand: String, val divisibleBy: Long, val trueMonkey: Int, val falseMonkey: Int, var inspectedCount: Long, ) fun main() { fun parseMonkeys(input: List<String>): List<Monkey> { return input .joinToString("\n") .split("\n\n") .map { monkeyStr -> val ( startingItemsLine, operationLine, testLine, trueLine, falseLine, ) = monkeyStr.split("\n").drop(1) val startingItems = startingItemsLine.split(": ").last().split(", ").map { it.toLong() } val (operator, operand) = """^old ([+*]) (old|\d+)$""".toRegex() .matchEntire(operationLine.split(" = ").last())!! .destructured val divisibleBy = testLine.split(" by ").last().toLong() val trueMonkey = trueLine.split("monkey ").last().toInt() val falseMonkey = falseLine.split("monkey ").last().toInt() Monkey( items = startingItems.toMutableList(), operator = operator, operand = operand, divisibleBy = divisibleBy, trueMonkey = trueMonkey, falseMonkey = falseMonkey, inspectedCount = 0, ) } } fun iterateMonkeys(monkeys: List<Monkey>, times: Int, reducer: (Long) -> Long): Long { repeat(times) { monkeys.forEach { monkey -> monkey.inspectedCount += monkey.items.size monkey.items.forEach { item -> val updatedItem = when (monkey.operator) { "+" -> if (monkey.operand == "old") { item + item } else { item + monkey.operand.toLong() } "*" -> if (monkey.operand == "old") { item * item } else { item * monkey.operand.toLong() } else -> throw Exception("Invalid Operator") }.let { reducer(it) } if (updatedItem % monkey.divisibleBy == 0L) { monkeys[monkey.trueMonkey].items.add(updatedItem) } else { monkeys[monkey.falseMonkey].items.add(updatedItem) } } monkey.items = mutableListOf() } } return monkeys.map { it.inspectedCount } .sortedDescending() .take(2) .reduce { a, b -> a * b } } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) return iterateMonkeys(monkeys, times = 20, reducer = { it / 3 }) } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) val divisor = monkeys.map { it.divisibleBy }.reduce(Long::times) return iterateMonkeys(monkeys, times = 10000, reducer = { it % divisor }) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) val input = readInput("Day11") println(part1(input)) println(measureTimeMillis { part2(input) }) check(part2(testInput) == 2713310158L) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
3,790
aoc2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2020/d16/Day16.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d16 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines private data class Rule(val fieldName: String, val validRanges: List<IntRange>) private fun Rule.validValue(value: Int): Boolean = validRanges.any { value in it } private fun scanningErrorRate(rules: List<Rule>, ticket: List<Int>): Int = ticket.sumOf { value -> if (rules.any { it.validValue(value) }) 0 else value } // field names in ticket values order private fun determineFields(rules: List<Rule>, validTickets: List<List<Int>>): List<String> { val fieldsInOrder: MutableList<String?> = rules.map { null }.toMutableList() val remainingRules = rules.toMutableList() while (fieldsInOrder.any { it == null }) { fieldsInOrder.forEachIndexed { i, maybeField -> if (maybeField == null) { remainingRules.filter { rule -> validTickets.map { it[i] }.all { rule.validValue(it) } }.let { filteredRules -> if (filteredRules.size == 1) { fieldsInOrder[i] = filteredRules[0].fieldName remainingRules.remove(filteredRules[0]) } } } } } return fieldsInOrder.map { it!! } } fun main() { var blankLines = 0 val ruleLines = mutableListOf<String>() val ticketLines = mutableListOf<String>() (DATAPATH / "2020/day16.txt").useLines { lines -> lines.forEach { line -> when { line.isEmpty() -> blankLines++ blankLines == 0 -> ruleLines.add(line) line[0].isDigit() -> ticketLines.add(line) // ignore non-ticket lines } } } val rules = ruleLines.map { line -> Rule( line.substringBefore(":"), line.substringAfter(": ").split(" or ").map { it.split("-").let { parts -> parts[0].toInt()..parts[1].toInt() } } ) } // NOTE: My ticket is tickets[0], nearby tickets are the rest val tickets = ticketLines.map { line -> line.split(",").map { it.toInt() } } val myTicket = tickets[0] val otherTickets = tickets.subList(1, tickets.size) otherTickets.sumOf { scanningErrorRate(rules, it) } .also { println("Part one: $it") } otherTickets.filter { ticket -> ticket.all { value -> rules.any { it.validValue(value) } } }.let { validTickets -> determineFields(rules, validTickets) }.let { fieldNamesInOrder -> fieldNamesInOrder.mapIndexedNotNull { index, s -> if (s.startsWith("departure")) index else null } }.map { idx -> myTicket[idx].toLong() }.reduce(Long::times) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,952
advent-of-code
MIT License
src/Day02.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.math.max private const val EXPECTED_1 = 8 private const val EXPECTED_2 = 2286 private class Day02(isTest: Boolean) : Solver(isTest) { fun part1(): Any { var sum = 0 var id = 1 for (line in readAsLines()) { val parts = line.substringAfter(": ").split(";").map { it.trim() } var possible = true for (set in parts) { set.split(",").map { it.trim() }.forEach { val count = it.substringBefore(" ").toInt() val color = it.substringAfter(" ") when(color) { "red" -> possible = possible && count <= 12 "green" -> possible = possible && count <= 13 "blue" -> possible = possible && count <= 14 } } } if (possible) { sum += id } id++ } return sum } fun part2(): Any { var sum = 0 var id = 1 for (line in readAsLines()) { val parts = line.substringAfter(": ").split(";").map { it.trim() } var minBlue = 0 var minRed = 0 var minGreen = 0 for (set in parts) { set.split(",").map { it.trim() }.forEach { val count = it.substringBefore(" ").toInt() val color = it.substringAfter(" ") when(color) { "red" -> minRed = max(minRed, count) "green" -> minGreen = max(minGreen, count) "blue" -> minBlue = max(minBlue, count) } } } println("$minBlue $minRed $minGreen") sum += minBlue * minRed * minGreen id++ } return sum } } fun main() { val testInstance = Day02(true) val instance = Day02(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
2,272
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2021/Day10.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2021 import utils.InputUtils import java.util.* fun main() { val testInput = """[({(<(())[]>[[{[]{<()<>> [(()[<>])]({[<{<<[]>>( {([(<{}[<>[]}>{[]{[(<()> (((({<>}<{<{<>}{[]{[]{} [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] {<[[]]>}<{[{[{[]{()[[[] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{ <{([{{}}[<[[[<>{}]]]>[]]""".split("\n") val opens = "([{<" val closes = ")]}>" fun score(c: Char) = when(c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } fun validate(s: String): Int { val stack = Stack<Char>() for(c in s) { if(c in opens) { stack.push(c) } if(c in closes) { val o = stack.pop() val expected = closes[opens.indexOf(o)] if (c != expected) { //println("Was $c expected $expected") return score(c) } } } return 0 } fun tail(s: String): String { val stack = Stack<Char>() for(c in s) { if(c in opens) { stack.push(c) } if(c in closes) { val o = stack.pop() val expected = closes[opens.indexOf(o)] if (c != expected) { return "" } } } return stack.joinToString("").reversed() } fun part1(input: List<String>): Int { return input.sumOf(::validate) } fun part2Score(s: String): Long { return s.fold(0L ) { acc, c -> (acc * 5) + (opens.indexOf(c) + 1)} } fun part2(input: List<String>): Long { val scores = input .asSequence() .filter { validate(it) ==0 } .map(::tail) .filter(String::isNotBlank) .onEach { println("$it ${part2Score(it)}") } .map { part2Score(it)}.sorted().toList() return scores.median() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 26397) val puzzleInput = InputUtils.downloadAndGetLines(2021, 10) val input = puzzleInput.toList() println(part1(input)) println("=== Part 2 ===") println(part2(testInput)) println(part2(input)) } private fun List<Long>.median(): Long = this[size / 2]
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,422
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc23/Day04.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import aoc23.Day04Domain.ScratchCards import aoc23.Day04Parser.toScratchCards import aoc23.Day04Solution.part1Day04 import aoc23.Day04Solution.part2Day04 import common.Year23 import kotlin.math.pow object Day04 : Year23 { fun List<String>.part1(): Int = part1Day04() fun List<String>.part2(): Int = part2Day04() } object Day04Solution { fun List<String>.part1Day04(): Int = toScratchCards() .points() fun List<String>.part2Day04(): Int = toScratchCards() .cardsWon() } object Day04Domain { data class ScratchCards( private val cards: List<Card> ) { private val cardMatches = cards.map { it.matches() } fun points(): Int = cardMatches.sumOf { 2.0.pow(it - 1).toInt() } fun cardsWon(): Int { val cards = IntArray(cardMatches.size) { 1 } cardMatches.forEachIndexed { index, copies -> repeat(copies) { copyIndex -> cards[index + copyIndex + 1] += cards[index] } } return cards.sum() } } data class Card( val winning: Set<Int>, val yours: Set<Int> ) { fun matches(): Int = winning.intersect(yours).size } } object Day04Parser { fun List<String>.toScratchCards(): ScratchCards = ScratchCards( cards = map { line -> line.split(":").let { (_, cards) -> cards.split(" | ").let { (winning, yours) -> Day04Domain.Card( winning = winning.toInts(), yours = yours.toInts() ) } } } ) private fun String.toInts(): Set<Int> = split(" ").filter { it.isNotBlank() }.map { it.trim().toInt() }.toSet() }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
1,876
aoc
Apache License 2.0
src/Day14.kt
tomoki1207
572,815,543
false
{"Kotlin": 28654}
import kotlin.math.max import kotlin.math.min data class Cave(val input: List<String>) { data class CavePoint(val x: Int, val y: Int) private val cave: MutableSet<CavePoint> private val maxDepth: Int init { val cave = input.flatMap { line -> val points = line.split("->").map { point -> point.trim().split(",").let { (x, y) -> x.toInt() to y.toInt() } } points.windowed(2) { (start, end) -> if (start.first != end.first) { return@windowed (min(start.first, end.first)..max(start.first, end.first)).map { x -> CavePoint(x, start.second) } } else { return@windowed (min(start.second, end.second)..max(start.second, end.second)).map { y -> CavePoint(start.first, y) } } }.flatten() }.toMutableSet() maxDepth = cave.maxOf { it.y } cave.addAll((-1000..1000).map { CavePoint(it, maxDepth + 2) }) this.cave = cave } fun dropSand(x: Int = 500, y: Int = 0): Boolean { if (y > maxDepth) { return false } // bottom if (!cave.contains(CavePoint(x, y))) { return dropSand(x, y + 1) } // left if (!cave.contains(CavePoint(x - 1, y))) { return dropSand(x - 1, y) } // right if (!cave.contains(CavePoint(x + 1, y))) { return dropSand(x + 1, y) } cave.add(CavePoint(x, y - 1)) return true } fun stackSand(x: Int = 500, y: Int = 0): Boolean { if (y == 0 && cave.contains(CavePoint(x, y))) { return false } // bottom if (!cave.contains(CavePoint(x, y))) { return stackSand(x, y + 1) } // left if (!cave.contains(CavePoint(x - 1, y))) { return stackSand(x - 1, y) } // right if (!cave.contains(CavePoint(x + 1, y))) { return stackSand(x + 1, y) } cave.add(CavePoint(x, y - 1)) return true } } fun main() { fun solve(input: List<String>, process: (Cave) -> Boolean): Int { val cave = Cave(input) var step = 0 while (process(cave)) { ++step } return step } fun part1(input: List<String>) = solve(input) { it.dropSand() } fun part2(input: List<String>) = solve(input) { it.stackSand() } val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
2,764
advent-of-code-kotlin-2022
Apache License 2.0
src/day03/Day03.kt
marcBrochu
573,884,748
false
{"Kotlin": 12896}
package day03 import readInput fun calculateItemPriority(item: Char): Int { return if(item.isUpperCase()) { item - 'A' + 27 } else if (item.isLowerCase()) { item - 'a' + 1 } else { 0 } } fun main() { fun part1(input: List<String>): Int { fun findDuplicateInRucksack(rucksack: String): Char { val half: Int = if (rucksack.length % 2 == 0) rucksack.length / 2 else rucksack.length / 2 + 1 val first: String = rucksack.substring(0, half) val second: String = rucksack.substring(half) val duplicateSet = first.toSet().intersect(second.toSet()) if (duplicateSet.any()) { return duplicateSet.elementAt(0) } return ' ' } return input.sumOf { rucksacks -> calculateItemPriority(findDuplicateInRucksack(rucksacks)) } } fun part2(input: List<String>): Int { fun findDuplicateInRucksackGroup(rucksacks: List<String>): Char { var current: Set<Char>? = null for (rucksack in rucksacks) { current = current?.intersect(rucksack.toSet()) ?: rucksack.toSet() } if (current != null && current.any()) { return current.elementAt(0) } return ' ' } var groupSum = 0 input.chunked(3).map { group -> groupSum += calculateItemPriority(findDuplicateInRucksackGroup(group)) } return groupSum } val input = readInput("day03/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
8d4796227dace8b012622c071a25385a9c7909d2
1,650
advent-of-code-kotlin
Apache License 2.0
src/Day09.kt
cvb941
572,639,732
false
{"Kotlin": 24794}
import kotlin.math.absoluteValue fun main() { fun getDirVector(vectorChar: Char): Pair<Int, Int> { return when (vectorChar) { 'U' -> Pair(0, 1) 'D' -> Pair(0, -1) 'L' -> Pair(-1, 0) 'R' -> Pair(1, 0) else -> throw IllegalArgumentException("Invalid input: $vectorChar") } } fun getTailMovement(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> { val headRelative = head - tail return when { headRelative == 0 to 0 -> 0 to 0 // On top, do not move headRelative.toList().maxOf { it.absoluteValue } == 1 -> 0 to 0 // Touching, do not move else -> { headRelative.first.coerceIn(-1..1) to headRelative.second.coerceIn(-1..1) } } } class Part1 { val visited = mutableSetOf(0 to 0) var tail = Pair(0, 0) var head = Pair(0, 0) fun solve(input: List<String>): Int { input.forEach { val (dir, steps) = it.split(" ") val dirVector = getDirVector(dir[0]) repeat(steps.toInt()) { head += dirVector val tailMovement = getTailMovement(head, tail) tail += tailMovement visited += tail } } return visited.size } } class Part2(size: Int) { val visited = Array(size) { mutableSetOf(0 to 0) } val positions = Array(size) { 0 to 0 } fun solve(input: List<String>): Int { input.forEach { val (dir, steps) = it.split(" ") val dirVector = getDirVector(dir[0]) repeat(steps.toInt()) { // Move head val newHeadPosition = positions[0] + dirVector positions[0] = newHeadPosition positions.indices.zipWithNext { headIndex, tailIndex -> // Move tail val tailMovement = getTailMovement(positions[headIndex], positions[tailIndex]) positions[tailIndex] += tailMovement visited[tailIndex] += positions[tailIndex] } } } return visited.last().size } } fun part1(input: List<String>): Int { return Part1().solve(input) } fun part2(input: List<String>): Int { return Part2(10).solve(input) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fe145b3104535e8ce05d08f044cb2c54c8b17136
2,834
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day12.kt
joostbaas
573,096,671
false
{"Kotlin": 45397}
data class Day12( private val start: Point, private val end: Point, private val grid: Map<Point, Char>, ) { companion object { fun day12Part1(input: List<String>): Int = input.parse().let { it.calculateShortestPathFromStartToEnd() } fun day12Part2(input: List<String>): Int = input.parse().let { it.findStartingPointWithShortestPath() } private fun List<String>.parse(): Day12 { val initial: Triple<Point?, Point?, Map<Point, Char>> = Triple(null, null, emptyMap()) infix operator fun Triple<Point?, Point?, Map<Point, Char>>.plus( other: Triple<Point?, Point?, Map<Point, Char>>, ) = Triple( first ?: other.first, second ?: other.second, third + other.third, ) val (startingPoint, bestSignalPoint, allPoints) = this.foldIndexed(initial) { y: Int, gridAcc, line: String -> val lineResult: Triple<Point?, Point?, Map<Point, Char>> = line.foldIndexed(initial) { x: Int, lineAcc, point: Char -> Point(x, y).let { when (point) { 'S' -> Triple(it, null, mapOf(it to 'a')) 'E' -> Triple(null, it, mapOf(it to 'z')) else -> Triple(null, null, mapOf(it to point)) } } + lineAcc } gridAcc + lineResult } return Day12( startingPoint!!, bestSignalPoint!!, allPoints ) } } data class Point(val x: Int, val y: Int) private fun Point.candidatesToMoveTo(forbiddenNode: Char?): Set<Point> { val thisElevation = grid[this]!! return listOf( Point(x - 1, y), Point(x + 1, y), Point(x, y - 1), Point(x, y + 1), ).filter { val elevationOfNeighbour: Char? = grid[it] it != this && elevationOfNeighbour != null && elevationOfNeighbour != forbiddenNode && elevationOfNeighbour - thisElevation <= 1 }.toHashSet() } fun calculateShortestPathFromStartToEnd(max: Int = grid.size, forbiddenNode: Char? = null): Int { var edges: Set<Point> = hashSetOf(start) var steps = 1 while (steps <= max) { val accessibleFromPreviousEdges: Set<Point> = edges.flatMap { it.candidatesToMoveTo(forbiddenNode) .filterNot { candidate -> edges.contains(candidate) } }.toHashSet() if (accessibleFromPreviousEdges.contains(end)) return steps steps++ edges = accessibleFromPreviousEdges } return Int.MAX_VALUE } fun findStartingPointWithShortestPath(): Int = grid.filterValues { elevation -> elevation == 'a' } .keys.fold(Int.MAX_VALUE) { minSoFar, start -> this.copy(start = start).calculateShortestPathFromStartToEnd(forbiddenNode = 'a').let { minSoFar.coerceAtMost(it) } } }
0
Kotlin
0
0
8d4e3c87f6f2e34002b6dbc89c377f5a0860f571
3,315
advent-of-code-2022
Apache License 2.0
advent-of-code-2022/src/Day02.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
/* Hints I've used to solve the puzzle: 1. We can map letter to a digit: choice = letter - 'A' // A -> 0, B -> 1, C -> 2 (the same logic may be applied to X, Y, Z) choiceScore = choice + 1 2. Order of symbols (Rock, Paper, Scissors) allows us to quickly understand round outcome. Next symbol always beats the current - Paper beats Rock, Scissors beats Paper and Rock beats Scissors. So using the previous hint we can use indices to calculate outcome: elfChoice = elfLetter - 'A' myChoice = myLetter - 'X' outcome = when { elfChoice == (myChoice + 1) % 3 -> 0 (lose) elfChoice == myChoice -> 1 (draw) myChoice == (elfChoice + 1) % 3 -> 2 (win) } // Or by formula outcome = ((myChoice - elfChoice) % 3 + 1) % 3 outcomeScore = outcome * 3 // loss -> 0, draw -> 3, win -> 6 3. We can use desired outcome and Elf's choice to restore our choice: choiceDiff = outcome - 1 // loss -> -1, draw -> 0, win -> 1 myChoice = (elfChoice + choiceDiff) % 3 */ fun main() { // Convert lines to pairs of digits in range 0..2 fun readInput(name: String) = readLines(name).map { it[0] - 'A' to it[2] - 'X' } fun part1(input: List<Pair<Int, Int>>): Int { return input.sumOf { (elf, me) -> (me + 1) + ((me - elf).mod(3) + 1) % 3 * 3 } // Readable version: // var score = 0 // for ((elfChoice, myChoice) in input) { // val choiceScore = myChoice + 1 // val outcome = ((myChoice - elfChoice).mod(3) + 1) % 3 // score += choiceScore + outcome * 3 // } // return score } fun part2(input: List<Pair<Int, Int>>): Int { return input.sumOf { (elf, outcome) -> outcome * 3 + (elf + outcome).mod(3) + 1 } // Readable version: // var score = 0 // for ((elfChoice, outcome) in input) { // val myChoice = (elfChoice + outcome - 1).mod(3) // val choiceScore = myChoice + 1 // val outcomeScore = outcome * 3 // score += outcomeScore + choiceScore // } // return score } val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,324
advent-of-code
Apache License 2.0
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day08.kt
codelicia
627,407,402
false
{"Kotlin": 49578, "PHP": 554, "Makefile": 293}
package com.codelicia.advent2021 class Day08(private val signals: List<String>) { data class SegmentMap( val map: Map<String, Int>, val decodedNumber: Int ) { companion object { private fun String.order() = this.split("").sortedDescending().joinToString(separator = "") fun of(input: String): SegmentMap { val (segment, numbers) = input.split(" | ") val segmentSplit = segment.split(" ") // Hacky ones val sixDigits = segmentSplit.filter { it.length == 6 } val fiveDigits = segmentSplit.filter { it.length == 5 } // Easy discoverable val one = segmentSplit.first { it.length == 2 } val four = segmentSplit.first { it.length == 4 } val seven = segmentSplit.first { it.length == 3 } val eight = segmentSplit.first { it.length == 7 } // Tricky val nine = sixDigits.first { it.split("").containsAll(four.split("")) } val zero = sixDigits.filter { !it.split("").containsAll(nine.split("")) } .first { it.split("").containsAll(one.split("")) } val six = sixDigits.filter { !it.split("").containsAll(nine.split("")) } .first { !it.split("").containsAll(one.split("")) } val three = fiveDigits.first { it.split("").containsAll(one.split("")) } val five = fiveDigits.first { six.split("").containsAll(it.split("")) } val two = fiveDigits.filter { !it.split("").containsAll(three.split("")) } .first { !it.split("").containsAll(five.split("")) } val map = mutableMapOf<String, Int>() map[zero.order()] = 0 map[one.order()] = 1 map[two.order()] = 2 map[three.order()] = 3 map[four.order()] = 4 map[five.order()] = 5 map[six.order()] = 6 map[seven.order()] = 7 map[eight.order()] = 8 map[nine.order()] = 9 val number = numbers.split(" ").map { map[it.order()]!! } return SegmentMap(map, number.joinToString(separator = "").toInt()) } } } private val easyDigits = listOf(2, 3, 4, 7) fun part1(): Int = signals.map { it.split(" | ")[1].split(" ") } .map { segments -> segments.map { when { easyDigits.contains(it.length) -> 1 else -> 0 } } }.sumOf { it.sum() } fun part2(): Int = signals.map { SegmentMap.of(input = it) } .sumOf { it.decodedNumber } }
2
Kotlin
0
0
df0cfd5c559d9726663412c0dec52dbfd5fa54b0
2,903
adventofcode
MIT License
src/main/kotlin/com/jacobhyphenated/advent2023/day7/Day7.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day7 import com.jacobhyphenated.advent2023.Day /** * Day 7: Camel Cards * * Camel is like poker but with its own rules on what cards win. * The puzzle input is a list of hands with a bet for each hand. * * The total score takes the weakest hand and multiplies the bet by 1, * then the second-weakest hand by 2, and so on until the strongest hand is multiplied by the total number of hands. */ class Day7: Day<List<Pair<Hand, Int>>> { override fun getInput(): List<Pair<Hand, Int>> { return parseInput(readInputFile("7")) } /** * Part 1: Add up the hand scores * * Sort the Hands (the weakest first). Then multiply each bet by index+1 */ override fun part1(input: List<Pair<Hand, Int>>): Int { return input .sortedBy { it.first }.reversed() .mapIndexed { i, (_, bet) -> (i+1) * bet } .sum() } /** * Part 2: The J cards are actually Jokers. * Jokers take on the whatever value gives the hand the highest score. * However, for tiebreakers, a J is considered the weakest card. */ override fun part2(input: List<Pair<Hand, Int>>): Int { input.forEach { (hand, _) -> hand.applyJokers() } return input .sortedBy { it.first }.reversed() .mapIndexed { i, (_, bet) -> (i+1) * bet } .sum() } fun parseInput(input: String): List<Pair<Hand,Int>> { return input.lines().map { line -> val (cardString, bet) = line.split(" ") val cards = cardString.toCharArray().map { Card.fromChar(it) } Pair(Hand(cards), bet.toInt()) } } override fun warmup(input: List<Pair<Hand, Int>>) { part1(input) } } /** * Track the Camel/Poker Hand. * * For part 2, we transform the cards using [modifiedCards] where the Jokers take on different card values. * for part 1, [modifiedCards] == [cards]. */ class Hand(private var cards: List<Card>): Comparable<Hand> { private var modifiedCards = cards // remember hand rank to avoid repeat calculations private var rank: HandRank? = null /** * Remap [cards] so Jacks become Jokers (Jokers have a lower value than Jacks) * Find the card that appears most frequently that is no a joker. * Have the Jokers take on that value and store that in [modifiedCards] * * This is a mutating function that changes the internal values of the Hand class. */ fun applyJokers() { cards = cards.map { if (it == Card.JACK) { Card.JOKER } else { it } } val counts = cards.groupingBy { it }.eachCount() if (counts[Card.JOKER] == null) { return } val max = counts.maxBy { (card, count) -> if (card == Card.JOKER) { 0 } else { count } }.key modifiedCards = cards.map { if (it == Card.JOKER) { max } else { it } } rank = null } /** * Sort. Enums are sorted by ordinal - the order they appear in the enum * Sort based on rank first, then compare the value of the first card in each hand. * Then the second, and so forth */ override fun compareTo(other: Hand): Int { val compareRanks = this.getRank().compareTo(other.getRank()) if (compareRanks != 0) { return compareRanks } for (i in cards.indices) { val compareCard = cards[i].compareTo(other.cards[i]) if (compareCard != 0) { return compareCard } } return 0 } /** * Calculate the [HandRank] of the hand. This can be derived by counting haw many times a card repeats. */ private fun getRank(): HandRank { if (rank != null) { return rank!! } // Create a Map of Card -> Number of times that card appears in this hand val counts = modifiedCards.groupingBy { it }.eachCount() return when (counts.size) { 1 -> HandRank.FIVE_OF_A_KIND 2 -> if (counts.values.any { it == 4 }) { HandRank.FOUR_OF_A_KIND } else { HandRank.FULL_HOUSE } 3 -> if (counts.values.any { it == 3 }) { HandRank.THREE_OF_A_KIND } else { HandRank.TWO_PAIR } 4 -> HandRank.ONE_PAIR 5 -> HandRank.HIGH_CARD else -> throw IllegalStateException("A hand must have exactly 5 cards") }.also { rank = it } } } enum class HandRank { FIVE_OF_A_KIND, FOUR_OF_A_KIND, FULL_HOUSE, THREE_OF_A_KIND, TWO_PAIR, ONE_PAIR, HIGH_CARD } // note: Jokers are not mapped from strings. 'J' Is treated as a Jack for part1 // and transformed into a Joker during part 2 enum class Card { ACE, KING, QUEEN, JACK, TEN, NINE, EIGHT, SEVEN, SIX, FIVE, FOUR, THREE, TWO, JOKER; companion object { private val cardMap = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') .zip(Card.values()) .toMap() fun fromChar(c: Char): Card { return cardMap[c] ?: throw IllegalArgumentException("Invalid Character: $c") } } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day7().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
4,843
advent2023
The Unlicense
src/Year2022Day08.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
private inline fun <T> Iterable<T>.countDoWhile(predicate: (T) -> Boolean): Int { var counter = 0 for (item in this) { counter++ if (!predicate(item)) return counter } return counter } fun main() { fun part1(input: List<String>): Int { val G = input.map { it.map { c -> c.digitToInt() }.toList() } fun isVisible(i: Int, j: Int): Boolean { val top = (0 until i).reversed() val down = i + 1 until G.rowSize val left = (0 until j).reversed() val right = j + 1 until G.columnSize return top.all { G[i][j] > G[it][j] } || down.all { G[i][j] > G[it][j] } || left.all { G[i][j] > G[i][it] } || right.all { G[i][j] > G[i][it] } } return sequence { for (i in 0 until G.rowSize) { for (j in 0 until G.columnSize) { yield(isVisible(i, j)) } } }.count { it } } fun part2(input: List<String>): Int { val G = input.map { it.map { it.digitToInt() }.toList() } fun score(i: Int, j: Int): Int { val top = (0 until i).reversed() val down = i + 1 until G.rowSize val left = (0 until j).reversed() val right = j + 1 until G.columnSize return top.countDoWhile { G[i][j] > G[it][j] } * down.countDoWhile { G[i][j] > G[it][j] } * left.countDoWhile { G[i][j] > G[i][it] } * right.countDoWhile { G[i][j] > G[i][it] } } return sequence { for (i in 0 until G.rowSize) { for (j in 0 until G.columnSize) { yield(score(i, j)) } } }.max() } val testLines = readLines(true) check(part1(testLines) == 21) check(part2(testLines) == 8) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
2,025
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/phiber/aoc2022/day2/Solution.kt
rsttst
572,967,557
false
{"Kotlin": 7688}
package dev.phiber.aoc2022.day2 import dev.phiber.aoc2022.readAllLinesUntilEmpty enum class Outcome(val points: Int) { LOSS(0), TIE(3), WIN(6); companion object { fun forChar(char: Char) : Outcome = when (char) { 'X' -> LOSS 'Y' -> TIE 'Z' -> WIN else -> throw RuntimeException("Invalid character.") } } } enum class Symbol( val points: Int, val evaluateOutcome: (opponentSymbol: Symbol) -> Outcome, val evaluatePlayerSymbol: (outcome: Outcome) -> Symbol ) { ROCK( points = 1, evaluateOutcome = { opponentSymbol -> when (opponentSymbol) { ROCK -> Outcome.TIE PAPER -> Outcome.LOSS SCISSORS -> Outcome.WIN } }, evaluatePlayerSymbol = { outcome -> when (outcome) { Outcome.LOSS -> SCISSORS Outcome.TIE -> ROCK Outcome.WIN -> PAPER } } ), PAPER( points = 2, evaluateOutcome = { opponentSymbol -> when (opponentSymbol) { ROCK -> Outcome.WIN PAPER -> Outcome.TIE SCISSORS -> Outcome.LOSS } }, evaluatePlayerSymbol = { outcome -> when (outcome) { Outcome.LOSS -> ROCK Outcome.TIE -> PAPER Outcome.WIN -> SCISSORS } } ), SCISSORS( points = 3, evaluateOutcome = { opponentSymbol -> when (opponentSymbol) { ROCK -> Outcome.LOSS PAPER -> Outcome.WIN SCISSORS -> Outcome.TIE } }, evaluatePlayerSymbol = { outcome -> when (outcome) { Outcome.LOSS -> PAPER Outcome.TIE -> SCISSORS Outcome.WIN -> ROCK } } ); companion object { fun forOpponentChar(opponentChar: Char) : Symbol = when (opponentChar) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS else -> throw RuntimeException("Invalid character.") } fun forPlayerChar(playerChar: Char) : Symbol = when (playerChar) { 'X' -> ROCK 'Y' -> PAPER 'Z' -> SCISSORS else -> throw RuntimeException("Invalid character.") } } } fun main() { val lines: List<String> = readAllLinesUntilEmpty() val characterPairs: List<Pair<Char, Char>> = lines .map { line -> line.split(" ", limit=2) } .map { (opponentSymbolStr, playerSymbolStr) -> opponentSymbolStr[0] to playerSymbolStr[0] } val task1Matches: List<Pair<Symbol, Symbol>> = characterPairs .map { (opponentSymbolChar, playerSymbolChar) -> Symbol.forOpponentChar(opponentSymbolChar) to Symbol.forPlayerChar(playerSymbolChar) } val task1Points: Int = task1Matches.sumOf { (opponentSymbol, playerSymbol) -> playerSymbol.points + playerSymbol.evaluateOutcome(opponentSymbol).points } val task2Matches: List<Pair<Symbol, Outcome>> = characterPairs .map { (opponentSymbolChar, outcomeChar) -> Symbol.forOpponentChar(opponentSymbolChar) to Outcome.forChar(outcomeChar) } val task2Points: Int = task2Matches.sumOf { (opponentSymbol, outcome) -> outcome.points + opponentSymbol.evaluatePlayerSymbol(outcome).points } println("Task 1: $task1Points") println("Task 2: $task2Points") }
0
Kotlin
0
0
2155029ebcee4727cd0af75543d9f6f6ab2b8995
3,376
advent-of-code-2022
Apache License 2.0
src/Day10.kt
bananer
434,885,332
false
{"Kotlin": 36979}
import java.util.* fun main() { fun syntaxErrorScore(c: Char): Int = when (c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> throw IllegalArgumentException() } fun part1(input: List<String>): Int { return input.sumOf { val stack = Stack<Char>() for(c in it) { val valid = when(c) { '(','[','{','<' -> { stack.push(c) true } ')' -> stack.pop() == '(' ']' -> stack.pop() == '[' '}' -> stack.pop() == '{' '>' -> stack.pop() == '<' else -> throw IllegalArgumentException() } if (!valid) { return@sumOf syntaxErrorScore(c) } } // no syntax error return@sumOf 0 } } fun autoCompleteScore(s: String): Long { var score = 0L s.forEach { c -> score *= 5L score += when (c) { ')' -> 1L ']' -> 2L '}' -> 3L '>' -> 4L else -> throw IllegalArgumentException() } } return score } fun part2(input: List<String>): Long { val completions = input.map { val stack = Stack<Char>() for (c in it) { val valid = when (c) { '(', '[', '{', '<' -> { stack.push(c) true } ')' -> stack.pop() == '(' ']' -> stack.pop() == '[' '}' -> stack.pop() == '{' '>' -> stack.pop() == '<' else -> throw IllegalArgumentException() } if (!valid) { return@map "" } } return@map stack.reversed() .map { c -> when (c) { '(' -> ')' '[' -> ']' '{' -> '}' '<' -> '>' else -> throw IllegalStateException() } } .joinToString("") } val completionsScores = completions .filter { it.isNotEmpty() } .map { autoCompleteScore(it) } .sorted() return completionsScores[completionsScores.size / 2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 26397) val testOutput2 = part2(testInput) println("test output2: $testOutput2") check(testOutput2 == 288957L) val input = readInput("Day10") println("output part1: ${part1(input)}") println("output part2: ${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
3,100
advent-of-code-2021
Apache License 2.0
src/Day07.kt
ktrom
573,216,321
false
{"Kotlin": 19490, "Rich Text Format": 2301}
import java.util.Scanner fun main() { // get directories smaller than given size fun getDirectories(input: List<String>, size: Int): Int { val root: Node = getSystemTree(input) return getDirectories(root, size, Condition.LESS_THAN).sumOf { it.size } } fun part1(input: List<String>): Int { return getDirectories(input, 100000) } fun part2(input: List<String>): Int { val root: Node = getSystemTree(input) val totalSpace = 70000000 // sure, this will have literally every node, but i've got to get to sleep :p val allNodes: List<Node> = getDirectories(root, 1, Condition.GREATER_THAN) val availableSpace = totalSpace - root.size val necessarySpace = 30000000 - availableSpace return allNodes.filter { it.size > necessarySpace }.minBy { it.size }.size } // test if implementation meets criteria from the description val testInput = readInput("Day07_test") println(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) println(part2(testInput) == 24933642) println(part2(input)) } class Node(val name: String){ var parent: Node? = null val children: MutableMap<String, Node> = mutableMapOf() var size = -1 } fun getSystemTree(input: List<String>): Node{ val fileSystemRoot = Node("fileSystem") val root = Node("/") fileSystemRoot.children[root.name] = root root.parent = fileSystemRoot var currentNode: Node? = fileSystemRoot // set up node tree input.forEach { val reader = Scanner(it.reader()) val firstValue: String = reader.next() if(firstValue == "$"){ val cmd: String = reader.next() if(cmd == "cd"){ val nextDirName: String = reader.next() currentNode = if(nextDirName == ".."){ currentNode!!.parent } else{ currentNode!!.children[nextDirName] } } } else if(firstValue == "dir"){ val dirName: String = reader.next() val childNode = Node(dirName) currentNode!!.children[dirName] = childNode childNode.parent = currentNode } else{ val fileSize = firstValue.toInt() val fileName = reader.next() val fileNode = Node(fileName) fileNode.size = fileSize currentNode!!.children[fileName] = fileNode fileNode.parent = currentNode } } return root } // If this is called on a node, and that node has -1 size, this will calculate size // returns all nodes greater than given size beneath node fun getDirectories(node: Node, size: Int, condition: Condition): List<Node> { val nodesMeetingCondition = mutableListOf<Node>() if(node.size == -1){ node.size = 0 node.children.map { val childNode = it.value nodesMeetingCondition.addAll(getDirectories(childNode, size, condition)) node.size += childNode.size } } val nodeSizeMeetsCondition = condition == Condition.GREATER_THAN && node.size > size || condition == Condition.LESS_THAN && node.size < size if(nodeSizeMeetsCondition && node.children.isNotEmpty()){ nodesMeetingCondition.add(node) } return nodesMeetingCondition } enum class Condition{ GREATER_THAN, LESS_THAN }
0
Kotlin
0
0
6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd
3,494
kotlin-advent-of-code
Apache License 2.0
src/day24/Day24.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day24 import java.io.File import java.util.* fun main() { val valley = Valley.parse(File("src/day24/input.txt").readLines()) val there = solve(valley, Valley.START, valley.finish) println(there.first) val back = solve(there.second, valley.finish, Valley.START) val thereAgain = solve(back.second, Valley.START, valley.finish) println(there.first + back.first + thereAgain.first) } fun solve(valley: Valley, from: Pair<Int, Int>, to: Pair<Int, Int>): Pair<Int, Valley> { val maps = mutableListOf(valley) val visited = mutableSetOf<Pair<Int, Pair<Int, Int>>>() val queue = PriorityQueue<Pair<Int, Pair<Int, Int>>>( compareBy { it.first + (to.first - it.second.first) + (to.second - it.second.second) } ) queue.add(Pair(0, from)) while (queue.isNotEmpty()) { val pair = queue.poll() if (pair in visited) continue visited.add(pair) val (minute, location) = pair if (location == to) { return Pair(minute, maps[minute]) } val nextMinute = minute + 1 if (maps.size == nextMinute) { maps.add(maps.last().next()) } val map = maps[nextMinute] queue.addAll(map.options(location).map { Pair(minute + 1, it) }) } throw IllegalStateException("End never reached") } data class Valley(val width: Int, val height: Int, val blizzardsAndWalls: Map<Pair<Int, Int>, List<Char>>) { val finish = Pair(width - 2, height - 1) companion object { val START = Pair(1, 0) fun parse(lines: List<String>): Valley { val blizzardWalls = lines.mapIndexed { row, line -> line.mapIndexed { column, char -> Pair(column, row) to listOf(char) }.filter { '.' !in it.second }.toMap() }.reduce { a, b -> a + b } return Valley(lines.first().length, lines.size, blizzardWalls) } } fun print(location: Pair<Int, Int>): String { val buffer = StringBuffer() for (row in (0 until height)) { for (column in (0 until width)) { val c = Pair(column, row) if (c == location) { buffer.append("E") } else { val b = blizzardsAndWalls[c] ?: emptyList() buffer.append(if (b.isEmpty()) '.' else if (b.size == 1) b.first() else b.size) } } buffer.appendLine() } return buffer.toString() } fun next(): Valley { return Valley(width, height, blizzardsAndWalls.map { (c, l) -> l.map { d -> Pair(c, d) } }.flatten().map { p -> Pair(when (p.second) { '^' -> Pair(p.first.first, if (p.first.second == 1) (height - 2) else (p.first.second - 1)) '>' -> Pair(if (p.first.first == width - 2) 1 else (p.first.first + 1), p.first.second) 'v' -> Pair(p.first.first, if (p.first.second == height - 2) 1 else (p.first.second + 1)) '<' -> Pair(if (p.first.first == 1) (width - 2) else (p.first.first - 1), p.first.second) '#' -> p.first else -> throw IllegalStateException("Unknown direction ${p.second}") }, p.second) }.fold(mutableMapOf()) { m, p -> m[p.first] = (m[p.first] ?: emptyList()) + p.second; m }) } fun options(location: Pair<Int, Int>): List<Pair<Int, Int>> { val deltas = listOf(Pair(0, 0), Pair(0, -1), Pair(1, 0), Pair(0, 1), Pair(-1, 0)) return deltas.map { d -> Pair(location.first + d.first, location.second + d.second) } .filter { c -> (c.first > 0 && c.first < width - 1 && c.second > 0 && c.second < height - 1) || c == finish || c == START } .filterNot { c -> c in blizzardsAndWalls } } }
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
3,839
advent-of-code-2022
MIT License
src/Day03.kt
hoppjan
433,705,171
false
{"Kotlin": 29015, "Shell": 338}
fun main() { /** * Calculates binary [String] gamma and multiplies it with its inversion, epsilon. * @return decimal power consumption (product of gamma and epsilon) */ fun part1(input: List<String>): Int { val gamma = input.gammaString() val epsilon = gamma.invertBitString() return gamma.toInt(radix = 2) * epsilon.toInt(radix = 2) } /** * Calculates o2 and co2 ratings and * @return product of the ratings */ fun part2(input: List<String>) = input.filterO2Rating() * input.filterCO2Rating() runEverything("03", 198, 230, ::part1, ::part2, StringInputReader) } /** * Builds a binary [String] consisting of the more common [Char] for each column ('0' or '1'). */ private fun List<String>.gammaString(): String { val counted = '0' val counters = MutableList(first().length) { 0 } // counter for each column forEach { line -> line.forEachIndexed { index, char -> if (char == counted) counters[index]++ } } return buildString { for (i in counters) append(if (i > this@gammaString.size / 2) counted else '1') } } private fun String.invertBitString() = buildString { for (bitChar in this@invertBitString) append(if (bitChar == '1') 0 else 1) } /** * Filters the remaining [List] of binary [String]s for the more common [Char] in every column. * @return the last remaining matching binary [String] as an [Int] */ private fun List<String>.filterGasRating(filterRule: (toMatch: Char, matcher: Char) -> Boolean): Int { var filteredList = this for (i in first().indices) { filteredList = filteredList.filter { filterRule(it[i], filteredList.gammaString()[i]) } if (filteredList.size == 1) break } return filteredList.first().toInt(radix = 2) } // To be honest, I have no clue anymore how this filterRule works exactly, // but it was the only difference between o2 and co2 rating. private fun List<String>.filterO2Rating () = filterGasRating { toMatch, matcher -> toMatch != matcher } private fun List<String>.filterCO2Rating() = filterGasRating { toMatch, matcher -> toMatch == matcher }
0
Kotlin
0
0
04f10e8add373884083af2a6de91e9776f9f17b8
2,226
advent-of-code-2021
Apache License 2.0
src/Day05.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
fun main() { fun String.parseStacks(stacks: HashMap<Int, ArrayList<Char>>) { chunkedSequence(4) .map { it .replace(Regex("[\\[\\]\\s]"), "") .firstOrNull() } .forEachIndexed { index, char -> if (char != null) { stacks.compute(index + 1) { _, cur -> cur?.apply { add(0, char) } ?: arrayListOf(char) } } } } fun part1(input: List<String>): String { val stacks = hashMapOf<Int, ArrayList<Char>>() for (line in input) { if (line.contains('[')) { line.parseStacks(stacks) } else if (line.contains("move")) { val (howMany, from, to) = Regex("\\d+").findAll(line).toList().map { it.value.toInt() } repeat(howMany) { stacks[to]!!.add(stacks[from]!!.removeLast()) } } } return stacks.toSortedMap().values.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val stacks = hashMapOf<Int, ArrayList<Char>>() for (line in input) { if (line.contains('[')) { line.parseStacks(stacks) } else if (line.contains("move")) { val (howMany, from, to) = Regex("\\d+").findAll(line).toList().map { it.value.toInt() } stacks[to]!!.addAll(stacks[from]!!.takeLast(howMany)) stacks[from] = ArrayList(stacks[from]!!.dropLast(howMany)) } } return stacks.toSortedMap().values.map { it.last() }.joinToString("") } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
1,901
aoc-2022
Apache License 2.0
src/Day07.kt
nielsz
573,185,386
false
{"Kotlin": 12807}
fun main() { fun part1(input: List<String>): Int { val fileSystem = createFileSystem(input) return fileSystem.getDirectories() .filter { it.getSize() <= 100_000 } .sumOf { it.getSize() } } fun part2(input: List<String>): Int { val totalSize = 70_000_000 val minSize = 30_000_000 val fileSystem = createFileSystem(input) val usedSize = fileSystem.getCurrentDirectorySize() // 40_572_957 val availableSize = totalSize - usedSize // 29_427_043 val missingSize = minSize - availableSize // 572_957 return fileSystem.getDirectories() .map { it.getSize() } .filter { it > missingSize }.minOf { it } } val input = readInput("Day07") println("size is: " + part1(input)) // 1447046 println("size is: " + part2(input)) // 578710 } fun createFileSystem(input: List<String>): FileSystem { val fileSystem = FileSystem() var readingDirectoryContents = false for (line in input) { if (line[0] == '$') { if (line.substring(2).startsWith("cd ")) { fileSystem.changeDirectory(line.substring(5)) readingDirectoryContents = false } else if (line == "$ ls") { readingDirectoryContents = true } } else if (readingDirectoryContents) { fileSystem.addObject(line) } } fileSystem.changeDirectory("/") return fileSystem } class FileSystem { private val root = Directory("/", parent = null) private var workingDirectory = root fun changeDirectory(directory: String) { workingDirectory = when (directory) { "/" -> root ".." -> workingDirectory.parent!! else -> workingDirectory.getDirectory(directory) } } fun addObject(line: String) { workingDirectory.addObject(line) } fun getCurrentDirectorySize() = workingDirectory.getSize() fun getDirectories(): List<Directory> { return workingDirectory.getDirectories() } } data class Directory(val name: String, val parent: Directory?) : FileObject() { private val children = mutableListOf<FileObject>() fun getDirectories(): List<Directory> { val result = mutableListOf<Directory>() val childrenOfThisDirectory = children.filterIsInstance<Directory>() result.addAll(childrenOfThisDirectory) childrenOfThisDirectory.forEach { result.addAll(it.getDirectories()) } return result } override fun getSize() = children.sumOf { it.getSize() } fun getDirectory(name: String): Directory { return children.filterIsInstance<Directory>().first { it.name == name } } fun addObject(line: String) { if (line.startsWith("dir")) { children.add(Directory(name = line.substring(4), parent = this)) } else { val file = line.split(" ") children.add(File(name = file[1], filesize = file[0].toInt())) } } } data class File(val name: String, val filesize: Int) : FileObject() { override fun getSize() = filesize } abstract class FileObject { abstract fun getSize(): Int }
0
Kotlin
0
0
05aa7540a950191a8ee32482d1848674a82a0c71
3,246
advent-of-code-2022
Apache License 2.0
src/Day04/Day04.kt
Trisiss
573,815,785
false
{"Kotlin": 16486}
fun main() { fun rangeEntry(firstRange: Pair<Int, Int>, secondRange: Pair<Int, Int>): Boolean = firstRange.first >= secondRange.first && firstRange.second <= secondRange.second || secondRange.first >= firstRange.first && secondRange.second <= firstRange.second fun rangeOverlap(firstRange: Pair<Int, Int>, secondRange: Pair<Int, Int>): Boolean = firstRange.first >= secondRange.first && firstRange.first <= secondRange.second || secondRange.first >= firstRange.first && secondRange.first <= firstRange.second fun part1(input: List<String>): Int = input.count { line -> line.split(',').map { it.split('-').map { it.toInt() } }.run { rangeEntry(get(0)[0] to get(0)[1], get(1)[0] to get(1)[1]) } } fun part2(input: List<String>): Int = input.count { line -> line.split(',').map { it.split('-').map { it.toInt() } }.run { rangeOverlap(get(0)[0] to get(0)[1], get(1)[0] to get(1)[1]) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04/Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cb81a0b8d3aa81a3f47b62962812f25ba34b57db
1,278
AOC-2022
Apache License 2.0
src/main/kotlin/day3/Day3.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day3 import java.io.File fun computeGammaAndEpsilon(diagnosticReport: List<String>): Pair<Int, Int> { val p = List(diagnosticReport[0].length) { -diagnosticReport.size / 2 } val sums = diagnosticReport.fold(p) { acc, s -> s.map { it - '0' }.zip(acc){ a, b -> a + b } } val (gammaRaw, epsilonRaw) = sums .map { if (it >= 0) 1 else 0 } .fold(Pair("", "")) { acc, d -> Pair(acc.first + d, acc.second + (1 - d)) } return Pair(gammaRaw.toInt(2), epsilonRaw.toInt(2)) } fun computeOxygenGenerator(diagnosticReport: List<String>): Int { tailrec fun rec(remaining: List<String>, bitPosition: Int): String { // assuming input has always a single answer although after processing last bit // the remaining values are the same return if (remaining.size == 1) remaining.first() else { val (ones, zeros) = remaining.partition { it[bitPosition] == '1' } // assuming it's either 0 or 1) rec(if (ones.size >= zeros.size) ones else zeros, bitPosition + 1) } } return rec(diagnosticReport, 0).toInt(2) } fun computeCO2Scrubber(diagnosticReport: List<String>): Int { tailrec fun rec(remaining: List<String>, bitPosition: Int): String { // assuming input has always a single answer although after processing last bit // the remaining values are the same return if (remaining.size == 1) remaining.first() else { val (ones, zeros) = remaining.partition { it[bitPosition] == '1' } // assuming it's either 0 or 1) rec(if (ones.size < zeros.size) ones else zeros, bitPosition + 1) } } return rec(diagnosticReport, 0).toInt(2) } fun printProduct(pair: Pair<Int, Int>): Int = pair.first * pair.second fun main() { File("./input/day3.txt").useLines { lines -> val diagnosticReport = lines.toList() println("First value: ${printProduct(computeGammaAndEpsilon(diagnosticReport))}") println("Second value: ${computeOxygenGenerator(diagnosticReport) * computeCO2Scrubber(diagnosticReport)}") } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
1,985
advent-of-code-2021
MIT License
src/day08/Day08.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day08 import readInput fun main() { part1() part2() } enum class Direction { UP, DOWN, LEFT, RIGHT } fun part1() { val input = readInput(8) val grid = input.map { line -> line.map { it.digitToInt() } } fun Pair<Int, Int>.visible(direction: Direction, height: Int): Boolean = if (first !in 0..grid[0].lastIndex || second !in 0..grid.lastIndex) { true } else if (grid[second][first] >= height) { false } else { when (direction) { Direction.UP -> second == 0 || (first to second - 1).visible(Direction.UP, height) Direction.DOWN -> second == grid.lastIndex || (first to second + 1).visible(Direction.DOWN, height) Direction.LEFT -> first == 0 || (first - 1 to second).visible(Direction.LEFT, height) Direction.RIGHT -> first == grid[0].lastIndex || (first + 1 to second).visible(Direction.RIGHT, height) } } var total = 0 for ((rowIndex, row) in grid.withIndex()) { for ((index, height) in row.withIndex()) { if ((index to rowIndex - 1).visible(Direction.UP, height) || (index to rowIndex + 1).visible(Direction.DOWN, height) || (index - 1 to rowIndex).visible(Direction.LEFT, height) || (index + 1 to rowIndex).visible(Direction.RIGHT, height) ) { total++ } } } println(total) } fun part2() { val grid = readInput(8).map { line -> line.map { it.digitToInt() } } fun Pair<Int, Int>.score(direction: Direction, height: Int, stop: Boolean): Int = if (stop || first !in 0..grid[0].lastIndex || second !in 0..grid.lastIndex) { 0 } else { 1 + when (direction) { Direction.UP -> (first to second - 1).score(direction, height, grid[second][first] >= height) Direction.DOWN -> (first to second + 1).score(direction, height, grid[second][first] >= height) Direction.LEFT -> (first - 1 to second).score(direction, height, grid[second][first] >= height) Direction.RIGHT -> (first + 1 to second).score(direction, height, grid[second][first] >= height) } } var total = 0 for ((rowIndex, row) in grid.withIndex()) { for ((index, height) in row.withIndex()) { val product = (index to rowIndex - 1).score(Direction.UP, height, false) * (index to rowIndex + 1).score(Direction.DOWN, height, false) * (index - 1 to rowIndex).score(Direction.LEFT, height, false) * (index + 1 to rowIndex).score(Direction.RIGHT, height, false) total = maxOf(total, product) } } println(total) }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
2,808
advent-of-code-2022
Apache License 2.0
src/Day15.kt
SimoneStefani
572,915,832
false
{"Kotlin": 33918}
import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min fun main() { data class Point(val x: Long, val y: Long) { fun manhattan(other: Point): Long = (x - other.x).absoluteValue + (y - other.y).absoluteValue fun tuningFreq() = x * 4_000_000L + y } data class Sensor(val coords: Point, val beacon: Point) { val radius = coords.manhattan(beacon) fun contains(p: Point): Boolean = coords.manhattan(p) <= radius fun skipHorizontally(currentY: Long) = coords.x + radius - (coords.y - currentY).absoluteValue + 1 } fun parseLine(line: String): Sensor { val (sx, sy, bx, by) = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") .matchEntire(line)?.destructured ?: throw IllegalArgumentException("Can't parse line: $line") return Sensor(Point(sx.toLong(), sy.toLong()), Point(bx.toLong(), by.toLong())) } fun part1(input: List<String>, atY: Long): Int { var minX = 0L var maxX = 0L val sensors = input.map { line -> parseLine(line).also { minX = min(minX, it.coords.x - it.radius) maxX = max(maxX, it.coords.x + it.radius) } } return (minX - 1..maxX + 1).count { x -> sensors.any { it.contains(Point(x, atY)) } } - 1 } fun part2(input: List<String>, max: Long): Long { val sensors = input.map(::parseLine) (0..max).forEach { y -> var x = 0L while (x <= max) { val p = Point(x, y) val sensor = sensors.find { it.contains(p) } ?: return p.tuningFreq() x = sensor.skipHorizontally(y) } } return 0L } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2_000_000)) println(part2(input, 4_000_000L)) }
0
Kotlin
0
0
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
2,014
aoc-2022
Apache License 2.0
src/main/kotlin/days/y2023/day12_a/Day12.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day12_a import util.InputReader import util.timeIt typealias PuzzleLine = String typealias PuzzleInput = List<PuzzleLine> class Day12(val input: PuzzleInput) { fun partOne(): Long { return input.sumOf { line -> val config = line.toConfiguration() getCount(config.str, config.widths) } } fun partTwo(): Long { val bigInput = input.map { line -> line.toConfiguration().bigify(5) } return bigInput.sumOf { line -> getCount(line.str, line.widths) } } private val cachedCounts = mutableMapOf<Pair<String, List<Int>>, Long>() private fun getCount(remaining: String, widths: List<Int>): Long = cachedCounts.getOrPut(remaining to widths) { when { remaining.isEmpty() -> if (widths.isEmpty()) 1L else 0L widths.isEmpty() -> if (remaining.contains('#')) 0L else 1L else -> { val block = widths.first() var result = 0L result += if (remaining.couldBeFunctional()) getCount(remaining.drop(1), widths) else 0L result += if (remaining.couldBeBroken()) { if (remaining.fitsBlock(block)) getCount(remaining.drop(block + 1), widths.drop(1)) else 0L } else 0L return@getOrPut result } } } private fun String.fitsBlock(block: Int) = length >= block && !(substring(0, block).contains('.')) && (length == block || (this)[block] in setOf('.', '?')) private fun String.couldBeBroken() = first() in setOf('#', '?') private fun String.couldBeFunctional() = first() in setOf('.', '?') } data class Configuration( val str: String, val widths: List<Int> ) fun PuzzleLine.toConfiguration(): Configuration { val (head, blocks) = this.split(" ") return Configuration(head.chompDots(), blocks.split(",").map { it.toInt() }) } fun String.chompDots(): String { return this.replace(Regex("\\.+"), ".") } fun Configuration.bigify(n: Int) = copy( str = List(n) { this.str }.joinToString("?"), widths = List(n) { this.widths }.flatten() ) fun main() { timeIt { val year = 2023 val day = 12 val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day) fun partOne(input: PuzzleInput) = Day12(input).partOne() fun partTwo(input: PuzzleInput) = Day12(input).partTwo() println("Example 1: ${partOne(exampleInput)}") println("Puzzle 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput)}") println("Puzzle 2: ${partTwo(puzzleInput)}") } }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
2,911
AdventOfCode
Creative Commons Zero v1.0 Universal
src/Day09.kt
niltsiar
572,887,970
false
{"Kotlin": 16548}
import kotlin.math.absoluteValue import kotlin.math.sign fun main() { fun part1(input: List<String>): Int { return parseMoves(input).generateTailMoves().toSet().size } fun part2(input: List<String>): Int { val moves = parseMoves(input) var knotMoves = moves repeat(9) { knotMoves = knotMoves.generateTailMoves() } return knotMoves.toSet().size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val testInputB = readInput("Day09B_test") check(part2(testInputB) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } private fun parseMoves(input: List<String>): List<Pair<Int, Int>> { return buildList { var x = 0 var y = 0 add(Pair(x, y)) input.forEach { line -> val repetitions = line.drop(2).toInt() repeat(repetitions) { when (line[0]) { 'U' -> y++ 'D' -> y-- 'L' -> x-- 'R' -> x++ } add(Pair(x, y)) } } } } private fun List<Pair<Int, Int>>.generateTailMoves(): List<Pair<Int, Int>> { return runningFold(Pair(0, 0)) { oldPosition, newPosition -> val dx = newPosition.first - oldPosition.first val dy = newPosition.second - oldPosition.second when { // If diff is less than one in both directions tail doesn't move dx.absoluteValue <= 1 && dy.absoluteValue <= 1 -> oldPosition // More vertical distance dx.absoluteValue < dy.absoluteValue -> Pair(newPosition.first, newPosition.second - dy.sign) // More horizontal distance dx.absoluteValue > dy.absoluteValue -> Pair(newPosition.first - dx.sign, newPosition.second) else -> Pair(newPosition.first - dx.sign, newPosition.second - dy.sign) } } }
0
Kotlin
0
0
766b3e168fc481e4039fc41a90de4283133d3dd5
2,067
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
import kotlin.math.max import kotlin.math.min fun main() { fun isCompassing(low1: Int, high1: Int, low2: Int, high2: Int): Boolean { return (low1 <= low2 && high1 >= high2) || (low2 <= low1 && high2 >= high1) } fun part1(input: List<String>): Int { return input.count { val (firstRange, secondRange) = it.split(",") val (low1, high1) = firstRange.split("-").map { s -> s.toInt() } val (low2, high2) = secondRange.split("-").map { s -> s.toInt() } isCompassing(low1, high1, low2, high2) } } fun isCompassingPart2(low1: Int, high1: Int, low2: Int, high2: Int): Boolean { val biggestLow = max(low1, low2) val lowestHigh = min(high1, high2) return biggestLow <= lowestHigh } fun part2(input: List<String>): Int { return input.count { val (firstRange, secondRange) = it.split(",") val (low1, high1) = firstRange.split("-").map { s -> s.toInt() } val (low2, high2) = secondRange.split("-").map { s -> s.toInt() } isCompassingPart2(low1, high1, low2, high2) } } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
1,397
aoc-2022
Apache License 2.0
src/main/kotlin/day22.kt
gautemo
433,582,833
false
{"Kotlin": 91784}
import shared.getLines data class Cube(val on: Boolean, var x: Range, var y: Range, var z: Range){ fun volume() = x.length() * y.length() * z.length() } data class Range(val from: Int, val to: Int){ fun length() = (to - from).toLong() + 1 fun valid() = from <= to fun intersect(b: Range) = Range(maxOf(from, b.from), minOf(to, b.to)) } class AllCubes(private var cubes: List<Cube>, allowedSpace: Range? = null){ init { if(allowedSpace != null){ cubes = cubes.map { val x = allowedSpace.intersect(it.x) val y = allowedSpace.intersect(it.y) val z = allowedSpace.intersect(it.z) if(x.valid() && y.valid() && z.valid()){ return@map Cube(it.on, x, y, z) } null }.filterNotNull() } } fun volume(): Long{ var sum = 0L for((i, cube) in cubes.withIndex()){ if(!cube.on) continue var volume = cube.volume() val ignore = cubes.drop(i+1).map { val intersectX = cube.x.intersect(it.x) val intersectY = cube.y.intersect(it.y) val intersectZ = cube.z.intersect(it.z) if(intersectX.valid() && intersectY.valid() && intersectZ.valid()){ return@map Cube(true, intersectX, intersectY, intersectZ) } null }.filterNotNull() val ignoreAllCubes = AllCubes(ignore) volume -= ignoreAllCubes.volume() sum += volume } return sum } companion object{ fun initialize(input: List<String>, allowedSpace: Range? = null): AllCubes{ val cubes = input.map { val nrs = Regex("""-?\d+""").findAll(it) Cube( it.contains("on"), Range(nrs.elementAt(0).value.toInt(), nrs.elementAt(1).value.toInt()), Range(nrs.elementAt(2).value.toInt(), nrs.elementAt(3).value.toInt()), Range(nrs.elementAt(4).value.toInt(), nrs.elementAt(5).value.toInt()), ) } return AllCubes(cubes, allowedSpace) } } } fun main(){ val input = getLines("day22.txt") val allCubesLimited = AllCubes.initialize(input, Range(-50,50)) val task1 = allCubesLimited.volume() println(task1) val allCubes = AllCubes.initialize(input) val task2 = allCubes.volume() println(task2) }
0
Kotlin
0
0
c50d872601ba52474fcf9451a78e3e1bcfa476f7
2,538
AdventOfCode2021
MIT License
app/src/main/kotlin/advent/of/code/twentytwenty/Day11.kt
obarcelonap
320,300,753
false
null
package advent.of.code.twentytwenty fun main(args: Array<String>) { val seatPlan = newSeatPlan(getResourceAsText("/day11-input")) val stabilizedSeatPlanPart1 = stabilizeSeatPlan(seatPlan, ::countAdjacentOccupiedSeats, 4) val occupiedSeatsPart1 = countOccupiedSeats(stabilizedSeatPlanPart1) println("Part 1: found $occupiedSeatsPart1 occupied seats in seat plan") val stabilizedSeatPlanPart2 = stabilizeSeatPlan(seatPlan, ::countFirstOccupiedSeatInAllDirections, 5) val occupiedSeatsPart2 = countOccupiedSeats(stabilizedSeatPlanPart2) println("Part 2: found $occupiedSeatsPart2 occupied seats in seat plan") } abstract class Position(val icon: Char) { fun countOccupied() = when (this) { is Occupied -> 1 else -> 0 } } object Floor : Position('.') abstract class Seat(icon: Char) : Position(icon) object Occupied : Seat('#') object Empty : Seat('L') typealias SeatPlan = List<List<Position>> typealias CountSeats = (x: Int, y: Int) -> Int fun stabilizeSeatPlan(seatPlan: SeatPlan, countSeats: (seatPlan: SeatPlan) -> CountSeats, occupiedLimit: Int) = generateSequence(seatPlan, { val newSeatPlan = iterate(it, countSeats(it), occupiedLimit) if (newSeatPlan == it) null else newSeatPlan }) .last() fun newSeatPlan(text: String): SeatPlan = text.lines() .map { it.map { char -> when (char) { Occupied.icon -> Occupied Empty.icon -> Empty else -> Floor } } } fun countOccupiedSeats(seatPlan: SeatPlan) = seatPlan.flatten() .sumBy { it.countOccupied() } private fun iterate(seatPlan: SeatPlan, countSeats: CountSeats, occupiedLimit: Int): SeatPlan { val (maxX, maxY) = size(seatPlan) fun iteratePosition(x: Int, y: Int): Position = when (val currentPosition = seatPlan[x][y]) { is Empty -> if (countSeats(x, y) == 0) Occupied else Empty is Occupied -> if (countSeats(x, y) >= occupiedLimit) Empty else Occupied else -> currentPosition } return generateSequence(0, { it + 1 }) .take(maxX) .map { generateSequence(Pair(it, 0), { (x, y) -> Pair(x, y + 1) }) .take(maxY) .map { (x, y) -> iteratePosition(x, y) } .toList() } .toList() } fun countAdjacentOccupiedSeats(seatPlan: SeatPlan): CountSeats { return fun(x: Int, y: Int): Int = adjacentSeats(x, y, seatPlan) .map { (x, y) -> seatPlan[x][y] } .count { it is Occupied } } private fun adjacentSeats(x: Int, y: Int, seatPlan: SeatPlan): List<Pair<Int, Int>> { val seatPlanRange = inRange(seatPlan) return listOf( Pair(x - 1, y - 1), Pair(x, y - 1), Pair(x + 1, y - 1), Pair(x - 1, y), Pair(x + 1, y), Pair(x - 1, y + 1), Pair(x, y + 1), Pair(x + 1, y + 1) ) .filter { (x, y) -> seatPlanRange(x, y) } } private fun inRange(seatPlan: SeatPlan): (x: Int, y: Int) -> Boolean { val (maxX, maxY) = size(seatPlan) return fun(x, y) = x in 0 until maxX && y in 0 until maxY } fun countFirstOccupiedSeatInAllDirections(seatPlan: SeatPlan): CountSeats = fun(x: Int, y: Int): Int = adjacentSeats(x, y, seatPlan) .map { (adjacentX, adjacentY) -> navigateToSeat(Pair(adjacentX, adjacentY), Pair(adjacentX - x, adjacentY - y), seatPlan) } .count { it is Occupied } fun navigateToSeat(position: Pair<Int, Int>, direction: Pair<Int, Int>, seatPlan: SeatPlan): Seat? { if (!inRange(seatPlan)(position.first, position.second)) { return null } return when (val current = seatPlan[position.first][position.second]) { is Seat -> current else -> navigateToSeat(Pair(position.first + direction.first, position.second + direction.second), direction, seatPlan) } } private fun size(seatPlan: SeatPlan): Pair<Int, Int> = Pair(seatPlan.size, seatPlan[0].size)
0
Kotlin
0
0
a721c8f26738fe31190911d96896f781afb795e1
4,154
advent-of-code-2020
MIT License
src/main/kotlin/_50to100/Task54.kt
embuc
735,933,359
false
{"Kotlin": 110920, "Java": 60263}
package se.embuc._50to100 import se.embuc.Task import se.embuc.utils.readFileAsString import kotlin.math.sign // Poker hands class Task54 : Task { override fun solve(): Any { val games = readFileAsString("54_poker.txt").lines().map { parseGame(it) } var countPlayer1 = 0; for (game in games) { if (game.hand1.compareTo(game.hand2) > 0) { countPlayer1++ } } return countPlayer1 } data class Card(val s: String) : Comparable<Card> { val value: Int val suit: Char init { value = when (s[0]) { 'T' -> 10 'J' -> 11 'Q' -> 12 'K' -> 13 'A' -> 14 else -> s[0].toString().toInt() } suit = s[1] } override fun compareTo(other: Card): Int { return this.value.compareTo(other.value) } } data class Game(val hand1: Hand, val hand2: Hand) data class Hand(val hand: List<Card>) : Comparable<Hand> { var soretedCards: List<Int> var score: Int = 0 init { val (score, sortedCards) = evaluateHand() this.score = score this.soretedCards = sortedCards } private fun evaluateHand(): Pair<Int, List<Int>> { val cardCounts = hand.groupingBy { it.value }.eachCount() val cardValueOrder = "AKQJT98765432".toList().reversed() // Sort cards based on frequency, then by their poker value val sortedCards = cardCounts.entries.sortedWith( compareByDescending<Map.Entry<Int, Int>> { it.value } .thenByDescending { it.key } ).map { it.key } val isFlush = hand.map { it.suit }.distinct().size == 1 val sortedValues = hand.map { it.value }.sorted() val isStraight = sortedValues.zipWithNext().all { (a, b) -> b - a == 1 } val isStraightFlush = isFlush && isStraight val isRoyalFlush = isFlush && sortedValues == listOf(10, 11, 12, 13, 14) val score = when { isRoyalFlush -> 10 isStraightFlush -> 9 cardCounts.any { it.value == 4 } -> 8 // Four of a kind cardCounts.size == 2 && cardCounts.any { it.value == 3 } -> 7 // Full house isFlush -> 6 isStraight -> 5 cardCounts.any { it.value == 3 } -> 4 // Three of a kind cardCounts.size == 3 -> 3 // Two pair cardCounts.size == 4 -> 2 // One pair else -> 1 // High card } return Pair(score, sortedCards) } override fun compareTo(other: Hand): Int { return this.score.compareTo(other.score).let { if (it != 0) it else compareLexicographically(this.soretedCards, other.soretedCards) } } private fun compareLexicographically(handA: List<Int>, handB: List<Int>): Int { handA.forEachIndexed { index, charA -> val charB = handB[index] val diff = charA - charB if (diff != 0) return diff.sign } return 0 } } private fun parseGame(s: String): Game { val cards = s.split(" ") val player1 = Hand(cards.subList(0, 5).map { Card(it) }) val player2 = Hand(cards.subList(5, 10).map { Card(it) }) return Game(player1, player2) } }
0
Kotlin
0
1
79c87068303f862037d27c1b33ea037ab43e500c
2,869
projecteuler
MIT License
src/Day05.kt
achugr
573,234,224
false
null
import java.util.Stack class Move(val amount: Int, val from: Int, val to: Int) { companion object Parser { private val moveRegex = Regex("move (\\d+) from (\\d+) to (\\d+)") fun parse(input: String): Move? { return moveRegex.find(input) ?.groupValues ?.drop(1) ?.map { it.toInt() } ?.let { values -> Move(values[0], values[1] - 1, values[2] - 1) } } } } class ShipStacks(private val stacks: List<Stack<Char>>) { fun applyMove(move: Move) { repeat(move.amount) { val item = stacks[move.from].pop() stacks[move.to].push(item) } } fun applyMoveKeepingOrder(move: Move) { val stack = Stack<Char>() repeat(move.amount) { stack.push(stacks[move.from].pop()) } repeat(move.amount) { stacks[move.to].push(stack.pop()) } } fun getTop(): String { return stacks .map { it.peek() } .joinToString(separator = "") } companion object Reader { fun read(input: List<String>): ShipStacks { val columnPositions = getColumnPositions(input) val stacks = input.takeWhile { !isColumnLegendLine(it) } .flatMap { line -> columnPositions.map { column -> Pair(column, line.elementAtOrNull(column)) } } .filter { it.second != null && it.second!!.isLetter() } .sortedBy { it.first } .groupBy({ it.first }, { it.second!! }) .values .map { column -> column.reversed().toCollection(Stack()) } return ShipStacks(stacks); } private fun getColumnPositions(input: List<String>) = (input .find { isColumnLegendLine(it) } ?.mapIndexed { idx, char -> Pair(idx, char) } ?.filter { it.second.isDigit() } ?.map { it.first } ?: throw IllegalArgumentException("Incorrect input")) private fun isColumnLegendLine(it: String) = it.trimStart().startsWith("1") } } fun main() { fun part1(input: List<String>): String { val shipStacks = ShipStacks.read(input) input.stream() .map { Move.parse(it) } .forEach { it?.let { shipStacks.applyMove(it) } } return shipStacks.getTop() } fun part2(input: List<String>): String { val shipStacks = ShipStacks.read(input) input.stream() .map { Move.parse(it) } .forEach { it?.let { shipStacks.applyMoveKeepingOrder(it) } } return shipStacks.getTop() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
d91bda244d7025488bff9fc51ca2653eb6a467ee
2,926
advent-of-code-kotlin-2022
Apache License 2.0
src/year_2023/day_10/Day10.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_10 import readInput import util.* import kotlin.math.E enum class Direction() { North, East, South, West, ; fun inverse(): Direction { return when (this) { North -> South East -> West South -> North West -> East } } } enum class Pipe(val char: Char, val first: Direction, val second: Direction) { Vertical('|', Direction.North, Direction.South), Horizontal('-', Direction.East, Direction.West), Ninety_NE('L', Direction.North, Direction.East), Ninety_NW('J', Direction.North, Direction.West), Ninety_SW('7', Direction.South, Direction.West), Ninety_SE('F', Direction.South, Direction.East), ; companion object { fun fromChar(char: Char): Pipe? { return Pipe.values().firstOrNull { it.char == char } } } } data class Field( val startPoint: Point, val pipes: Map<Point, Pipe> ) object Day10 { /** * */ fun solutionOne(text: List<String>): Int { val field = parseField(text) return calculateLoopFromStart(field).size / 2 } /** * */ fun solutionTwo(text: List<String>): Long { val field = parseField(text) val path = calculateLoopFromStart(field) return path.calculateArea() } private fun parseField(text: List<String>): Field { var startingPoint: Point? = null val pipes = mutableMapOf<Point, Pipe>() text.forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char == 'S') { startingPoint = x to y } else { Pipe.fromChar(char)?.let { pipe -> pipes[(x to y)] = pipe } } } } return Field( startPoint = startingPoint!!, pipes = pipes ) } private fun calculateLoopFromStart(field: Field): List<Point> { makeLoop(Direction.North, field)?.let { return it } makeLoop(Direction.East, field)?.let { return it } makeLoop(Direction.South, field)?.let { return it } makeLoop(Direction.West, field)?.let { return it } throw IllegalArgumentException("No paths") } private fun makeLoop(direction: Direction, field: Field): List<Point>? { var currentPoint = field.startPoint var currentDirection = direction val path = mutableListOf<Point>() path.add(currentPoint) while (true) { currentPoint = when (currentDirection) { Direction.North -> currentPoint.up() Direction.East -> currentPoint.right() Direction.South -> currentPoint.down() Direction.West -> currentPoint.left() } if (currentPoint == field.startPoint) { return path } val nextPipe = field.pipes[currentPoint] ?: return null currentDirection = when (currentDirection.inverse()) { nextPipe.first -> nextPipe.second nextPipe.second -> nextPipe.first else -> return null } path.add(currentPoint) } } } fun main() { val text = readInput("year_2023/day_10/Day10.txt") val solutionOne = Day10.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day10.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,546
advent_of_code
Apache License 2.0
src/day11/Day11.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day11 import readInput import java.lang.Exception private fun lowestCommonDenominator(a: Long, b: Long): Long { val biggerNum = if (a > b) a else b var lcm = biggerNum while (true) { if (((lcm % a) == 0L) && ((lcm % b) == 0L)) { break } lcm += biggerNum } return lcm } data class Monkey( val name: String, val items: MutableList<Long>, val operationTokens: List<String>, var operationsCount: Long = 0, val testDivisor: Long, val trueResMonkeyName: String, val falseResMonkeyName: String ) { fun doOperationOn(item: Long): Long { operationsCount++ fun itemVal(itemStr: String): Long { return if (itemStr == "old") item else itemStr.toLong() } val item1 = itemVal(operationTokens[0]) val item2 = itemVal(operationTokens[2]) val res = when (val operator = operationTokens[1]) { "*" -> item1 * item2 "+" -> item1 + item2 else -> throw Exception("Operator $operator Unknown") } return res } fun test(input: Long) = input % testDivisor == 0L } fun reduce(input: Long) = input / 3 fun main() { fun parseMonkeys(input: List<String>): List<Monkey> { return input.chunked(7).map { monkeyArr -> Monkey( name = monkeyArr[0].removePrefix("Monkey ").removeSuffix(":"), items = monkeyArr[1].removePrefix(" Starting items: ").let { it.split(", ").map { i -> i.toLong() }.toMutableList() }, operationTokens = monkeyArr[2].removePrefix(" Operation: new = ").split(" "), testDivisor = monkeyArr[3].removePrefix(" Test: divisible by ").toLong(), trueResMonkeyName = monkeyArr[4].removePrefix(" If true: throw to monkey "), falseResMonkeyName = monkeyArr[5].removePrefix(" If false: throw to monkey ") ) } } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) repeat(20) { _ -> monkeys.forEach { monkey -> monkey.items.forEach { item -> var modifiedItem = item modifiedItem = monkey.doOperationOn(modifiedItem) modifiedItem = reduce(modifiedItem) monkey.test(modifiedItem).also { (if (it) monkey.trueResMonkeyName else monkey.falseResMonkeyName).also { name -> monkeys.find { it.name == name }!!.also { targetMonkey -> targetMonkey.items.add(modifiedItem) } } } } monkey.items.clear() } } return monkeys.sortedByDescending { it.operationsCount }.take(2).let { it[0].operationsCount * it[1].operationsCount } } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) val divisors = monkeys.map { it.testDivisor }.distinct() val lcd = divisors.fold(1L, fun (acc, i) = lowestCommonDenominator(acc, i)) repeat(10000) { _ -> monkeys.forEach { monkey -> monkey.items.forEach { item -> var modifiedItem = item modifiedItem = monkey.doOperationOn(modifiedItem) modifiedItem = modifiedItem % lcd monkey.test(modifiedItem).also { (if (it) monkey.trueResMonkeyName else monkey.falseResMonkeyName).also { name -> monkeys.find { it.name == name }!!.also { targetMonkey -> targetMonkey.items.add(modifiedItem) } } } } monkey.items.clear() } } return monkeys.sortedByDescending { it.operationsCount }.take(2).let { it[0].operationsCount * it[1].operationsCount } } val testInput = readInput("Day11_test") val input = readInput("Day11") println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 10605L) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test] : ${part2(testInput)}") check(part2(testInput) == 2713310158) println("Part 2 [Real] : ${part2(input)}") }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
4,520
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day24/Day24.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day24 import readInput import java.util.PriorityQueue import kotlin.math.abs class Map( val width: Int, val height: Int, val map: List<String>, private val horizontal: kotlin.collections.Map<Int, List<Blizzard>>, private val vertical: kotlin.collections.Map<Int, List<Blizzard>> ) { fun neighbours(position: Position, round: Int): List<Position> { return listOf( position, position + Direction.RIGHT, position + Direction.LEFT, position + Direction.UP, position + Direction.DOWN, ) .filter { itValid(it, round + 1) } } private fun itValid(it: Position, round: Int): Boolean { return it.col in (0 until width) && it.row in (0 until height) && map[it.row][it.col] != '#' && checkHorizontal(it, round) && checkVertical(it, round) } private fun checkHorizontal(it: Position, round: Int): Boolean { val innerCol = it.col - 1 val blizzards = horizontal[it.row] ?: emptyList() return blizzards.none { innerCol == currentCol(it, round) } } private fun currentCol(it: Blizzard, round: Int): Int { val innerWidth = width - 2 return ((it.initPosition.col - 1 + innerWidth + (it.direction.dx * round) % innerWidth) % innerWidth) } private fun checkVertical(it: Position, round: Int): Boolean { val innerRow = it.row - 1 val blizzards = vertical[it.col] ?: emptyList() return blizzards.none { innerRow == currentRow(it, round) } } private fun currentRow(it: Blizzard, round: Int): Int { val innerHeight = height - 2 return ((it.initPosition.row - 1 + innerHeight + (it.direction.dy * round) % innerHeight) % innerHeight) } fun println(round: Int) { val result: Array<CharArray> = Array(height) { CharArray(width) { '.' } } for (blizzard in vertical.values.flatten() + horizontal.values.flatten()) { val row = currentRow(blizzard, round) + 1 val col = currentCol(blizzard, round) + 1 val char = when (blizzard.direction) { Direction.LEFT -> '<' Direction.RIGHT -> '>' Direction.UP -> '^' Direction.DOWN -> 'v' } result[row][col] = char } println(result.joinToString(separator = "\n") { String(it) }) } } data class Position(val col: Int, val row: Int) { operator fun plus(dir: Direction): Position = Position(col + dir.dx, row + dir.dy) } enum class Direction(val dx: Int, val dy: Int, val value: Int) { LEFT(-1, 0, 2), UP(0, -1, 3), RIGHT(1, 0, 0), DOWN(0, 1, 1); } data class Blizzard(val initPosition: Position, val direction: Direction) fun parse(input: List<String>): Map { val map = input.takeWhile { it.isNotEmpty() } val (horizontal, vertical) = map.flatMapIndexed { y, line -> line.mapIndexed { x, c -> when (c) { '>' -> Blizzard(Position(x, y), Direction.RIGHT) '<' -> Blizzard(Position(x, y), Direction.LEFT) '^' -> Blizzard(Position(x, y), Direction.UP) 'v' -> Blizzard(Position(x, y), Direction.DOWN) '.', '#' -> null else -> error("Unexpected char $c") } }.filterNotNull() } .partition { it.direction in setOf(Direction.LEFT, Direction.RIGHT) } .let { (horizontal, vertical) -> horizontal.groupBy { it.initPosition.row } to vertical.groupBy { it.initPosition.col } } return Map(map[0].length, map.size, map, horizontal, vertical) } data class Path(val p: Position, val round: Int) { operator fun plus(it: Position): Path = Path(it, round + 1) } fun main() { fun solve(map: Map, start: Position, end: Position, startRound: Int): Int { val q = PriorityQueue(compareBy<Path> { (p, r) -> r + abs(end.col - p.col) + abs(end.row - p.row) }) val seen = mutableSetOf<Path>() q.add(Path(start, startRound)) while (q.isNotEmpty()) { val (p, round) = q.poll() if (p == end) { return round } val neighbours = map.neighbours(p, round) neighbours.forEach { val path = Path(it, round + 1) if (seen.add(path)) { q.add(path) } } } return -1 } fun part1(input: List<String>): Int { val map = parse(input) val end = Position(map.width - 2, map.height - 1) val start = Position(1, 0) return solve(map, start, end, 0) } fun part2(input: List<String>): Int { val map = parse(input) val end = Position(map.width - 2, map.height - 1) val start = Position(1, 0) val trip1 = solve(map, start, end, 0) val trip2 = solve(map, end, start, trip1) return solve(map, start, end, trip2) } val testInput = readInput("day24", "test") val input = readInput("day24", "input") val part1 = part1(testInput) println(part1) check(part1 == 18) println(part1(input)) val part2 = part2(testInput) println(part2) check(part2 == 54) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
5,378
aoc2022
Apache License 2.0
src/main/kotlin/day8/Day8.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day8 import java.io.File /* * An entry has the following format: <representation of the ten digits> | <display output> * i.e: * acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf */ fun parseOnlyDigitsOutput(entries: List<String>): List<List<String>> = entries.map { entry -> entry.split(" | ")[1].split(" ") } fun countOneFourSevenAndEights(listOfDisplayDigitRows: List<List<String>>): Int { val listOfSizes = listOf(2, 4, 3, 7) // The amount of signals that 1, 4, 7 and 8 require respectively return listOfDisplayDigitRows.sumOf { digitsRow -> digitsRow.count { digit -> listOfSizes.contains(digit.length) } } } /* * Digits representation * * 0: 1: 2: 3: 4: * aaaa .... aaaa aaaa .... * b c . c . c . c b c * b c . c . c . c b c * .... .... dddd dddd dddd * e f . f e . . f . f * e f . f e . . f . f * gggg .... gggg gggg .... * * 5: 6: 7: 8: 9: * aaaa aaaa aaaa aaaa aaaa * b . b . . c b c b c * b . b . . c b c b c * dddd dddd .... dddd dddd * . f e f . f e f . f * . f e f . f e f . f * gggg gggg .... gggg gggg */ private val digitMap = mapOf( "abcefg" to 0, "cf" to 1, "acdeg" to 2, "acdfg" to 3, "bcdf" to 4, "abdfg" to 5, "abdefg" to 6, "acf" to 7, "abcdefg" to 8, "abcdfg" to 9, ) /* * The input contains the representation of all digits. * With that information and the `digitMap` above we can already infer a few things: * - Only edge 'b' appears 6 times * - Only edge 'e' appears 4 times * - Only edge 'f' appears 9 times * - Edges 'a' and 'c' appear 8 times * - Edges 'd' and 'g' appear 7 times * * Also comparing the edges of numbers we can disambiguate edges in the last two statements: * - 7.edges - 4.edges = 'a' * - 4.edges - 7.edges = 'b' and 'd' * * Although the last subtraction will produce two edges, we've already inferred 'b' so we can discard it in favour of 'd' */ fun computeEquivalenceMap(digitsSignals: String): Map<Char, Char> { val translations = mutableMapOf<Char, Char>() // Get some equivalences due to unique number of occurrences val occurrences = digitsSignals.replace(" ", "").groupingBy { it }.eachCount() occurrences.forEach { (c, n) -> if (n == 4) translations[c] = 'e' if (n == 6) translations[c] = 'b' if (n == 9) translations[c] = 'f' } // Get the rest by comparing numbers with subtle differences val signals = digitsSignals.split(" ").groupBy { it.length } val four = signals[4]!!.first().toSet() // 4 the only digit that requires four signals to be represented val seven = signals[3]!!.first().toSet() // 7 the only digit that requires three signals to be represented // 7 - 4 will output edge 'a' val a = (seven - four).first() translations[a] = 'a' // 'c' is the other edge with 8 occurrences that is not 'a' val c = occurrences.entries.first { (c, n) -> n == 8 && c != a }.key translations[c] = 'c' // 4 - 7 will generate edges 'b' and 'd' but 'b' is already in the translations map val d = (four - seven).first { c -> !translations.contains(c) } translations[d] = 'd' // 'g' is the other edge with 7 occurrences that is not 'd' val g = occurrences.entries.first { (c, n) -> n == 7 && c != d }.key translations[g] = 'g' return translations } fun decipherSignal(entry: String): Int { val (signals, display) = entry.split(" | ") val equivalenceMap = computeEquivalenceMap(signals) val outputDigits = display .split(" ") .map { digit -> val translation = digit.map(equivalenceMap::get).sortedBy { it }.joinToString("") digitMap[translation] } return outputDigits.joinToString("").toInt() } fun main() { File("./input/day8.txt").useLines { lines -> val entries = lines.toList() val listOfDisplayDigitRows = parseOnlyDigitsOutput(entries) println("First part: ${countOneFourSevenAndEights(listOfDisplayDigitRows)}") println("First part: ${entries.sumOf { decipherSignal(it) }}") } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
4,227
advent-of-code-2021
MIT License
src/main/kotlin/days/Day2.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days class Day2 : Day(2) { val games = inputList.map(this::parseGame) override fun partOne(): Any { val bag = CubeSet(12, 13, 14) return games.filter { it.isPossible(bag) }.sumOf { it.id } } override fun partTwo(): Any { return games.sumOf { it.minimumCubeSet().power() } } fun parseGame(record: String): Game { val colon = record.indexOf(':') val id = record.substring(record.indexOf(' ') + 1, colon).toInt() val sets = record.substring(colon + 1).split(';').map { it.split(',') } return Game(id, sets.map { it.associate(this::parseCube) }.map(this::parseCubeSet)) } private fun parseCube(string: String): Pair<String, Int> { val (count, colour) = Regex("(\\d+) (.+)").findAll(string).toList().flatMap { it.groupValues.drop(1) } return colour to count.toInt() } private fun parseCubeSet(cubes: Map<String, Int>): CubeSet { return CubeSet( cubes.getOrDefault("red", 0), cubes.getOrDefault("green", 0), cubes.getOrDefault("blue", 0) ) } data class Game(val id: Int, val cubeSets: List<CubeSet>) { fun highestRed() = cubeSets.maxOf { it.red } fun highestGreen() = cubeSets.maxOf { it.green } fun highestBlue() = cubeSets.maxOf { it.blue } fun isPossible(bag: CubeSet): Boolean { return highestRed() <= bag.red && highestGreen() <= bag.green && highestBlue() <= bag.blue } fun minimumCubeSet(): CubeSet { return CubeSet(highestRed(), highestGreen(), highestBlue()) } } data class CubeSet(val red: Int, val green: Int, val blue: Int) { fun power() = red * green * blue } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
1,764
aoc-2023
Creative Commons Zero v1.0 Universal
2022/src/Day09.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src import kotlin.math.abs import kotlin.math.sign fun correct(vertex: Pair<Int,Int>) : Pair<Int,Int> { return if (abs(vertex.first) > 1 || abs(vertex.second) > 1) Pair((vertex.first - sign(vertex.first.toDouble())).toInt(), (vertex.second - sign(vertex.second.toDouble())).toInt()) else vertex } fun main() { val lookup = mapOf( "L" to Pair(-1,0), "R" to Pair(1,0), "U" to Pair(0,1), "D" to Pair(0,-1)) val visitedCells = mutableSetOf<Pair<Int,Int>>() fun part1(input: List<List<String>>): Int { visitedCells.clear() val knotPositions = mutableListOf( Pair(0, 0), Pair(0, 0)) input.forEach { val direction = lookup[it[0]] val distance = it[1].toInt() for (a in 0 until distance) { knotPositions[0] = Pair(first = knotPositions[0].first + direction!!.first, second = knotPositions[0].second + direction.second ) for (index in 1 until knotPositions.size) { val diff = Pair( first = knotPositions[index].first - knotPositions[index - 1].first, second = knotPositions[index].second - knotPositions[index - 1].second ) knotPositions[index] = Pair( first = knotPositions[index - 1].first + correct(diff).first, second = knotPositions[index - 1].second + correct(diff).second ) } visitedCells.add(knotPositions.last()) } } return visitedCells.size } fun part2(input: List<List<String>>): Int { visitedCells.clear() val knotPositions = mutableListOf( Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0) ) input.forEach { val direction = lookup[it[0]] val distance = it[1].toInt() for (a in 0 until distance) { knotPositions[0] = Pair(first = knotPositions[0].first + direction!!.first, second = knotPositions[0].second + direction.second ) for (index in 1 until knotPositions.size) { val diff = Pair( first = knotPositions[index].first - knotPositions[index - 1].first, second = knotPositions[index].second - knotPositions[index - 1].second ) knotPositions[index] = Pair( first = knotPositions[index - 1].first + correct(diff).first, second = knotPositions[index - 1].second + correct(diff).second ) } visitedCells.add(knotPositions.last()) } } return visitedCells.size } val input = readInput("input9") .map { it.trim().split(" ") } .toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
3,166
AoC
Apache License 2.0
2023/13/solve-1.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File fun partiallyMirrored(s1: String, s2: String) = with(s1.reversed()) { this.startsWith(s2) || s2.startsWith(this) } fun vReflectAtCol(input: List<String>): Int { val lastCol = input[0].lastIndex var candidates = (0 .. lastCol-1).filter { x -> input.indices.all { y -> val left = input[y].substring(0,x+1) val right = input[y].substring(x+1) partiallyMirrored(left, right) } } return if (candidates.count() == 0) { 0 } else { candidates[0] + 1 } } fun hReflectAtRow(input: List<String>): Int { var n = 1 var candidates = (0 .. input.lastIndex-1).filter { y -> input[0].indices.all { x -> val up = (0..y).map { input[it][x] }.joinToString("") val down = (y+1 .. input.lastIndex).map { input[it][x] }.joinToString("") partiallyMirrored(up, down) } } while (candidates.count() > 1) { candidates = candidates.filter { y -> (y - n + 1 >= 0) && (y + n <= input.lastIndex) && input[y-n+1] == input[y+n] } n++ } return if (candidates.count() == 0) { 0 } else { candidates[0] + 1 } } fun solve(input: List<String>): Int = 100 * hReflectAtRow(input) + vReflectAtCol(input) fun main(input: String) { val patterns: List<List<String>> = File(input).readText().split("\n\n").map { it.trimEnd('\n').split('\n') } patterns.map { solve(it) }.sum().let { println(it) } } main(args.getOrNull(0) ?: "input")
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,484
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/d23/D23_1.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d23 import d16.Direction import input.Input class D23_1 { companion object { private fun findSplittingIntersections(lines: List<String>): List<Pair<Int, Int>> { val intersections = mutableListOf<Pair<Int, Int>>() for (i in 1..<lines.lastIndex) { for (j in 1..<lines[i].lastIndex) { val loc = Pair(i, j) if (isSplittingIntersection(lines, loc)) intersections.add(loc) } } return intersections } private fun isPassableSlope(lines: List<String>, loc: Pair<Int, Int>, dir: Direction): Boolean { return when (dir) { Direction.ABOVE -> lines[loc.first - 1][loc.second] == '^' Direction.BELOW -> lines[loc.first + 1][loc.second] == 'v' Direction.LEFT -> lines[loc.first][loc.second - 1] == '<' Direction.RIGHT -> lines[loc.first][loc.second + 1] == '>' } } private fun isSplittingIntersection(lines: List<String>, loc: Pair<Int, Int>): Boolean { return Direction.entries.count { isPassableSlope(lines, loc, it) } == 2 } private fun getIntersectionMoves(lines: List<String>, loc: Pair<Int, Int>): List<Move> { val moves = mutableListOf<Move>() if (isPassableSlope(lines, loc, Direction.ABOVE)) moves.add(Move(loc, Pair(loc.first - 1, loc.second), 1)) if (isPassableSlope(lines, loc, Direction.BELOW)) moves.add(Move(loc, Pair(loc.first + 1, loc.second), 1)) if (isPassableSlope(lines, loc, Direction.LEFT)) moves.add(Move(loc, Pair(loc.first, loc.second - 1), 1)) if (isPassableSlope(lines, loc, Direction.RIGHT)) moves.add(Move(loc, Pair(loc.first, loc.second + 1), 1)) return moves } private fun getNextMove(lines: List<String>, move: Move): Move { val top = Pair(move.to.first - 1, move.to.second) if (lines[top] in listOf('.', '^') && top != move.from) return Move(move.to, top, move.steps + 1) val bottom = Pair(move.to.first + 1, move.to.second) if (lines[bottom] in listOf('.', 'v') && bottom != move.from) return Move(move.to, bottom, move.steps + 1) val left = Pair(move.to.first, move.to.second - 1) if (lines[left] in listOf('.', '<') && left != move.from) return Move(move.to, left, move.steps + 1) val right = Pair(move.to.first, move.to.second + 1) if (lines[right] in listOf('.', '>') && right != move.from) return Move(move.to, right, move.steps + 1) throw RuntimeException("No moves possible") } private fun findNextIntersectionAndSteps( lines: List<String>, intersections: List<Pair<Int, Int>>, move: Move ): Pair<Int, Int> { val index = intersections.indexOf(move.to) if (index != -1 || move.to.first == lines.lastIndex) { return Pair(index, move.steps) } return findNextIntersectionAndSteps(lines, intersections, getNextMove(lines, move)) } fun solve() { val lines = Input.read("input.txt") val intersections = findSplittingIntersections(lines) val start = Pair(0, lines[0].indexOf('.')) // directed edge to step count val longestDirectDistance = mutableMapOf<Pair<Int, Int>, Int>() for (fromIntersectionIndex in intersections.indices) { val fromIntersection = intersections[fromIntersectionIndex] val moves = getIntersectionMoves(lines, fromIntersection) for (move in moves) { val next = findNextIntersectionAndSteps(lines, intersections, move) val toIntersectionIndex = next.first val steps = next.second longestDirectDistance.putIfLargerOrAbsent( Pair( fromIntersectionIndex, toIntersectionIndex ), steps ) } } val startToFirstIntersection = findNextIntersectionAndSteps( lines, intersections, Move(start, Pair(start.first + 1, start.second), 1) ) longestDirectDistance[Pair(-2, startToFirstIntersection.first)] = startToFirstIntersection.second val finishDistances = mutableListOf<Int>() val posStack = ArrayDeque<Pair<Int, Int>>() posStack.add(startToFirstIntersection) while (posStack.isNotEmpty()) { val pos = posStack.removeLast() val nextIntersections = longestDirectDistance.filter { it.key.first == pos.first } nextIntersections.forEach { val to = it.key.second val totalSteps = pos.second + it.value if (to == -1) finishDistances.add(totalSteps) else posStack.add(Pair(to, totalSteps)) } } println(finishDistances.max()) } } } fun main() { D23_1.solve() }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
5,329
aoc2023-kotlin
MIT License
src/Day04.kt
camina-apps
572,935,546
false
{"Kotlin": 7782}
data class Section( val start: Int, val end: Int ) fun main() { // horizontal arranged based on starting point fun parseIntoArrangedSections(input: String): Pair<Section, Section> { val elves = input.split(",") val rawSectionA = elves[0].split("-") val rawSectionB = elves[1].split("-") val sectionA = Section(rawSectionA[0].toInt(), rawSectionA[1].toInt()) val sectionB = Section(rawSectionB[0].toInt(), rawSectionB[1].toInt()) return if (sectionA.start <= sectionB.start) { Pair(sectionA, sectionB) } else { Pair(sectionB, sectionA) } } fun fullyContains(left: Section, right: Section): Boolean { if (left.start == right.start || left.end == right.end) return true return left.end >= right.end } fun isOverlapping(left: Section, right: Section): Boolean { return (right.start <= left.end && right.start >= left.start ) } fun part1(input: List<String>): Int { return input.sumOf { line -> val sections = parseIntoArrangedSections(line) if (fullyContains(sections.first, sections.second)) { 1.0 } else { 0.0 } }.toInt() } fun part2(input: List<String>): Int { return input.sumOf { line -> val sections = parseIntoArrangedSections(line) if (isOverlapping(sections.first, sections.second)) { 1.0 } else { 0.0 } }.toInt() } 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
fb6c6176f8c127e9d36aa0b7ae1f0e32b5c31171
1,788
aoc_2022
Apache License 2.0
src/Day03.kt
anisch
573,147,806
false
{"Kotlin": 38951}
fun findMatch(s1: String, s2: String): Char { for (c in 'A'..'z') { if (c in s1 && c in s2) return c } error("wtf???") } fun findMatch(s1: String, s2: String, s3: String): Char { for (c in 'A'..'z') { if (c in s1 && c in s2 && c in s3) return c } error("wtf???") } fun getPriority(c: Char): Int = if (c.isLowerCase()) c - 'a' + 1 else c - 'A' + 27 fun main() { fun part1(input: List<String>): Int { return input .map { r -> r.chunked(r.length shr 1) } .map { (f, s) -> findMatch(f, s) } .sumOf { c -> getPriority(c) } } fun part2(input: List<String>): Int { return input .chunked(3) .map { (r1, r2, r3) -> findMatch(r1, r2, r3) } .sumOf { c -> getPriority(c) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") val input = readInput("Day03") check(part1(testInput) == 157) println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
1,097
Advent-of-Code-2022
Apache License 2.0
src/2017Day10_2.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
package day2017_10_2 import utils.runSolver private typealias SolutionType = Int private const val defaultSolution = 0 private const val dayNumber: String = "10" private val testSolution1: SolutionType? = 88 private val testSolution2: SolutionType? = 36 class CircularList(private val backingList: MutableList<Int>) : List<Int> by backingList { override operator fun get(index: Int): Int = backingList[index % backingList.size] fun set(index: Int, element: Int): Int = backingList.set(index % backingList.size, element) fun replace(index: Int, collection: Collection<Int>) { collection.forEachIndexed { curIndex, el -> set(index + curIndex, el) } } fun cut(index: Int, length: Int): List<Int> { val out = mutableListOf<Int>() for (curIndex in index until length + index) { out.add(get(curIndex)) } return out } override fun toString() = backingList.toString() } private fun part1(input: Pair<List<Int>, Int>): SolutionType { val (lengths, loopSize) = input val list = CircularList(List(loopSize) { it }.toMutableList()) var skip = 0 var curIndex = 0 lengths.forEach { length -> val cut = list.cut(curIndex, length) list.replace(curIndex, cut.asReversed()) curIndex += length + skip skip += 1 } println(list) return list[0] * list[1] } private fun part2(index: String): String { val lengths = index.map { it.code } + listOf(17, 31, 73, 47, 23) val allLengths = List(64) { lengths }.flatten() val list = CircularList(List(256) { it }.toMutableList()) var skip = 0 var curIndex = 0 allLengths.forEach { length -> val cut = list.cut(curIndex, length) list.replace(curIndex, cut.asReversed()) curIndex += length + skip skip += 1 } val chunks = list.chunked(16) val denseList = chunks.map { it.reduce { acc, i -> acc.xor(i) } } return denseList.joinToString(separator = "") { it.toString(16) } } fun main() { val part1TestInput = listOf(3, 4, 1, 5) val part1Input = listOf(97, 167, 54, 178, 2, 11, 209, 174, 119, 248, 254, 0, 255, 1, 64, 190) val part2TestInput = "AoC 2017" val part2Input = "97,167,54,178,2,11,209,174,119,248,254,0,255,1,64,190" runSolver("Test 1", part1TestInput to 5, 12, ::part1) runSolver("Test 2 $part2TestInput", part2TestInput, "33efeb34ea91902bb2f59c9920caa6cd", ::part2) runSolver("Part 1", part1Input to 256, null, ::part1) runSolver("Part 2", part2Input, null, ::part2) }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
2,622
2022-AOC-Kotlin
Apache License 2.0
src/Day16.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun part1(input: List<String>): Int { val grid = ValvesGrid.parse(input) var states = listOf(ValvesSingleOperatorState(me = Operator(listOf("AA")))) repeat(30) { states = states .asSequence() .map { state -> with(state) { val opened = me.opened val newPressure = totalPressure + opened.values.sum() val current = me.steps.first() val nextSteps = me.steps.drop(1) val valve = grid[current] if (nextSteps.isEmpty() && !opened.contains(current) && valve.rate > 0) { listOf( copy( me = me.copy(opened = opened.plus(current to valve.rate)), totalPressure = newPressure, ) ) } else { if (nextSteps.isNotEmpty()) { listOf( copy( me = me.copy(steps = nextSteps), totalPressure = newPressure, ) ) } else { grid.nexSteps(current, opened.keys).map { steps -> copy( me = me.copy(steps = steps), totalPressure = newPressure, ) } } }.ifEmpty { listOf(copy(totalPressure = newPressure)) } } } .flatten() .sortedByDescending(ValvesSingleOperatorState::totalPressure) .toList() } return states.maxBy { it.totalPressure }.also { println(it.me.opened) }.totalPressure } fun part2(input: List<String>): Int { val grid = ValvesGrid.parse(input) var states = listOf( ValvesTwoOperatorsState( me = Operator(listOf("AA")), el = Operator(listOf("AA")), ) ) repeat(26) { states = states .asSequence() .map { state -> with(state) { val opened = me.opened.plus(el.opened) val currentTargets = listOf(me.steps.last(), el.steps.last()) val newPressure = totalPressure + opened.values.sum() fun newOperators(operator: Operator): List<Operator> { val current = operator.steps.first() val nextSteps = operator.steps.drop(1) val valve = grid[current] return if (nextSteps.isEmpty() && !opened.contains(current) && valve.rate > 0) { listOf(operator.copy(opened = operator.opened.plus(current to valve.rate))) } else { if (nextSteps.isNotEmpty()) { listOf(operator.copy(steps = nextSteps)) } else { grid.nexSteps(current, opened.keys.plus(currentTargets)) .map { steps -> operator.copy(steps = steps) } } } } newOperators(me).map { me -> newOperators(el).mapNotNull { el -> if (me.steps != el.steps) { ValvesTwoOperatorsState( me = me, el = el, totalPressure = newPressure, ) } else { null } } } .flatten() .ifEmpty { listOf(state.copy(totalPressure = newPressure)) } } } .flatten() .sortedByDescending(ValvesTwoOperatorsState::totalPressure) .take(10000) .toList() } return states.maxBy { it.totalPressure }.also { println(it) }.totalPressure } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") check(part1(testInput).also { println("part1 test: $it") } == 1651) check(part2(testInput).also { println("part2 test: $it") } == 1707) val input = readInput("Day16") println(part1(input)) println(part2(input)) } private data class Operator( val steps: List<String>, val opened: Map<String, Int> = emptyMap(), ) private data class Valve( val rate: Int, val connections: List<String>, ) private data class ValvesSingleOperatorState( val me: Operator, val totalPressure: Int = 0, ) private data class ValvesTwoOperatorsState( val me: Operator, val el: Operator, val totalPressure: Int = 0, ) private class ValvesGrid( val valves: Map<String, Valve>, ) { private val steps: MutableMap<String, MutableMap<String, List<String>>> = mutableMapOf() operator fun get(key: String) = valves.getValue(key) fun nexSteps(from: String, visited: Set<String> = emptySet()): List<List<String>> { return valves .filterKeys { !visited.contains(it) } .filterValues { it.rate > 0 } .entries .sortedByDescending { it.value.rate } .map { stepsFromToCached(from, it.key) } .sortedBy { it.size } .filter { it.isNotEmpty() } } private fun stepsFromToCached(from: String, to: String, visited: Set<String> = emptySet()): List<String> { return steps.getOrPut(from) { mutableMapOf() }.getOrPut(to) { stepsFromTo(from, to, visited) } } private fun stepsFromTo(from: String, to: String, visited: Set<String> = emptySet()): List<String> { val (_, connected) = get(from) return if (connected.contains(to)) { listOf(to) } else { connected.filterNot(visited::contains) .map { label -> label to stepsFromTo(label, to, visited + from) } .filter { it.second.isNotEmpty() } .minByOrNull { it.second.size } ?.let { listOf(it.first) + it.second } ?: emptyList() } } companion object { private val regexValve = Regex("Valve ([A-Z][A-Z]) has flow rate=(\\d+);") private val regexConnected = Regex("tunnels? leads? to valves? (.*)$") fun parse(input: List<String>): ValvesGrid { return ValvesGrid( buildMap { input.map { line -> val (label, rate) = regexValve.find(line)!!.groupValues.drop(1) val connected = regexConnected.find(line)!!.groupValues[1].split(", ") put(label, Valve(rate.toInt(), connected)) } } ) } } }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
7,647
aoc-2022
Apache License 2.0
src/Day05.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
fun readStacks(input: List<String>, stackNumLine: String): List<ArrayDeque<Char>> { val stackNums = stackNumLine.toCharArray() val countStacks = stackNums.filterNot { it == ' ' }.last().toString().toInt() val stacks = MutableList(countStacks) { ArrayDeque<Char>() } input.forEach { line -> line.toCharArray().forEachIndexed { i, chr -> if (listOf('[', ']', ' ').contains(chr).not()) { val stackNum = stackNums[i].toString().toInt() - 1 if (stackNum >= 0) { stacks[stackNum].addLast(chr) } } } } return stacks } fun main() { fun part1(input: List<String>): String { val stackInput = input.takeWhile { it.isNotEmpty() } val stacks = readStacks(stackInput.dropLast(1), stackInput.last()) input.drop(stackInput.size + 1).forEach { line -> val match = """move\s(\d+)\sfrom\s(\d+)\sto\s(\d+)""".toRegex().find(line) val (numCrates, stackNumFrom, stackNumTo) = match!!.destructured repeat(numCrates.toInt()) { val firstChr = stacks[stackNumFrom.toInt() - 1].removeFirst() stacks[stackNumTo.toInt() - 1].addFirst(firstChr) } } return stacks.map { it.first() }.joinToString("") } fun part2(input: List<String>): String { val stackInput = input.takeWhile { it.isNotEmpty() } val stacks = readStacks(stackInput.dropLast(1), stackInput.last()) input.drop(stackInput.size + 1).forEach { line -> val match = """move\s(\d+)\sfrom\s(\d+)\sto\s(\d+)""".toRegex().find(line) val (numCrates, stackNumFrom, stackNumTo) = match!!.destructured (1..numCrates.toInt()).map { stacks[stackNumFrom.toInt() - 1].removeFirst() }.reversed().forEach { stacks[stackNumTo.toInt() - 1].addFirst(it) } } return stacks.map { it.first() }.joinToString("") } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
2,204
advent-of-code-2022
Apache License 2.0
src/Day07.kt
coolcut69
572,865,721
false
{"Kotlin": 36853}
fun main() { fun parseFileSystem(inputs: List<String>): Directory { val rootDirectory = Directory("/", null) var currentDir = rootDirectory for (action in inputs) { if (action.startsWith("$")) { // command when (action) { "$ ls" -> continue "$ cd .." -> currentDir = currentDir.parent!! else -> { val newDir = action.substringAfter("$ cd ") if (newDir != "/") { currentDir = currentDir.getDirectory(newDir) } } } } else { if (action.startsWith("dir")) { val dirName = action.substringAfter("dir ") val directory = Directory(dirName, currentDir) currentDir.addDirectory(directory) } else { val size = action.split(" ")[0].toInt() val fileName = action.split(" ")[1] File(fileName, size) currentDir.addFile(File(fileName, size)) } } } return rootDirectory } fun part1(inputs: List<String>): Int { val rootDirectory = parseFileSystem(inputs) return rootDirectory.getDirectories(false).filter { it.getSize() <= 10_0000 }.sumOf { it.getSize() } } fun part2(inputs: List<String>): Int { val rootDirectory = parseFileSystem(inputs) val requiredDiskspace = 30_000_000 - (70_000_000 - rootDirectory.getSize()) return rootDirectory.getDirectories(true).filter { it.getSize() > requiredDiskspace }.minOf { it.getSize() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95_437) check(part2(testInput) == 24_933_642) val input = readInput("Day07") // println(part1(input)) check(part1(input) == 1_723_892) // println(part2(input)) check(part2(input) == 8_474_158) } data class Directory(val name: String, val parent: Directory?) { private val files: MutableList<File> = ArrayList() private val directories: MutableList<Directory> = ArrayList() fun addFile(file: File) { files.add(file) } fun addDirectory(directory: Directory) { directories.add(directory) } fun getDirectory(name: String): Directory { return directories.find { directory: Directory -> directory.name == name }!! } fun getSize(): Int { return files.sumOf { it.size } + directories.sumOf { it.getSize() } } fun getDirectories(includeRoot: Boolean): List<Directory> { return when (includeRoot) { true -> concatenate(listOf(this), directories, directories.flatMap { it.getDirectories(false) }) false -> concatenate(directories, directories.flatMap { it.getDirectories(false) }) } } } fun <T> concatenate(vararg lists: List<T>): List<T> { return listOf(*lists).flatten() } data class File(val name: String, val size: Int)
0
Kotlin
0
0
031301607c2e1c21a6d4658b1e96685c4135fd44
3,186
aoc-2022-in-kotlin
Apache License 2.0
year2018/src/main/kotlin/net/olegg/aoc/year2018/day24/Day24.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day24 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 24](https://adventofcode.com/2018/day/24) */ object Day24 : DayOf2018(24) { override fun first(): Any? { val (immune, infection) = data .split("\n\n") .map { it.lines().drop(1) } .mapIndexed { system, group -> group.mapIndexedNotNull { index, line -> Group.from(line, index + 1, system) } } return solve(immune + infection).sumOf { it.units.toInt() } } override fun second(): Any? { val (immune, infection) = data .split("\n\n") .map { it.lines().drop(1) } .mapIndexed { system, group -> group.mapIndexedNotNull { index, line -> Group.from(line, index + 1, system) } } generateSequence(0) { it + 1 }.forEach { boost -> val boosted = immune.map { it.copy(attack = it.attack + boost) } val result = solve(boosted + infection) when { result.isEmpty() -> println("Boost $boost, stalemate") result.first().system == immune.first().system -> return result.sumOf { it.units } else -> println("Boost $boost, ${result.sumOf { it.units }} units remaining") } } return -1 } private fun solve(initialBoard: List<Group>): List<Group> { val board = initialBoard.map { it.copy() }.toMutableList() while (board.distinctBy { it.system }.size == 2) { val attacks = mutableMapOf<Pair<Int, Int>, Group?>() board .sortedWith( compareByDescending<Group> { it.power() } .thenByDescending { it.initiative }, ) .forEach { group -> val targets = board .filter { it.system != group.system } .filterNot { it in attacks.values } targets .map { it to group.damage(it) } .filterNot { it.second == 0L } .sortedWith( compareByDescending<Pair<Group, Long>> { it.second } .thenByDescending { it.first.power() } .thenByDescending { it.first.initiative }, ) .firstOrNull() ?.let { attacks[group.system to group.index] = it.first } } val killed = board .sortedByDescending { it.initiative } .mapNotNull { group -> group.takeIf { it.units > 0 } ?.let { attacks[group.system to group.index]?.let { target -> (group.damage(target) / target.hit).also { target.units -= it } } } } .sum() if (killed == 0L) { return emptyList() } board.removeIf { it.units <= 0 } } return board } data class Group( var units: Long, val hit: Long, val weak: Set<String>, val immune: Set<String>, val attack: Long, val type: String, val initiative: Int, val index: Int, val system: Int, ) { companion object { private val PATTERN = ( "(-?\\d+) units each with (-?\\d+) hit points" + " ?\\(?([^)]*)\\)? with an attack that does (-?\\d+) (\\w+) damage at initiative (-?\\d+)" ).toRegex() fun from( string: String, index: Int, system: Int ): Group? { return PATTERN.matchEntire(string)?.let { match -> val (unitsRaw, hitRaw, specRaw, attackRaw, type, initiativeRaw) = match.destructured val weak = mutableSetOf<String>() val immune = mutableSetOf<String>() specRaw .takeIf { it.isNotBlank() } ?.split("; ") ?.forEach { spec -> val (kind, typesRaw) = spec.split(" to ") val types = typesRaw.split(", ") when (kind) { "weak" -> weak += types "immune" -> immune += types } } return@let Group( units = unitsRaw.toLong(), hit = hitRaw.toLong(), weak = weak, immune = immune, attack = attackRaw.toLong(), type = type, initiative = initiativeRaw.toInt(), index = index, system = system, ) } } } fun damage(to: Group) = when (type) { in to.immune -> 0L in to.weak -> power() * 2L else -> power() } fun power() = units * attack } } fun main() = SomeDay.mainify(Day24)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
4,467
adventofcode
MIT License
src/Day11.kt
mcrispim
573,449,109
false
{"Kotlin": 46488}
fun main() { class Monkey( val items: MutableList<Long>, val op: String, val paramStr: String, val testDivisor: Int, val testTrue: Int, val testFalse: Int ) { var inspectionCounter = 0 fun processItems(monkeyList: List<Monkey>, relief: (Long) -> Long) { while (items.isNotEmpty()) { var item = items.removeAt(0) val par = if (paramStr == "old") item else paramStr.toLong() item = if (op == "+") item + par else item * par item = relief(item) if (item % testDivisor == 0L) { monkeyList[testTrue].items.add(item) } else { monkeyList[testFalse].items.add(item) } inspectionCounter++ } } } fun getCommonDivisor(monkeyList: List<Monkey>): Long { var result = 1L for (monkey in monkeyList) { result *= monkey.testDivisor } return result } fun getInput(input: List<String>): List<Monkey> { val monkeyList = mutableListOf<Monkey>() var lineCounter = 0 while (lineCounter < input.size) { val firstLine = input[lineCounter++] // Monkey number if (firstLine.isBlank()) continue val items = input[lineCounter++].substringAfter(":").split(",").map { it.trim { c -> c == ' ' }.toLong() } .toMutableList() val operation = input[lineCounter++].substringAfter("old ").split(" ") val op = operation.first() val paramStr = operation.last() val testDivisor = input[lineCounter++].substringAfter("by ").toInt() val testTrue = input[lineCounter++].substringAfter("monkey ").toInt() val testfalse = input[lineCounter++].substringAfter("monkey ").toInt() monkeyList.add(Monkey(items, op, paramStr, testDivisor, testTrue, testfalse)) } return monkeyList } fun part1(input: List<String>): Long { val monkeyList = getInput(input) for (round in 1..20) { for (monkey in monkeyList) { monkey.processItems(monkeyList) { it / 3 } } } val (counter1, counter2) = monkeyList.map { it.inspectionCounter }.sortedDescending().take(2) return (counter1 * counter2).toLong() } fun part2(input: List<String>): Long { val monkeyList = getInput(input) val cd = getCommonDivisor(monkeyList) for (round in 1..10000) { for (monkey in monkeyList) { monkey.processItems(monkeyList) { (it % cd) + cd } } } val countersList = monkeyList.map { it.inspectionCounter.toLong() } val (counter1, counter2) = countersList.sortedDescending().take(2) return (counter1 * counter2) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10_605L) check(part2(testInput) == 2_713_310_158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5fcacc6316e1576a172a46ba5fc9f70bcb41f532
3,225
AoC2022
Apache License 2.0
src/day7/Day07.kt
JoeSkedulo
573,328,678
false
{"Kotlin": 69788}
package day7 import Runner fun main() { Day7Runner().solve() } class Day7Runner : Runner<Int>( day = 7, expectedPartOneTestAnswer = 95437, expectedPartTwoTestAnswer = 24933642 ) { override fun partOne(input: List<String>, test: Boolean): Int { val contents = directoryContents(input) val directories = sizedDirectories(contents) return directories .filter { directory -> directory.size <= 100000 } .sumOf { directory -> directory.size } } override fun partTwo(input: List<String>, test: Boolean): Int { val contents = directoryContents(input) val directories = sizedDirectories(contents) val totalSize = directories.maxOf { directory -> directory.size } val freeSpace = 70000000 - totalSize val needed = 30000000 - freeSpace return directories .filter { directory -> directory.size >= needed } .minOf { directory -> directory.size } } private fun sizedDirectories(files: List<DirectoryContent>) : List<SizedDirectory> { val paths = files.map { file -> file.path }.distinct() return paths.map { path -> SizedDirectory( fullPath = path, size = files .filter { content -> content.path.startsWith(path) } .filterIsInstance<File>() .sumOf { it.size } ) } } private fun directoryContents(input: List<String>) : List<DirectoryContent> { return input.mapIndexedNotNull { index, line -> when { line.isFile() -> File(size = line.fileSize(), path = input.pathForLine(index)) line.isDir() -> Directory(path = input.pathForLine(index)) else -> null } } } private fun List<String>.pathForLine(number: Int) : String = let { lines -> return buildList { lines.subList(0, number).forEach { line -> when { line.isBack() -> removeLast() line.isChangeDirectory() -> add(line.dirName()) line.isRootDirectory() -> clear() } } }.joinToString("/") } private fun String.fileSize() = split(" ")[0].toInt() private fun String.dirName() = split(" ")[2] private fun String.isFile() = first().toString().toIntOrNull() != null private fun String.isDir() = startsWith("dir") private fun String.isChangeDirectory() = split(" ")[1] == "cd" private fun String.isBack() = this == "$ cd .." private fun String.isRootDirectory() = this == "$ cd /" } sealed class DirectoryContent( open val path: String ) data class File( val size: Int, override val path: String ) : DirectoryContent(path) data class Directory( override val path: String ) : DirectoryContent(path) data class SizedDirectory( val fullPath: String, val size: Int )
0
Kotlin
0
0
bd8f4058cef195804c7a057473998bf80b88b781
2,999
advent-of-code
Apache License 2.0
src/main/kotlin/net/navatwo/adventofcode2023/day1/Day1Solution.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023.day1 import net.navatwo.adventofcode2023.framework.ComputedResult import net.navatwo.adventofcode2023.framework.Solution sealed class Day1Solution : Solution<List<Day1Solution.CalibrationLine>> { data object Part1 : Day1Solution() { override fun solve(input: List<CalibrationLine>): ComputedResult { return ComputedResult.Simple(input.sumOf { parse(it.line) }) } private fun parse(line: String): Int { val mostSig = (0..line.lastIndex) .firstNotNullOf { i -> val ch = line[i] if (ch.isDigit()) ch.digitToInt() else null } val leastSig = (line.lastIndex downTo 0) .firstNotNullOf { i -> val ch = line[i] if (ch.isDigit()) ch.digitToInt() else null } return mostSig * 10 + leastSig } } data object Part2 : Day1Solution() { override fun solve(input: List<CalibrationLine>): ComputedResult { return ComputedResult.Simple(input.sumOf { parse(it.line) }) } private fun parse(line: String): Int { val mostSig = (0..line.lastIndex) .firstNotNullOf { i -> tryParseChar(line, i) } val leastSig = (line.lastIndex downTo 0) .firstNotNullOf { i -> tryParseChar(line, i) } return mostSig * 10 + leastSig } } override fun parse(lines: Sequence<String>): List<CalibrationLine> { return lines.map { CalibrationLine(it) }.toList() } @JvmInline value class CalibrationLine(val line: String) } private data class Node( var value: Int? = null, val children: MutableMap<Char, Node> = mutableMapOf(), ) { fun find(input: CharSequence): Int? { var node: Node = this for (c in input) { val nextNode = node.children[c] // null node => no child // non-null node with value => found a word if (nextNode == null || nextNode.value != null) { return nextNode?.value } node = nextNode } return node.value } } private val numbers = 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, ) private val maxNumberSize = numbers.keys.maxOf { it.length } private fun buildTrie(): Node { val rootNode = Node() for ((word, value) in numbers) { var node = rootNode for (c in word) { node = node.children.getOrPut(c) { Node() } } node.value = value } return rootNode } private val numberTrie = buildTrie() private fun tryParseChar(line: String, index: Int): Int? { val char = line[index] if (char.isDigit()) return char.digitToInt() val numberValue = line.subSequence(index, minOf(index + maxNumberSize, line.length)) return numberTrie.find(numberValue) }
0
Kotlin
0
0
4b45e663120ad7beabdd1a0f304023cc0b236255
2,788
advent-of-code-2023
MIT License
src/main/day17/day17.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day17 import Point import day17.Direction.DOWN import day17.Direction.LEFT import day17.Direction.RIGHT import findPattern import readInput import second const val leftWall = 0 const val rightWall = 6 typealias TetrisCave = MutableSet<Point> typealias TetrisRock = Set<Point> data class Jets(val jets: List<Direction>) { private var index = 0 fun next() = jets[index++ % jets.size] } enum class Direction { DOWN, LEFT, RIGHT } val fallingRocks = listOf( setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0)), setOf(Point(1, 0), Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2)), setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2)), setOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3)), setOf(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1)) ) fun main() { val input = readInput("main/day17/Day17") val heightDiffs = heightDiffs(input) val (rocksBeforePattern, patternSize) = heightDiffs.findPattern(1650) println("$rocksBeforePattern, $patternSize") println("Part1: ${solve(heightDiffs, rocksBeforePattern, patternSize, 2022)}") println("Part1: ${solve(heightDiffs, rocksBeforePattern, patternSize, 1000000000000L)}") } private fun solve(heightDiffs: List<Int>, rocksBeforePattern: Int, patternSize: Int, numberOfRocks: Long): Long { val rocksLeft = numberOfRocks - rocksBeforePattern val pattern = heightDiffs.drop(rocksBeforePattern - 1).take(patternSize) val patternSum = pattern.sum() return heightDiffs.take(rocksBeforePattern).sum() + (rocksLeft / patternSize * patternSum + pattern.take((rocksLeft - rocksLeft / patternSize * patternSize).toInt()).sum()) } fun heightDiffs(input: List<String>): List<Int> { val cave = emptyCaveWithFloor() val jets = input.first().parse() return (0..5000).map { var rock = cave.nextRock(shapeFor(it)) do { rock = cave.moveRock(rock, jets.next()).first val result = cave.moveRock(rock, DOWN) rock = result.first } while (result.second) cave.addAll(rock) cave.height() }.windowed(2).map { (it.second() - it.first()).toInt() } } private fun shapeFor(it: Int) = fallingRocks[it % fallingRocks.size] private fun emptyCaveWithFloor() = mutableSetOf( Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0), Point(4, 0), Point(5, 0), Point(6, 0), ) private fun TetrisCave.height() = maxOf { it.y }.toLong() fun TetrisCave.moveRock(rock: TetrisRock, direction: Direction): Pair<TetrisRock, Boolean> { var movedRock: TetrisRock = rock var rockMoved = false when (direction) { DOWN -> { val probedRock = rock.map { Point(it.x, it.y - 1) } if (probedRock.none { this.contains(it) }) { movedRock = probedRock.toSet() rockMoved = true } } LEFT -> { val probedRock = rock.map { Point(it.x - 1, it.y) } if (probedRock.none { this.contains(it) || it.x < leftWall }) { movedRock = probedRock.toSet() rockMoved = true } } RIGHT -> { val probedRock = rock.map { Point(it.x + 1, it.y) } if (probedRock.none { this.contains(it) || it.x > rightWall }) { movedRock = probedRock.toSet() rockMoved = true } } } return movedRock to rockMoved } fun TetrisCave.nextRock(rock: TetrisRock): TetrisRock { val xOffset = 2 val yOffset = maxOf { it.y } + 4 return rock.map { Point(it.x + xOffset, it.y + yOffset) }.toSet() } fun String.parse(): Jets = map { when (it) { '<' -> LEFT '>' -> RIGHT else -> error("illegal input") } }.let { Jets(it) }
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
3,850
aoc-2022
Apache License 2.0
src/main/kotlin/name/valery1707/problem/leet/code/RomanToIntegerK.kt
valery1707
541,970,894
false
null
package name.valery1707.problem.leet.code /** * # 13. Roman to Integer * * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. * * | Symbol | Value | * |--------|-------| * | `I` | `1` | * | `V` | `5` | * | `X` | `10` | * | `L` | `50` | * | `C` | `100` | * | `D` | `500` | * | `M` | `1000` | * * For example, `2` is written as `II` in Roman numeral, just two ones added together. * `12` is written as `XII`, which is simply `X + II`. * The number `27` is written as `XXVII`, which is `XX + V + II`. * * Roman numerals are usually written largest to smallest from left to right. * However, the numeral for four is not `IIII`. * Instead, the number four is written as `IV`. * Because the one is before the five we subtract it making four. * The same principle applies to the number nine, which is written as `IX`. * There are six instances where subtraction is used: * * `I` can be placed before `V` (`5`) and `X` (`10`) to make `4` and `9`. * * `X` can be placed before `L` (`50`) and `C` (`100`) to make `40` and `90`. * * `C` can be placed before `D` (`500`) and `M` (`1000`) to make `400` and `900`. * * Given a roman numeral, convert it to an integer. * * ### Constraints * * `1 <= s.length <= 15` * * `s` contains only the characters (`'I', 'V', 'X', 'L', 'C', 'D', 'M'`) * * It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]` * * <a href="https://leetcode.com/problems/roman-to-integer/">13. Roman to Integer</a> */ interface RomanToIntegerK { fun romanToInt(s: String): Int @Suppress("EnumEntryName", "unused") enum class Implementation : RomanToIntegerK { /** * Parse only valid values. */ maps { //Should be static private val values = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000) private val prefix = mapOf('I' to setOf('V', 'X'), 'X' to setOf('L', 'C'), 'C' to setOf('D', 'M')) override fun romanToInt(s: String): Int { val max = s.length - 1 var sum = 0 var i = 0 while (i <= max) { val c = s[i] sum += if (c in prefix && i < max && s[i + 1] in prefix[c]!!) { values[s[++i]]!! - values[c]!! } else { values[c]!! } i++ } return sum } }, /** * Logic: * * Parse valid `IV`: * * `prev == 0 && curr == 5 => sum = 0 + 5` * * `prev == 5 && curr == 1 => sum = 5 - 1` * * `sum == 4` * * Parse also invalid `IM`: * * `prev == 0 && curr == 1000 => sum = 0 + 1000` * * `prev == 1000 && curr == 1 => sum = 1000 - 1` * * `sum == 999` */ switch { override fun romanToInt(s: String): Int { var sum = 0 var prev = 0 for (i in (s.length - 1).downTo(0)) { val curr = when (s[i]) { 'I' -> 1 'V' -> 5 'X' -> 10 'L' -> 50 'C' -> 100 'D' -> 500 'M' -> 1000 else -> 0 } sum += if (curr >= prev) curr else -curr prev = curr } return sum } }, } }
3
Kotlin
0
0
76d175f36c7b968f3c674864f775257524f34414
3,662
problem-solving
MIT License
src/Day04.kt
aaronbush
571,776,335
false
{"Kotlin": 34359}
fun main() { fun String.toIntRange(): IntRange { val parts = this.split("-", limit = 2) return parts[0].toInt()..parts[1].toInt() } fun IntRange.subSetOf(other: IntRange) = this.first >= other.first && this.last <= other.last fun IntRange.overlaps(other: IntRange) = this.last >= other.first && this.first <= other.last fun loadSections(input: List<String>): List<Pair<IntRange, IntRange>> { val sectionRanges = input.map { line -> val parts = line.split(",", limit = 2) val sectionA = parts[0].toIntRange() val sectionB = parts[1].toIntRange() sectionA to sectionB } return sectionRanges } fun part1(input: List<String>): Int { val sectionRanges = loadSections(input) val sectionsContained = sectionRanges.map { it.first.subSetOf(it.second) || it.second.subSetOf(it.first) } return sectionsContained.count { it } } fun part2(input: List<String>): Int { val sectionRanges = loadSections(input) val sectionOverlaps = sectionRanges.map { it.first.overlaps(it.second) || it.second.overlaps(it.first) } return sectionOverlaps.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("p1: ${part1(input)}") println("p2: ${part2(input)}") }
0
Kotlin
0
0
d76106244dc7894967cb8ded52387bc4fcadbcde
1,569
aoc-2022-kotlin
Apache License 2.0