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/day5/Day5.kt
calvin-laurenson
572,736,307
false
{"Kotlin": 16407}
package day5 import readInput fun main() { fun parseCrateColumns(row: String): List<Char?> { return row.chunked(4).map { if (it.isBlank()) null else it[1] } } fun parseCrateColumns(rows: List<String>): Map<Int, MutableList<Char>> { return buildMap { for (row in rows) { val parsedRow = parseCrateColumns(row) println(parsedRow) parsedRow.forEachIndexed { i, c -> // println("$i, $c") if (c != null) { if (!contains(i + 1)) { put(i + 1, mutableListOf()) } // println("adding $c to ${i+1}") get(i+1)!!.add(0, c) } } } } } fun part1(input: List<String>): String { val splitIndex = input.indexOfFirst { it.isEmpty() } val startingRaw = input.slice(0 until splitIndex - 1) val labels = input[splitIndex - 1] // println("labels: $labels") val boxes: Map<Int, MutableList<Char>> = parseCrateColumns(startingRaw) println(boxes) val commands = input.takeLastWhile { it.isNotEmpty() } for (command in commands) { val (amount, from, to) = Regex("""move (\d+) from (\d+) to (\d+)""").find(command)!!.groups.toList().takeLast(3).map { it!!.value.toInt()} val fromList = boxes[from]!! val toList = boxes[to]!! val chars = fromList.takeLast(amount) chars.forEach { _ -> fromList.removeLast() } chars.reversed().forEach { toList.add(it) } } println(boxes) return boxes.toList().sortedBy { it.first }.map { it.second.last() }.joinToString("") } fun part2(input: List<String>): String { val splitIndex = input.indexOfFirst { it.isEmpty() } val startingRaw = input.slice(0 until splitIndex - 1) val labels = input[splitIndex - 1] // println("labels: $labels") val boxes: Map<Int, MutableList<Char>> = parseCrateColumns(startingRaw) println(boxes) val commands = input.takeLastWhile { it.isNotEmpty() } for (command in commands) { val (amount, from, to) = Regex("""move (\d+) from (\d+) to (\d+)""").find(command)!!.groups.toList().takeLast(3).map { it!!.value.toInt()} val fromList = boxes[from]!! val toList = boxes[to]!! val chars = fromList.takeLast(amount) chars.forEach { _ -> fromList.removeLast() } chars.forEach { toList.add(it) } } println(boxes) return boxes.toList().sortedBy { it.first }.map { it.second.last() }.joinToString("") } val testInput = readInput("day5/test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("day5/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
155cfe358908bbe2a554306d44d031707900e15a
2,990
aoc2022
Apache License 2.0
src/Day21.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
fun main() { data class Monkey(val name: String, val expr: String) fun Monkey.evaluateExpr(map: MutableMap<String, Long>): Long? { val parts = this.expr.split(" ") if (parts.size == 1) { return parts[0].toLong() } val name1 = parts.first() val name2 = parts.last() val operator = parts[1] if (operator == "=") { if (name1 in map) { map[name2] = map[name1]!! } else if (name2 in map) { map[name1] = map[name2]!! } } else { if (name1 in map && name2 in map) { val value1 = map[name1]!! val value2 = map[name2]!! return when (operator) { "+" -> value1 + value2 "-" -> value1 - value2 "*" -> value1 * value2 "/" -> value1 / value2 else -> null } } } return null } fun Monkey.variants(): List<Monkey> { val parts = this.expr.split(" ") if (parts.size == 1) { return listOf(this) } val name1 = parts.first() val name2 = parts.last() val operator = parts[1] return when (operator) { "+" -> listOf(this, Monkey(name1, "$name - $name2"), Monkey(name2, "$name - $name1")) "-" -> listOf(this, Monkey(name1, "$name + $name2"), Monkey(name2, "$name1 - $name")) "*" -> listOf(this, Monkey(name1, "$name / $name2"), Monkey(name2, "$name / $name1")) "/" -> listOf(this, Monkey(name1, "$name * $name2"), Monkey(name2, "$name1 / $name")) else -> listOf(this) } } fun List<Monkey>.calc(need: String): Long { val map = mutableMapOf<String, Long>() while (need !in map) { forEach { if (map[it.name] == null) { it.evaluateExpr(map)?.let { result -> map[it.name] = result } } } } return map[need]!! } fun part1(input: List<String>) = input.map { val (name, expr) = it.split(": ") Monkey(name, expr) } .calc("root") fun part2(input: List<String>) = input.flatMap { val (name, expr) = it.split(": ") when (name) { "root" -> Monkey(name, expr.replace("+", "=")).variants() else -> Monkey(name, expr).variants() } } .filterNot { it.name == "humn" && it.expr.split(" ").size == 1 } .calc("humn") val input = readInput("inputs/Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
2,844
aoc-2022
Apache License 2.0
src/main/kotlin/day3/Day3.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day3 class Day3 { fun getOrganizer(filename: String): RucksackOrganizer { val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines() return RucksackOrganizer(readLines) } } data class RucksackOrganizer(val input: List<String>) { val rucksacks = input.map { Rucksack(it) } val elfGroups = createElfGroups(listOf(), rucksacks) private fun createElfGroups(accumulator: List<ElfGroup>, input: List<Rucksack>): List<ElfGroup> { if (input.isEmpty()) return accumulator return createElfGroups(accumulator + ElfGroup(input.take(3)), input.drop(3)) } val part1Score = rucksacks.sumOf { it.score() } val part2Score = elfGroups.sumOf { it.score() } } data class ElfGroup(val rucksacks: List<Rucksack>) { val badge = rucksacks[0].types.intersect(rucksacks[1].types).intersect(rucksacks[2].types).first() fun score() = badge.day3Score() override fun toString(): String { return "[${rucksacks[0].input}][${rucksacks[1].input}][${rucksacks[2].input}][badge=$badge]" } } data class Rucksack(val input: String) { private val compartment1 = input.take(input.length / 2) private val compartment2 = input.takeLast(input.length / 2) private val duplicate = compartment1.toList().toSet().intersect(compartment2.toList().toSet()).first() val types = input.toList().toSet() fun score(): Int { return duplicate.day3Score() } override fun toString(): String { return "[Compartment1=$compartment1][Compartment2 = $compartment2][duplicate = $duplicate][score = ${score()}]" } } fun Char.day3Score(): Int { return if (this.isLowerCase()) { this.toInt() - 96 } else { this.toInt() - 38 } } fun main() { val rucksackOrganizerTest = Day3().getOrganizer("/day3_test.txt") val rucksackOrganizerInput = Day3().getOrganizer("/day3_input.txt") //rucksackOrganizer.rucksacks.forEach { println(it) } println("Part 1 score: ${rucksackOrganizerTest.part1Score}") println("Part 1 score: ${rucksackOrganizerInput.part1Score}") println("Part 2 score: ${rucksackOrganizerTest.part2Score}") println("Part 2 score: ${rucksackOrganizerInput.part2Score}") //println("ElfGroups: ${rucksackOrganizerTest.elfGroups}") }
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
2,326
adventofcode2022
Apache License 2.0
src/main/kotlin/io/tree/SmallestSubtreeWithAllDeepestNodes.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.tree import io.models.TreeNode import io.utils.runTests // https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/ class SmallestSubtreeWithAllDeepestNodes { fun execute(root: TreeNode?): TreeNode? = when (root) { null -> null else -> { var stack = listOf(Route(root)) while (stack.isNotEmpty()) { val nextStack = stack.flatMap { route -> route.children() } if (nextStack.isEmpty()) { break } stack = nextStack } val first = stack.first() when (stack.size) { 1 -> first.last() else -> { var index = 0 while (stack.all { index + 1 in first.nodes.indices && index + 1 in it.nodes.indices && first.nodes[index + 1].`val` == it.nodes[index + 1].`val` }) { index++ } first.nodes[index] } } } } private data class Route(val nodes: MutableList<TreeNode> = mutableListOf()) { constructor(root: TreeNode) : this(mutableListOf(root)) fun last() = nodes.last() fun add(node: TreeNode) = nodes.add(node) fun nextRight() = last().right?.let { copy(nodes = mutableListOf<TreeNode>().apply { addAll(nodes) }).apply { this.add(it) } } fun nextLeft() = last().left?.let { copy(nodes = mutableListOf<TreeNode>().apply { addAll(nodes) }).apply { this.add(it) } } fun children(): List<Route> { val nextRight = nextRight() val nextLeft = nextLeft() return when { nextLeft == null && nextRight == null -> emptyList() nextLeft == null -> listOf(nextRight!!) nextRight == null -> listOf(nextLeft) else -> listOf(nextLeft, nextRight) } } } // https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/146808/C%2B%2BJavaPython-One-Pass fun subtreeWithAllDeepest(root: TreeNode?): TreeNode? = deep(root).second private fun deep(root: TreeNode?): Pair<Int, TreeNode?> { if (root == null) return Pair(0, null) val left = deep(root.left) val right = deep(root.right) return Pair(maxOf(left.first, right.first) + 1, when { left.first == right.first -> root right.first > left.first -> left.second else -> right.second }) } } fun main() { runTests(listOf( TreeNode(3, left = TreeNode(5, left = TreeNode(6), right = TreeNode(2, TreeNode(7), TreeNode(4))), right = TreeNode(1, TreeNode(0), TreeNode(8))) to TreeNode(2, TreeNode(7), TreeNode(4)) )) { (input, value) -> value to SmallestSubtreeWithAllDeepestNodes().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,731
coding
MIT License
src/Day14.kt
buczebar
572,864,830
false
{"Kotlin": 39213}
import java.lang.Integer.max import java.lang.Integer.min private typealias Path = List<Position> private typealias MutableMatrix<T> = MutableList<MutableList<T>> private val Pair<Int, Int>.depth: Int get() = second private fun List<Path>.getMaxValue(selector: (Position) -> Int) = flatten().maxOf { selector(it) } private fun List<Path>.toFieldMatrix(): MutableMatrix<FieldType> { val maxDepth = getMaxValue { it.depth } val maxWidth = getMaxValue { it.x } val matrix = MutableList(maxDepth + 1) { MutableList(maxWidth * 2) { FieldType.AIR } } forEach { path -> path.windowed(2).forEach { (start, end) -> val xRange = min(start.x, end.x)..max(start.x, end.x) val depthRange = min(start.depth, end.depth)..max(start.depth, end.depth) for (x in xRange) { for (y in depthRange) { matrix[y][x] = FieldType.ROCK } } } } return matrix } private fun MutableList<MutableList<FieldType>>.addRow(type: FieldType) { add(MutableList(first().size) { type }) } fun main() { fun parseInput(name: String) = readInput(name) .map { line -> line.split(" -> ") .map { path -> path.split(",") .toListOfInts() .pair() } } fun simulate(fieldMatrix: MutableMatrix<FieldType>): Int { fun nextPosition(position: Position): Position? { val directionsToCheck = listOf(Position(0, 1), Position(-1, 1), Position(1, 1)) for (direction in directionsToCheck) { val newPosition = position + direction if (fieldMatrix[newPosition.depth][newPosition.x] == FieldType.AIR) { return newPosition } } return null } val maxDepth = fieldMatrix.size - 1 val sandStartPosition = Position(500, 0) var position = sandStartPosition while (position.depth < maxDepth && fieldMatrix[sandStartPosition.depth][sandStartPosition.x] == FieldType.AIR) { with(nextPosition(position)) { if (this == null) { fieldMatrix[position.depth][position.x] = FieldType.SAND position = sandStartPosition } else { position = this } } } return fieldMatrix.flatten().count { it == FieldType.SAND } } fun part1(fieldMatrix: MutableMatrix<FieldType>) = simulate(fieldMatrix) fun part2(fieldMatrix: MutableMatrix<FieldType>): Int { fieldMatrix.apply { addRow(FieldType.AIR) addRow(FieldType.ROCK) } return simulate(fieldMatrix) } val testInput = parseInput("Day14_test").toFieldMatrix() check(part1(testInput) == 24) check(part2(testInput) == 93) val input = parseInput("Day14").toFieldMatrix() println(part1(input)) println(part2(input)) } private enum class FieldType { AIR, SAND, ROCK }
0
Kotlin
0
0
cdb6fe3996ab8216e7a005e766490a2181cd4101
3,170
advent-of-code
Apache License 2.0
src/Day05.kt
hoppjan
573,053,610
false
{"Kotlin": 9256}
fun main() { val testLines = readInput("Day05_test") val testResult1 = part1(testLines) println("test part 1: $testResult1") check(testResult1 == "CMZ") val testResult2 = part2(testLines) println("test part 2: $testResult2") check(testResult2 == "MCD") val lines = readInput("Day05") println("part 1: ${part1(lines)}") println("part 2: ${part2(lines)}") } private fun part1(input: List<String>) = parsePlay(input) .let { (field, moves) -> field.toMutableList().play9000(moves).topCrates() } private fun part2(input: List<String>) = parsePlay(input) .let { (field, moves) -> field.toMutableList().play9001(moves).topCrates() } private fun parsePlay(input: List<String>): Play { val moves = input .takeLastWhile { line -> line.startsWith("move") } .map { it.toMove() } val start = input .take(input.indexOfFirst { it.isBlank() }) .dropLast(1) .rotate() .filter { it.matches(Regex("[A-Z]+ *")) } .map { it.trim() } return Play(start, moves) } private fun MutableList<String>.play9000(moves: List<Move>): List<String> { for (move in moves) { this[move.to] += this[move.from].takeLast(move.crates).reversed() this[move.from] = this[move.from].dropLast(move.crates) } return toList() } private fun MutableList<String>.play9001(moves: List<Move>): List<String> { for (move in moves) { this[move.to] += this[move.from].takeLast(move.crates) this[move.from] = this[move.from].dropLast(move.crates) } return toList() } private fun List<String>.topCrates() = buildString { for (stack in this@topCrates) append(stack.last()) } private fun String.toMove() = replace(Regex("[a-z]*"), "") .trim() .split(Regex(" +")) .let { (move, from, to) -> Move(move.toInt(), from.toInt() - 1, to.toInt() - 1) } private data class Move( val crates: Int, val from: Int, val to: Int, ) private data class Play( val field: List<String>, val moves: List<Move>, ) private fun List<String>.rotate(): List<String> = buildList { for (charIndex in 0 until this@rotate.maxOf { it.length }) add( buildString { for (lineIndex in this@rotate.indices.reversed()) append(this@rotate.getOrElse(lineIndex) { " " }.getOrElse(charIndex) { ' ' }) } ) }
0
Kotlin
0
0
f83564f50ced1658b811139498d7d64ae8a44f7e
2,417
advent-of-code-2022
Apache License 2.0
src/Day23.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day23.printSolutionIfTest(110, 20) } object Day23 : Day<Int, Int>(23) { override fun part1(lines: List<String>): Int { val map = lines.flatMapIndexed { y: Int, s: String -> s.chunked(1).mapIndexed { x, v -> Pair(Point(x, y), v) } } .toMap().toMutableMap() (1..10).forEach { round(it, map) } val elves = map.filter { (_, v) -> v == "#" }.keys val minx = elves.minOf { it.x } val miny = elves.minOf { it.y } val maxx = elves.maxOf { it.x } val maxy = elves.maxOf { it.y } val totalArea = (1 + maxx - minx) * (1 + maxy - miny) return totalArea - elves.size } override fun part2(lines: List<String>): Int { val map = lines.flatMapIndexed { y: Int, s: String -> s.chunked(1).mapIndexed { x, v -> Pair(Point(x, y), v) } } .toMap().toMutableMap() (1..Int.MAX_VALUE).forEach { if (round(it, map) == 0) return it } return -1 } data class Point(val x: Int, val y: Int) data class Move(val from: Point, val to: Point) enum class Direction(val x: Int, val y: Int) { N(0, -1), NE(1, -1), E(1, 0), SE(1, 1), S(0, 1), SW(-1, 1), W(-1, 0), NW(-1, -1); fun apply(from: Point) = Point(from.x + x, from.y + y) companion object { private val directions = listOf(listOf(N, NE, NW), listOf(S, SE, SW), listOf(W, NW, SW), listOf(E, NE, SE)) fun directionsForRound(round: Int) = (round..round + 3).map { directions[it % 4] } } } private fun round(num: Int, map: MutableMap<Point, String>): Int { val moves = mutableListOf<Move>() val alreadyProposed = mutableListOf<Point>() map.filter { (_, v) -> v == "#" }.forEach { (k, _) -> if (Direction.values().any { d -> (map[d.apply(k)] ?: ".") == "#" }) { Direction.directionsForRound(num - 1).firstOrNull { d -> d.all { (map[it.apply(k)] ?: ".") == "." } }?.get(0)?.apply(k)?.let { if (!alreadyProposed.contains(it)) { moves.add(Move(from = k, to = it)) alreadyProposed.add(it) } else { moves.removeIf { (_, to) -> to == it } } } } } moves.forEach { (from, to) -> map[from] = "." map[to] = "#" } return moves.size } }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
2,549
advent-of-code-2022
Apache License 2.0
src/Day23.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
fun main() { data class P(val x: Int, val y: Int) { operator fun plus(p: P) = P(x + p.x, y + p.y) } class Move(val check: List<P>, val move: P, val bit: Int) val n = P(0, -1) val s = P(0, 1) val w = P(-1, 0) val e = P(1, 0) val allDirections = listOf( n, n + e, e, s + e, s, s + w, w, n + w, ) val movesMask = 0b1111 val elfBit = 0b10000 val bitMeanings = Array(16) { P(0, 0) }.apply { set(0b0001, s) set(0b0010, n) set(0b0100, e) set(0b1000, w) } val moves = listOf( Move(listOf(n, n + e, n + w), n, 0b0001), Move(listOf(s, s + e, s + w), s, 0b0010), Move(listOf(w, n + w, s + w), w, 0b0100), Move(listOf(e, n + e, s + e), e, 0b1000), ) fun parse( input: List<String>, iterations: Int ): List<IntArray> { val width = input[0].length val height = input.size val map = List(height + iterations * 2) { y -> IntArray(width + iterations * 2) { x -> if (input.getOrNull(y - iterations)?.getOrNull(x - iterations) == '#') { elfBit } else { 0 } } } return map } fun part1(input: List<String>): Int { val iterations = 10 val map = parse(input, iterations) for (i in 0 until iterations) { for (y in map.indices) { for (x in map[y].indices) { if (map[y][x] and elfBit == 0) continue if (allDirections.all { (dx, dy) -> map[y + dy][x + dx] != elfBit }) continue for (moveIndex in moves.indices) { val move = moves[(moveIndex + i) % moves.size] if (move.check.all { (dx, dy) -> map[y + dy][x + dx] != elfBit }) { val (dx, dy) = move.move map[y + dy][x + dx] = map[y + dy][x + dx] or move.bit break } } } } for (y in map.indices) { for (x in map[y].indices) { val value = map[y][x] if (value and movesMask == 0) continue if (value.countOneBits() == 1) { val (dx, dy) = bitMeanings[value] map[y + dy][x + dx] = 0 map[y][x] = elfBit } else { map[y][x] = 0 } } } } val elfCount = input.sumOf { it.count { c -> c == '#' } } val yMin = map.indexOfFirst { it.contains(elfBit) } val yMax = map.indexOfLast { it.contains(elfBit) } val xMin = map[0].indices.indexOfFirst { x -> map.any { it[x] == elfBit } } val xMax = map[0].indices.indexOfLast { x -> map.any { it[x] == elfBit } } return (yMax - yMin + 1) * (xMax - xMin + 1) - elfCount } fun part2(input: List<String>, maxIterations: Int): Int { val offset = P(maxIterations, maxIterations) val elves = mutableSetOf<P>() for (y in input.indices) { for (x in input[y].indices) { if (input[y][x] == '#') elves += P(x, y) + offset } } val map = parse(input, maxIterations) val proposed = mutableSetOf<P>() for (i in 0 until maxIterations) { var hasMoved = false proposed.clear() for ((x, y) in elves) { if (map[y][x] and elfBit == 0) throw IllegalStateException("wrong elf location") if (allDirections.all { (dx, dy) -> map[y + dy][x + dx] != elfBit }) continue for (moveIndex in moves.indices) { val move = moves[(moveIndex + i) % moves.size] if (move.check.all { (dx, dy) -> map[y + dy][x + dx] != elfBit }) { val (dx, dy) = move.move map[y + dy][x + dx] = map[y + dy][x + dx] or move.bit proposed += P(x + dx, y + dy) break } } } for ((x, y) in proposed) { val value = map[y][x] if (value and movesMask == 0) continue if (value.countOneBits() == 1) { val (dx, dy) = bitMeanings[value] map[y + dy][x + dx] = 0 elves -= P(x + dx, y + dy) map[y][x] = elfBit elves += P(x, y) hasMoved = true } else { map[y][x] = 0 } } if (!hasMoved) return i + 1 } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day23_test") check(part1(testInput) == 110) check(part2(testInput, 20) == 20) val input = readInput("Day23") println(part1(input)) println(part2(input, 10000)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
5,199
AdventOfCode2022
Apache License 2.0
src/day16/puzzle16.kt
brendencapps
572,821,792
false
{"Kotlin": 70597}
package day16 import Puzzle import PuzzleInput import java.io.File import kotlin.math.max fun day16Puzzle() { Day16PuzzleSolution().solve(Day16PuzzleInput("inputs/day16/example.txt",1651)) Day16PuzzleSolution().solve(Day16PuzzleInput("inputs/day16/input.txt", 1862)) Day16Puzzle2Solution().solve(Day16PuzzleInput("inputs/day16/example.txt", 1707)) Day16Puzzle2Solution().solve(Day16PuzzleInput("inputs/day16/input.txt", 2422)) } class Day16PuzzleInput(val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) { private val regex = "Valve (\\S*) has flow rate=(\\d*); tunnel(s?) lead(s?) to valve(s?) (.*)".toRegex() private val valveList = File(input).readLines().map { line -> val (valve, flow, _, _, _, connected) = regex.find(line)?.destructured ?: error("Error with $line") Valve(valve, flow.toInt(), connected.split(", ")) } init { valveList.forEach{ valve -> valve.connectedValves.addAll(valveList.filter { v -> valve.connectedValvesInput.contains(v.name) })} } fun findMaxFlow(): Int { val initial = valveList.first { it.name == "AA"} val initialNode = Node(initial, 30, listOf(), valveList.filter { it.flowRate > 0 }, 0, 0) var currentNodes = listOf(initialNode) for(i in 1 .. 30) { currentNodes = currentNodes.flatMap { getNextNodes(it) } val maxFlow = currentNodes.maxOf{ it.flow * (it.minutesLeft-1) + it.totalFlow } currentNodes = currentNodes.filter { it.maxPotential() >= maxFlow }.distinctBy { it.valve.name + "_" + it.flow + "_" + it.totalFlow } } return currentNodes.maxOf { it.totalFlow } } fun findMaxFlow2(): Int { val initial = valveList.first { it.name == "AA"} val initialNode = Node2(initial, initial, 26, listOf(), valveList.filter { it.flowRate > 0 }, 0, 0) var currentNodes = listOf(initialNode) for(i in 1 .. 26) { currentNodes = currentNodes.flatMap { getNextNodes(it) } val maxFlow = currentNodes.maxOf{ it.flow * (it.minutesLeft-1) + it.totalFlow } currentNodes = currentNodes.filter { it.maxPotential() >= maxFlow }.distinctBy { it.myValve.name + "_" + it.elephantValve.name + "_" + it.flow + "_" + it.totalFlow } } return currentNodes.maxOf { it.totalFlow } } private fun getNextNodes(node: Node2): List<Node2> { val nextNodes = mutableListOf<Node2>() if(node.closedValves.isEmpty()) { return listOf( Node2( node.myValve, node.elephantValve, node.minutesLeft - 1, node.openValves, node.closedValves, node.flow, node.totalFlow + node.flow) ) } val canOpenMyValve = node.myValve.flowRate > 0 && node.closedValves.any { it == node.myValve} val canOpenElephantValve = node.elephantValve.flowRate > 0 && node.closedValves.any { it == node.elephantValve} if(canOpenMyValve || canOpenElephantValve) { if(node.myValve != node.elephantValve && canOpenMyValve && canOpenElephantValve) { nextNodes.add( Node2( node.myValve, node.elephantValve, node.minutesLeft - 1, node.openValves + node.myValve + node.elephantValve, node.closedValves.filter { it != node.myValve && it != node.elephantValve }, node.flow + node.myValve.flowRate + node.elephantValve.flowRate, node.totalFlow + node.flow ) ) } if(canOpenMyValve) { node.elephantValve.connectedValves.forEach { connectedValve -> nextNodes.add( Node2( node.myValve, connectedValve, node.minutesLeft - 1, node.openValves + node.myValve, node.closedValves.filter { it != node.myValve }, node.flow + node.myValve.flowRate, node.totalFlow + node.flow ) ) } if(node.closedValves.all { it.flowRate <= node.myValve.flowRate }) { return nextNodes } } if(node.myValve != node.elephantValve && canOpenElephantValve) { node.myValve.connectedValves.forEach { connectedValve -> nextNodes.add( Node2( node.elephantValve, connectedValve, node.minutesLeft - 1, node.openValves + node.elephantValve, node.closedValves.filter { it != node.elephantValve }, node.flow + node.elephantValve.flowRate, node.totalFlow + node.flow ) ) } if(node.closedValves.all { it.flowRate <= node.elephantValve.flowRate }) { return nextNodes } } } node.myValve.connectedValves.forEach { myConnectedValve -> node.elephantValve.connectedValves.forEach { elephantConnectedValve -> nextNodes.add( Node2( myConnectedValve, elephantConnectedValve, node.minutesLeft - 1, node.openValves, node.closedValves, node.flow, node.totalFlow + node.flow ) ) } } return nextNodes } private fun getNextNodes(node: Node): List<Node> { val nextNodes = mutableListOf<Node>() if(node.closedValves.isEmpty()) { return listOf( Node( node.valve, node.minutesLeft - 1, node.openValves, node.closedValves, node.flow, node.totalFlow + node.flow) ) } if(node.valve.flowRate > 0 && node.closedValves.any { it == node.valve}) { nextNodes.add( Node( node.valve, node.minutesLeft - 1, node.openValves + node.valve, node.closedValves.filter { it != node.valve}, node.flow + node.valve.flowRate, node.totalFlow + node.flow)) if(node.closedValves.all { it.flowRate <= node.valve.flowRate }) { return nextNodes } } node.valve.connectedValves.forEach { connectedValve -> nextNodes.add( Node( connectedValve, node.minutesLeft - 1, node.openValves, node.closedValves, node.flow, node.totalFlow + node.flow)) } return nextNodes } } data class Valve(val name: String, val flowRate: Int, val connectedValvesInput: List<String>) { val connectedValves = mutableListOf<Valve>() } class Node(val valve: Valve, val minutesLeft: Int, val openValves: List<Valve>, val closedValves: List<Valve>, val flow: Int, val totalFlow: Int) { fun maxPotential(): Int { val remainingFlow = flow * (minutesLeft - 1) + totalFlow return remainingFlow + closedValves.mapIndexed { index, v -> v.flowRate * max(0, (minutesLeft - index * 2)) }.sum() } } class Node2(val myValve: Valve, val elephantValve: Valve, val minutesLeft: Int, val openValves: List<Valve>, val closedValves: List<Valve>, val flow: Int, val totalFlow: Int) { fun maxPotential(): Int { val remainingFlow = flow * (minutesLeft - 1) + totalFlow return remainingFlow + closedValves.mapIndexed { index, v -> v.flowRate * max(0, (minutesLeft - index * 2)) }.sum() } } class Day16PuzzleSolution : Puzzle<Int, Day16PuzzleInput>() { override fun solution(input: Day16PuzzleInput): Int { return input.findMaxFlow() } } class Day16Puzzle2Solution : Puzzle<Int, Day16PuzzleInput>() { override fun solution(input: Day16PuzzleInput): Int { return input.findMaxFlow2() } }
0
Kotlin
0
0
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
8,734
aoc_2022
Apache License 2.0
src/main/kotlin/y2023/day03/Day03.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2023.day03 import Coord import Coordinated import Matrix import MatrixUtils import MatrixUtils.filterMatrixElement import MatrixUtils.move fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } data class Field( val digit: Int?, val isPartNumberIndicator: Boolean, val isPotentialGear: Boolean, var counted: Boolean = false ) fun input(): Matrix<Coordinated<Field>> = MatrixUtils.createMatrix(AoCGenerics.getInputLines("/y2023/day03/input.txt")) { y, row -> row.mapIndexed { x, char -> Coordinated( coord = Coord(x, y), data = Field( digit = if (char.isDigit()) char.digitToInt() else null, isPartNumberIndicator = !char.isDigit() && char != '.', isPotentialGear = char == '*' ) ) } } fun getNumberFromDigitAndMarkCounted(board: Matrix<Coordinated<Field>>, digitField: Coordinated<Field>): Int { var numberString = "" // search digits to the left var curField: Coordinated<Field>? = digitField while (curField?.data?.digit != null && !curField.data.counted) { numberString = "${curField.data.digit}$numberString" curField.data.counted = true curField = board.move(curField, MatrixUtils.SimpleDirection.LEFT) } // search digits to the right curField = board.move(digitField, MatrixUtils.SimpleDirection.RIGHT) while (curField?.data?.digit != null && !curField.data.counted) { numberString = "$numberString${curField.data.digit}" curField.data.counted = true curField = board.move(curField, MatrixUtils.SimpleDirection.RIGHT) } return if (numberString == "") 0 else numberString.toInt() } fun part1(): Int { val board = input() return board.filterMatrixElement { it.data.isPartNumberIndicator } .map { symbolField -> val adjacentFields = MatrixUtils.AdvancedDirection.values().mapNotNull { direction -> board.move(symbolField, direction) } adjacentFields.filter { it.data.digit != null } } .flatten() .sumOf { getNumberFromDigitAndMarkCounted(board, it) } } fun part2(): Int { val input = input() return input.filterMatrixElement { it.data.isPotentialGear } .sumOf { potentialGear -> val adjacentNumbers = MatrixUtils.AdvancedDirection.values() .mapNotNull { input.move(potentialGear, it) } // All adjacent fields .filter { it.data.digit != null } // All adjacent digit fields .map { getNumberFromDigitAndMarkCounted(input, it) } // All adjacent numbers, including 0 for duplicates .filter { it != 0 } // just adjacent numbers if (adjacentNumbers.size == 2) { adjacentNumbers[0] * adjacentNumbers[1] } else 0 } }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
3,007
AdventOfCode
MIT License
src/main/kotlin/Day13.kt
vw-anton
574,945,231
false
{"Kotlin": 33295}
import com.beust.klaxon.JsonArray import com.beust.klaxon.Parser import java.lang.StringBuilder fun main() { fun part1(input: List<String>) { val packets = input .splitBy { it.isEmpty() } .map { it.toPair() } .map { parse(it.first) to parse(it.second) } val sum = packets .mapIndexed { index, pair -> index + 1 to isInRightOrder(pair.first, pair.second) } .filter { it.second == -1 } .sumOf { it.first } println("part 1: $sum") } fun part2(input: List<String>) { val markers = listOf( parse("[[2]]"), parse("[[6]]") ) val packets = input .filter { it.isNotEmpty() } .map { parse(it) } .toMutableList() packets += markers packets.sortWith(PackageComparator()) val result = packets .mapIndexed { index, jsonArray -> when { markers.contains(jsonArray) -> index + 1 else -> 0 } } .filter { it != 0 } .fold(1) { acc, i -> acc * i } println("part 2: $result") } val file = readFile("input/13.txt") part1(file) part2(file) } private class PackageComparator() : Comparator<Any> { override fun compare(lhs: Any?, rhs: Any?): Int { return isInRightOrder(lhs, rhs) } } private fun parse(input: String): JsonArray<*> = Parser.default().parse(StringBuilder(input)) as JsonArray<*> fun isInRightOrder(left: Any?, right: Any?): Int { return when { left is Int && right is Int -> { when { left < right -> -1 left == right -> 0 left > right -> 1 else -> -1 } } left is Int && right is JsonArray<*> -> isInRightOrder(JsonArray(left), right) left is JsonArray<*> && right is Int -> isInRightOrder(left, JsonArray(right)) left is JsonArray<*> && right is JsonArray<*> -> { var index = 0 while (index < left.size && index < right.size) { val result = isInRightOrder(left[index], right[index]) if (result != 0) return result index++ } return if (left.size < right.size) -1 else if (left.size == right.size) 0 else 1 } else -> error("what happened") } }
0
Kotlin
0
0
a823cb9e1677b6285bc47fcf44f523e1483a0143
2,576
aoc2022
The Unlicense
src/Day02.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
private fun games(): List<RPS> = readInput("Day02").map { RPS(it[0] - 'A', it[2] - 'X') } private fun games2(): List<RPS2> = readInput("Day02").map { RPS2(it[0] - 'A', it[2] - 'X') } private fun part1(games: List<RPS>): Int { return games.sumOf { it.gamePts() + it.shapePts() } } private fun part2(games: List<RPS2>): Int { return games.sumOf { it.gamePts() + it.shapePts() } } fun main() { println(part1(games())) println(part2(games2())) } data class RPS(val opp: Int, val me: Int) { fun gamePts(): Int = (me - opp + 1).mod(3) * 3 fun shapePts(): Int = me + 1 } data class RPS2(val opp: Int, val res: Int) { fun gamePts(): Int = 3 * res fun shapePts(): Int = (opp + res - 1).mod(3) + 1 }
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
729
advent-of-code-2022
Apache License 2.0
src/Day02.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
enum class Shape { ROCK, PAPER, SCISSORS } enum class Outcome { LOSE, DRAW, WIN } fun main() { val shapes = mapOf( "A" to Shape.ROCK, "B" to Shape.PAPER, "C" to Shape.SCISSORS, "X" to Shape.ROCK, "Y" to Shape.PAPER, "Z" to Shape.SCISSORS) val shapesList = listOf(Shape.ROCK, Shape.PAPER, Shape.SCISSORS) val outcomes = mapOf( "X" to Outcome.LOSE, "Y" to Outcome.DRAW, "Z" to Outcome.WIN ) fun parseInputPart1(input: List<List<String>>): List<Pair<Shape, Shape>> { return input.map{round -> Pair(shapes[round.first()]!!, shapes[round.last()]!!)} } fun parseInputPart2(input:List<List<String>>): List<Pair<Shape, Outcome>> { return input.map{round -> Pair(shapes[round.first()]!!, outcomes[round.last()]!!)} } fun getOutcome(opponent: Shape, ownShape: Shape): Outcome { val opponentIndex = shapesList.indexOf(opponent) val ownShapeIndex = shapesList.indexOf(ownShape) // There is a relation between the relative index of the shapes and the outcome return when (ownShapeIndex - opponentIndex) { -1,2 -> Outcome.LOSE 0 -> Outcome.DRAW else -> Outcome.WIN } } fun getShape(opponent: Shape, outcome:Outcome): Shape{ val opponentIndex = shapesList.indexOf(opponent) // There is a relation between the relative index of the shapes and the outcome return when (outcome) { Outcome.LOSE -> if (opponentIndex - 1 >= 0) shapesList[opponentIndex - 1] else shapesList.last() Outcome.DRAW -> shapesList[opponentIndex] Outcome.WIN -> if (opponentIndex + 1 < shapesList.size) shapesList[opponentIndex + 1] else shapesList.first() } } fun calculateScoreOutcome(outcome: Outcome): Int { return when(outcome) { Outcome.LOSE -> 0 Outcome.DRAW -> 3 Outcome.WIN -> 6 } } fun calculateScoreShape(ownShape: Shape): Int{ return when(ownShape) { Shape.ROCK -> 1 Shape.PAPER -> 2 else -> 3 } } fun part1(input: List<List<String>>): Int { val readableInput = parseInputPart1(input) var sum = 0 for (line in readableInput) { val opponent = line.first val ownShape = line.second val outcome = getOutcome(opponent, ownShape) sum += calculateScoreShape(ownShape) sum += calculateScoreOutcome(outcome) } return sum } fun part2(input: List<List<String>>): Int { val readableInput = parseInputPart2(input) var sum = 0 for (line in readableInput) { val opponent = line.first val outcome = line.second val ownShape = getShape(opponent, outcome) sum += calculateScoreShape(ownShape) sum += calculateScoreOutcome(outcome) } return sum } val input = readInputAsStrings("Day02") .map{it.split(" ")} println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
3,158
AoC2022
Apache License 2.0
aoc2023/day12.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day12.execute() } private object Day12 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<SpringStatus>): Long = input .sumOf { it.calculatePossibilities() } private fun part2(input: List<SpringStatus>, numberOfFolds: Int = 5): Long = input .map { SpringStatus(List(numberOfFolds) { _ -> it.springs }.joinToString("?"), List(numberOfFolds) { _ -> it.damagedGroups }.flatten()) } .sumOf { it.calculatePossibilities() } private fun readInput(): List<SpringStatus> = InputRetrieval.getFile(2023, 12) .readLines() .map { SpringStatus.parse(it) } private data class SpringStatus(val springs: String, val damagedGroups: List<Int>, val knownDamagedIndex: List<Int> = springs.indices.filter { springs[it] == '#' }) { private val cache = mutableMapOf<String, Long>() fun calculatePossibilities(index: Int = 0, damagedGroupIndex: Int = 0): Long { val cacheKey = "$damagedGroupIndex-$index" cache[cacheKey]?.let { return it } // Reached the end of the String, validate if valid if (index >= springs.length) { return if (damagedGroupIndex >= damagedGroups.size) 1L else 0L } // Reached the end of the Damaged Groups, validate if all remaining are working if (damagedGroupIndex >= damagedGroups.size) { return if (this.springs.drop(index).any { it == '#' }) 0L else 1L } // Test the scenario where it is damaged val expectedDamaged = damagedGroups[damagedGroupIndex] val remainingSlots = springs.length - index val possibilitiesIfDamaged = if ( this.springs[index] != '.' && expectedDamaged <= remainingSlots && !this.springs.substring(index..<(index + expectedDamaged)).any { it == '.' } && !(remainingSlots != expectedDamaged && this.springs[index + expectedDamaged] == '#') ) { calculatePossibilities(index + expectedDamaged + 1, damagedGroupIndex + 1) } else { 0L } // Test the scenario where it is operational val possibilitiesIfWorking = if (this.springs[index] != '#') { this.calculatePossibilities(index + 1, damagedGroupIndex) } else { 0L } return (possibilitiesIfWorking + possibilitiesIfDamaged) .also { cache[cacheKey] = it } } companion object { fun parse(input: String): SpringStatus { val (gears, groups) = input.split(' ') return SpringStatus(gears, groups.split(',').map { it.toInt() }) } } } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,970
Advent-Of-Code
MIT License
src/main/kotlin/aoc/year2021/Day05.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2021 import aoc.Puzzle import kotlin.math.max import kotlin.math.min /** * [Day 5 - Advent of Code 2021](https://adventofcode.com/2021/day/5) */ object Day05 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int { val map = hashMapOf<Pair<Int, Int>, Int>() input.lineSequence() .flatMap { line -> val (x1, y1, x2, y2) = line.split(" -> ", limit = 2) .flatMap { it.split(",", limit = 2).map(String::toInt) } when { x1 == x2 -> (min(y1, y2)..max(y1, y2)).map { x1 to it } y1 == y2 -> (min(x1, x2)..max(x1, x2)).map { it to y1 } else -> emptyList() } } .forEach { map.compute(it) { _, old -> (old ?: 0) + 1 } } return map.count { (_, count) -> count >= 2 } } override fun solvePartTwo(input: String): Int { val map = hashMapOf<Pair<Int, Int>, Int>() input.lineSequence() .flatMap { line -> val (x1, y1, x2, y2) = line.split(" -> ", limit = 2) .flatMap { it.split(",", limit = 2).map(String::toInt) } when { x1 == x2 -> (min(y1, y2)..max(y1, y2)).map { x1 to it } y1 == y2 -> (min(x1, x2)..max(x1, x2)).map { it to y1 } else -> { val xRange = if (x1 < x2) x1..x2 else x1 downTo x2 val yRange = if (y1 < y2) y1..y2 else y1 downTo y2 xRange zip yRange } } } .forEach { map.compute(it) { _, old -> (old ?: 0) + 1 } } return map.count { (_, count) -> count >= 2 } } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,782
advent-of-code
Apache License 2.0
src/Day02.kt
timlam9
573,013,707
false
{"Kotlin": 9410}
fun main() { fun parseStrategyGuide(input: List<String>) = input.map { line -> line.split(" ") .run { this[0].first() to this[1].first() } } fun part1(input: List<String>): Int = parseStrategyGuide(input) .fold(0) { totalScore, (elf, player) -> val elfGameSign = elf.toGameSign() val playerGameSign = player.toGameSign() val status = playerGameSign.calculateGameStatus(elfGameSign) totalScore + playerGameSign.value + status.value } fun part2(input: List<String>): Int = parseStrategyGuide(input) .fold(0) { totalScore, (elf, player) -> val elfGameSign = elf.toGameSign() val gameStatus = player.toGameStatus() val playerGameSign = gameStatus.calculatePlayerSign(elfGameSign) totalScore + playerGameSign.value + gameStatus.value } val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun GameStatus.calculatePlayerSign(elfGameSign: GameSigns): GameSigns { return when (this) { GameStatus.WIN -> elfGameSign.advantage() GameStatus.DRAW -> elfGameSign GameStatus.DEFEAT -> elfGameSign.disadvantage() } } private fun Char.toGameStatus(): GameStatus = when (this) { 'X' -> GameStatus.DEFEAT 'Y' -> GameStatus.DRAW else -> GameStatus.WIN } private fun Char.toGameSign(): GameSigns = GameSigns.values().first { it.elf == this || it.player == this } enum class GameSigns(val elf: Char, val player: Char, val value: Int) { ROCK(elf = 'A', player = 'X', value = 1), PAPER(elf = 'B', player = 'Y', value = 2), SCISSOR(elf = 'C', player = 'Z', value = 3); fun advantage(): GameSigns = values().first { it.value - this.value == 1 || it.value - this.value == -2 } fun disadvantage(): GameSigns = values().first { it.value - this.value == -1 || it.value - this.value == 2 } } enum class GameStatus(val value: Int) { WIN(6), DRAW(3), DEFEAT(0) } fun GameSigns.calculateGameStatus(elfSign: GameSigns): GameStatus = when { value - elfSign.value == 1 || value - elfSign.value == -2 -> GameStatus.WIN value == elfSign.value -> GameStatus.DRAW else -> GameStatus.DEFEAT }
0
Kotlin
0
0
7971bea39439b363f230a44e252c7b9f05a9b764
2,278
aoc-2022
Apache License 2.0
src/main/kotlin/Day8.kt
ueneid
575,213,613
false
null
import kotlin.math.max class Day8(inputs: List<String>) { private val treeGrid = parse(inputs) private fun parse(inputs: List<String>): List<List<Int>> { return inputs.map { it.toList().map { height -> height.digitToInt() } } } private fun isVisible(input: List<List<Int>>, i: Int, j: Int): Boolean { return input[i].slice(0 until j).all { it < input[i][j] } || input[i].slice(j + 1 until input[i].size).all { it < input[i][j] } } private fun calcScenicScore(input: List<List<Int>>, i: Int, j: Int): Int { return listOf(j - 1 downTo 0, j + 1 until input[i].size).fold(1) { acc, range -> var c = 0 for (el in input[i].slice(range)) { c++ if (el >= input[i][j]) { break } } acc * c } } fun solve1(): Int { val transposedGrid = treeGrid.transpose() var count = treeGrid.size * treeGrid[0].size for (i in 1 until treeGrid.size - 1) { for (j in 1 until treeGrid[i].size - 1) { if (!isVisible(treeGrid, i, j) && !isVisible(transposedGrid, j, i)) { count -= 1 } } } return count } fun solve2(): Int { val transposedGrid = treeGrid.transpose() var maxScore = 0 for (i in 1 until treeGrid.size - 1) { for (j in 1 until treeGrid[i].size - 1) { maxScore = max(maxScore, calcScenicScore(treeGrid, i, j) * calcScenicScore(transposedGrid, j, i)) } } return maxScore } } fun main() { val obj = Day8(Resource.resourceAsListOfString("day8/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
1,804
adventcode2022
MIT License
2023/src/main/kotlin/Day07.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day07 { private enum class HandType { FIVE_OF_A_KIND, FOUR_OF_A_KIND, FULL_HOUSE, THREE_OF_A_KIND, TWO_PAIR, ONE_PAIR, HIGH_CARD; } private val cardStrengths = listOf( 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2' ).withIndex().associate { it.value to it.index } private val cardStrengthsAlt = listOf( 'A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J' ).withIndex().associate { it.value to it.index } private data class HandAndBid(val hand: Hand, val bid: Int) private data class Hand(val cards: String) { val handType = calculateHandType(cards) val handTypeAlt = calculateHandTypeWithJokers(cards) } private fun generateHandSelectors(useAlt: Boolean): Array<(Hand) -> Comparable<*>?> { val typeSelector = if (useAlt) { hand: Hand -> hand.handTypeAlt } else { hand: Hand -> hand.handType } val cardStrengths = if (useAlt) cardStrengthsAlt else cardStrengths val cardSelectors = (0..4).map<Int, (Hand) -> Int?> { index -> { hand -> cardStrengths[hand.cards[index]] } } return (listOf(typeSelector) + cardSelectors).toTypedArray() } private val cardSelectors = generateHandSelectors(false) private val cardSelectorsAlt = generateHandSelectors(true) private val handComparator = Comparator<HandAndBid> { h1, h2 -> compareValuesBy(h1.hand, h2.hand, *cardSelectors) } private val handComparatorAlt = Comparator<HandAndBid> { h1, h2 -> compareValuesBy(h1.hand, h2.hand, *cardSelectorsAlt) } fun part1(input: String) = solve(input, handComparator) fun part2(input: String) = solve(input, handComparatorAlt) private fun solve(input: String, comparator: Comparator<HandAndBid>): Int { return parseInput(input) .sortedWith(comparator) .asReversed() .map { it.bid } .withIndex() .sumOf { (index, bid) -> (index + 1) * bid } } private fun calculateHandTypeWithJokers(cards: String): HandType { return if (cards.none { it == 'J' }) { calculateHandType(cards) } else { cards .toCharArray() .distinct() .map { type -> calculateHandType(cards.replace('J', type)) } .minOf { it } } } private fun calculateHandType(cards: String): HandType { val cardCounts = cards.groupBy { it }.mapValues { it.value.size } if (cardCounts.containsValue(5)) { return HandType.FIVE_OF_A_KIND } if (cardCounts.containsValue(4)) { return HandType.FOUR_OF_A_KIND } if (cardCounts.containsValue(3)) { return if (cardCounts.containsValue(2)) HandType.FULL_HOUSE else HandType.THREE_OF_A_KIND } return when (cardCounts.count { it.value == 2 }) { 2 -> HandType.TWO_PAIR 1 -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } private fun parseInput(input: String): List<HandAndBid> { return input.splitNewlines().map { val (cards, bid) = it.splitWhitespace() return@map HandAndBid(Hand(cards), bid.toInt()) } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
3,030
advent-of-code
MIT License
src/main/kotlin/Day12.kt
ueneid
575,213,613
false
null
import java.util.* import kotlin.collections.ArrayDeque import kotlin.collections.set typealias Cell = Pair<Int, Int> class Day12(inputs: List<String>) { companion object { private val offsets = listOf<Pair<Int, Int>>( Pair(0, 1), Pair(0, -1), Pair(1, 0), Pair(-1, 0) ) private var charValue = ('a'..'z').toList().associateWith { (it - 96).code } } private val matrix = parse(inputs) private val height = matrix.size private val width = matrix[0].size private lateinit var sPos: Cell private lateinit var ePos: Cell private fun parse(inputs: List<String>): List<List<Char>> { val matrix = inputs.mapIndexed { y, line -> line.toList().mapIndexed { x, c -> when (c) { 'S' -> { sPos = Pair(x, y) 'a' } 'E' -> { ePos = Pair(x, y) 'z' } else -> c } } } return matrix } private fun getAdjacentCells(cell: Cell, visited: Map<Cell, Int>): List<Cell> { return offsets .asSequence() .map { Pair(cell.first + it.first, cell.second + it.second) } .filter { (nextX, nextY) -> nextY in 0 until height && nextX in 0 until width } .filter { !visited.contains(it) } .filter { (nextX, nextY) -> charValue[matrix[nextY][nextX]]!! <= charValue[matrix[cell.second][cell.first]]!! + 1 }.toList() } private fun calcMinStep(start: Cell): Int { val q = ArrayDeque(listOf(start)) val visited = mutableMapOf<Cell, Int>(start to 0) while (q.isNotEmpty()) { val cur = q.removeFirst() if (cur == ePos) { break } getAdjacentCells(cur, visited).forEach { visited[it] = visited.getOrDefault(cur, 0) + 1 q.addLast(it) } } return visited.getOrDefault(ePos, Int.MAX_VALUE) } fun solve1(): Int { return calcMinStep(sPos) } private fun findA(): List<Cell> { return matrix .asSequence() .flatMapIndexed { y, chars -> chars .mapIndexed { x, c -> Pair(Cell(x, y), c) } .filter { it.second == 'a' } .map { it.first } }.toList() } fun solve2(): Int { val buf = PriorityQueue<Int>() findA().asSequence().forEach { buf.add(calcMinStep(it)) } return buf.poll() } } fun main() { val obj = Day12(Resource.resourceAsListOfString("day12/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
2,854
adventcode2022
MIT License
src/Day04.kt
muellerml
573,601,715
false
{"Kotlin": 14872}
fun main() { fun part1(input: List<String>): Int { return input.count { line -> val (leftRange, rightRange) = line.split(",").map { Range(it) } if (leftRange.total() > rightRange.total()) { leftRange.max >= rightRange.max && leftRange.min <= rightRange.min } else { rightRange.max >= leftRange.max && rightRange.min <= leftRange.min } } } fun part2(input: List<String>): Int { return input.count { line -> val (leftRange, rightRange) = line.split(",").map { Range(it) } (leftRange.max >= rightRange.min && leftRange.max <= rightRange.max) || (rightRange.max >= leftRange.min && rightRange.max <= leftRange.max) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day04_test") val result = part1(testInput) check(result == 2) val input = readInput("day04") println("Part1: " + part1(input)) val result2 = part2(testInput) println(result2) check(result2 == 4) println("Part2: " + part2(input)) } data class Range(val min: Int, val max: Int) { constructor(rangeString: String): this(rangeString.substringBefore("-").toInt(), rangeString.substringAfter("-").toInt()) fun total() = max - min }
0
Kotlin
0
0
028ae0751d041491009ed361962962a64f18e7ab
1,350
aoc-2022
Apache License 2.0
src/Day02.kt
mborromeo
571,999,097
false
{"Kotlin": 10600}
fun main() { val pointsPerShape = mapOf( "X" to 1, "Y" to 2, "Z" to 3 ) fun part1(input: List<String>): Int { val pointsPerOutcome = mapOf( "AX" to 3, "BY" to 3, "CZ" to 3, "AY" to 6, "BZ" to 6, "CX" to 6 ) return input.sumOf { it -> it.split(' ').let { pointsPerShape.getOrDefault(it[1], 0) + pointsPerOutcome.getOrDefault(it[0] + it[1], 0) } } } fun part2(input: List<String>): Int { val selectShape = mapOf( "X" to mapOf( "A" to "Z", "B" to "X", "C" to "Y" ), "Y" to mapOf( "A" to "X", "B" to "Y", "C" to "Z" ), "Z" to mapOf( "A" to "Y", "B" to "Z", "C" to "X" ) ) val pointsPerRiggedOutcome = mapOf( "Y" to 3, "Z" to 6 ) return input.sumOf { it -> it.split(' ').let { pointsPerShape.getOrDefault(selectShape.getOrDefault(it[1], mapOf()).getOrDefault(it[0], 0), 0) + pointsPerRiggedOutcome.getOrDefault( it[1], 0) } } } val inputData = readInput("Day02_input") println("Part 1: " + part1(inputData)) println("Part 2: " + part2(inputData)) }
0
Kotlin
0
0
d01860ecaff005aaf8e1e4ba3777a325a84c557c
1,406
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day14.kt
VictorWinberg
433,748,855
false
{"Kotlin": 26228}
package days class Day14 : Day(14) { override fun partOne(): Any { var input = inputTestString.split("\n\n")[0] val commands = inputTestString.split("\n\n")[1].split("\n").map { Pair(it.split(" -> ")[0], it.split(" -> ")[1]) }.toMap() (0 until 10).forEach { input = input.zipWithNext().map { (a, b) -> val pair = a.toString() + b.toString() val key = commands.keys.find { it == pair } ?: return@map a.toString() a.toString() + commands[key] }.joinToString("") + input[input.length - 1] } val map = input.groupBy { it }.mapValues { (_, value) -> value.count() } return map.maxOf { it.value } - map.minOf { it.value } } override fun partTwo(): Any { val inputStr = inputString.split("\n\n")[0] var input = (inputStr + "_").zipWithNext().groupBy { it.first.toString() + it.second.toString() }.mapValues { (_, v) -> v.size.toLong() } val commands = inputString.split("\n\n")[1].split("\n").map { Pair(it.split(" -> ")[0], it.split(" -> ")[1]) }.toMap() (0 until 40).forEach { val map = input.toMap() as HashMap<String, Long> input.forEach poop@{ (pair, count) -> val key = commands.keys.find { it == pair } ?: return@poop val value = commands[key]!! val leftPair = pair[0] + value val rightPair = value + pair[1] map[pair] = map[pair]!!.minus(count) map[leftPair] = map.getOrDefault(leftPair, 0) + count map[rightPair] = map.getOrDefault(rightPair, 0) + count } input = map.toMap() } val map2 = input.map { (k, v) -> k[0] to v }.groupBy { it.first }.mapValues { (_, v) -> v.sumOf { it.second } } return map2.maxOf { it.value } - map2.minOf { it.value } } }
0
Kotlin
0
0
d61c76eb431fa7b7b66be5b8549d4685a8dd86da
1,914
advent-of-code-kotlin
Creative Commons Zero v1.0 Universal
src/day_03/Day03.kt
BrumelisMartins
572,847,918
false
{"Kotlin": 32376}
package day_03 import readInput fun main() { fun findPriorityItem(bag: Bag): String { val listOfDuplicates = bag.firstCompartment.intersect(bag.secondCompartment.toSet()) return listOfDuplicates.first() } fun findPriorityItemFromMultipleBags(listOfBags: List<MessyBag>): String { var setOfBags = listOfBags.first().bagContent.toSet() listOfBags.forEachIndexed { index, _ -> if (index >= listOfBags.size - 1) return@forEachIndexed val secondBag = listOfBags[index + 1] setOfBags = setOfBags.intersect(secondBag.bagContent.toSet()) } return setOfBags.first() } fun getPrioritySum(listOfBags: List<Bag>): Int { return listOfBags.sumOf { findPriorityItem(it).toPriority() } } fun getPrioritySumFromMultipleGroups(listOfBags: List<List<MessyBag>>): Int { return listOfBags.sumOf { findPriorityItemFromMultipleBags(it).toPriority() } } fun part1(input: List<String>): Int { val listOfBags = input.map { it.toBag() } return getPrioritySum(listOfBags) } fun part2(input: List<String>): Int { val listOfGroupBags = input.map { it.toMessyBag() } .windowed(3, 3) return getPrioritySumFromMultipleGroups(listOfGroupBags) } // test if implementation meets criteria from the description, like: val testInput = readInput("day_03/Day03_test") check(part1(testInput) == 157) val input = readInput("day_03/Day03") println(part1(input)) println(part2(input)) println(part2(testInput)) }
0
Kotlin
0
0
3391b6df8f61d72272f07b89819c5b1c21d7806f
1,598
aoc-2022
Apache License 2.0
src/day3/Day03.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day3 import readInput fun main() { fun parseInput(input: List<String>) = input.map { val size = it.length val compartment1 = it.slice(0 until (size / 2)).split("").slice(1..size / 2) val compartment2 = it.slice(size / 2 until size).split("").slice(1..size / 2) listOf(compartment1, compartment2) } fun findFirstCommon(list1: List<String>, list2: List<String>): Char { val second = list2.toSet() for (s in list1) { if(second.contains(s)) return s[0] } return '0' } fun getPriority(itemType: Char): Int { return if(itemType in 'a'..'z') { itemType.code - 96 } else { itemType.code - 38 } } fun part1(input: List<String>): Int { val data = parseInput(input) var prioritiesSum = 0 for(rucksack in data) { val itemType = findFirstCommon(rucksack.first(), rucksack.last()) val priority = getPriority(itemType) prioritiesSum += priority } return prioritiesSum } fun part2(input: List<String>): Int { var prioritiesSum = 0 for(i in input.indices step 3) { val second = input[i + 1].toSet() val third = input[i + 2].toSet() for (c in input[i]) { if (second.contains(c) && third.contains(c)) { val priority = getPriority(c) prioritiesSum += priority break } } } return prioritiesSum } // test if implementation meets criteria from the description, like: check(part1(readInput("Day03_test")) == 157) println(part1(readInput("Day03"))) check(part2(readInput("Day03_test")) == 70) println(part2(readInput("Day03"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
1,892
aoc-2022
Apache License 2.0
y2020/src/main/kotlin/adventofcode/y2020/Day07.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution fun main() = Day07.solve() object Day07 : AdventSolution(2020, 7, "Handy Haversacks") { override fun solvePartOne(input: String): Int { val containedBy: Map<String, List<String>> = input.lineSequence() .map(::parseRule) .flatMap { (container, inside) -> inside.mapValues { container }.entries } .groupBy({ it.key }, { it.value }) fun possibleContainers(bag: String): Set<String> = containedBy[bag].orEmpty() .map(::possibleContainers) .fold(setOf(bag), Set<String>::union) return possibleContainers("shiny gold").size - 1 } override fun solvePartTwo(input: String): Long { val contents: Map<String, Map<String, Int>> = input.lineSequence() .associate(this::parseRule) fun countContents(bag: String): Long = contents[bag].orEmpty() .entries .sumOf { (color, count) -> count * countContents(color) } + 1 return countContents("shiny gold") -1 } private fun parseRule(line: String): Pair<String, Map<String, Int>> { val container = line.substringBefore(" bags contain") val containedBagCounts: Map<String, Int> = """(\d+) (\w+ \w+) bags?""".toRegex() .findAll(line) .map { it.destructured } .associate { (count, color) -> color to count.toInt() } return container to containedBagCounts } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,582
advent-of-code
MIT License
src/Day09.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import kotlin.math.absoluteValue import kotlin.math.max enum class Direction { U, D, L, R } typealias Position = Pair<Int, Int> typealias Motion = Pair<Direction, Int> fun Position.move(direction: Direction): Position = when (direction) { Direction.U -> first - 1 to second Direction.D -> first + 1 to second Direction.L -> first to second - 1 Direction.R -> first to second + 1 } fun Position.adjacent(other: Position): Boolean = max( (first - other.first).absoluteValue, (second - other.second).absoluteValue, ) <= 1 fun Position.chase(other: Position): Position = if (adjacent(other)) { this } else { var newPosition = this if (other.first < first) { newPosition = newPosition.move(Direction.U) } if (other.first > first) { newPosition = newPosition.move(Direction.D) } if (other.second < second) { newPosition = newPosition.move(Direction.L) } if (other.second > second) { newPosition = newPosition.move(Direction.R) } newPosition } class Rope(val size: Int) { private val knots = MutableList(size) { origin } fun head() = knots.first() fun tail() = knots.last() fun move(motions: Iterable<Motion>): Int { val visitedPositons = mutableSetOf(tail()) motions.forEach { (direction, steps) -> repeat(steps) { knots[0] = head().move(direction) // Move head first for (i in 1 until size) { knots[i] = knots[i].chase(knots[i - 1]) // Each knot chases the knot in front } visitedPositons.add(tail()) } } return visitedPositons.size } companion object { val origin: Position = 0 to 0 } } fun main() { val motions: List<Motion> = readInput("Day09").map { line -> val (direction, steps) = line.split(" ") Direction.valueOf(direction) to steps.toInt() } println(Rope(2).move(motions)) println(Rope(10).move(motions)) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
2,145
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day13.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2023 import AoCDay import util.illegalInput // https://adventofcode.com/2023/day/13 object Day13 : AoCDay<Int>( title = "Point of Incidence", part1ExampleAnswer = 405, part1Answer = 37718, part2ExampleAnswer = 400, part2Answer = 40995, ) { private class Pattern(private val pattern: List<String>) { init { require(pattern.isNotEmpty()) { "Pattern must not be empty" } require(pattern.all(String::isNotEmpty)) { "Rows must not be empty" } require(pattern.map(String::length).distinct().size == 1) { "All rows must have the same length" } } fun replace(row: Int, col: Int) = Pattern(pattern.mapIndexed { iRow, r -> r.mapIndexed { iCol, c -> if (iRow == row && iCol == col) when (c) { '.' -> '#' '#' -> '.' else -> illegalInput(c) } else c }.joinToString("") }) val rowCount get() = pattern.size val colCount get() = pattern.first().length val rows get() = pattern val cols get() = pattern.first().indices.map { i -> pattern.map { row -> row[i] }.joinToString("") } } private fun parsePatterns(input: String) = input.split("\n\n").map(String::lines).map(::Pattern) private fun getReflections(list: List<String>) = (1..list.lastIndex) .filter { x -> (list.take(x).reversed() zip list.drop(x)).all { (a, b) -> a == b } } override fun part1(input: String) = parsePatterns(input).sumOf { pattern -> getReflections(pattern.rows).singleOrNull()?.let(100::times) ?: getReflections(pattern.cols).single() } override fun part2(input: String): Int { val patterns = parsePatterns(input) var sum = 0 outer@ for (pattern in patterns) { val rowReflection = getReflections(pattern.rows).singleOrNull() val colReflection = getReflections(pattern.cols).singleOrNull() for (row in 0..<pattern.rowCount) { for (col in 0..<pattern.colCount) { val replaced = pattern.replace(row, col) val rr = getReflections(replaced.rows).filter { it != rowReflection } if (rr.isNotEmpty()) { sum += rr.single() * 100 continue@outer } val cr = getReflections(replaced.cols).filter { it != colReflection } if (cr.isNotEmpty()) { sum += cr.single() continue@outer } } } } return sum } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,705
advent-of-code-kotlin
MIT License
2021/src/main/kotlin/day3_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Solution import utils.startsWith fun main() { Day3.run() } object Day3 : Solution<IntGrid>() { override val name = "day3" override val parser = IntGrid.singleDigits override fun part1(input: IntGrid): Int { val gamma = (0 until input.width).map { index -> getPop(input[index].values).first }.joinToString(separator = "").toInt(2) val epsilon = (0 until input.width).map { index -> getPop(input[index].values).second }.joinToString(separator = "").toInt(2) return gamma * epsilon } override fun part2(input: IntGrid): Int { val oxygen = generateSequence(emptyList<Int>() to input.rows) { (mask, rows) -> if (mask.size == input.width) return@generateSequence null val newMask = mask + getPop(rows.map { it[mask.size] }).first (newMask to rows.filter { it.values.startsWith(newMask) }).takeIf { it.second.isNotEmpty() } }.last().second.first().values.joinToString("").toInt(2) val co2 = generateSequence(emptyList<Int>() to input.rows) { (mask, rows) -> if (mask.size == input.width) return@generateSequence null val newMask = mask + getPop(rows.map { it[mask.size] }).second (newMask to rows.filter { it.values.startsWith(newMask) }).takeIf { it.second.isNotEmpty() } }.last().second.first().values.joinToString("").toInt(2) return oxygen * co2 ///co2 } /** * Returns 1, 0 if there's at least as many ones as zeroes in strings at pos * else returns 0, 1 */ private fun getPop(values: Collection<Int>): Pair<Int, Int> { val ones = values.count { it == 1 } val zeroes = values.count { it == 0 } return if (ones >= zeroes) 1 to 0 else 0 to 1 } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,714
aoc_kotlin
MIT License
src/Day03.kt
romainbsl
572,718,344
false
{"Kotlin": 17019}
fun main() { fun part1(input: List<String>): Int = input.sumOf { Rucksack.fromBatch(it).score } fun part2(input: List<String>): Int = input.chunked(3).sumOf { chunkOfThree: List<String> -> val rucksackBatch = chunkOfThree.map { rucksack -> rucksack.map { Item.fromChar(it) }.toSet() } rucksackBatch[0] .intersect(rucksackBatch[1]) .intersect(rucksackBatch[2]) .sumOf { it.value } } val testInput = readInput("Day03") // Part 1 println(part1(testInput)) // Part 2 println(part2(testInput)) } data class Rucksack( val left: Compartment, val right: Compartment, ) { val score: Int get() = left.items.intersect(right.items.toSet()).sumOf { it.value } companion object { fun fromBatch(batch: String): Rucksack { val chunkSize = batch.length / 2 return Rucksack( left = Compartment.fromBatch(batch.take(chunkSize)), right = Compartment.fromBatch(batch.drop(chunkSize)) ) } } } data class Compartment(val items: List<Item>) { companion object { fun fromBatch(batch: String): Compartment = Compartment(batch.map { Item.fromChar(it) }) } } @JvmInline value class Item(val value: Int) { companion object { private const val a = 'a' private const val A = 'A' fun fromChar(c: Char): Item = when (c.isLowerCase()) { true -> Item(c - a + 1) false -> Item(c - A + 27) } } }
0
Kotlin
0
0
b72036968769fc67c222a66b97a11abfd610f6ce
1,536
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
Miguel1235
726,260,839
false
{"Kotlin": 21105}
private fun findCords(r: Int, c: Int, engine: List<List<Char>>): Map<String, Char?> { return mapOf( "bottom" to engine.getOrNull(r + 1)?.getOrNull(c), "top" to engine.getOrNull(r - 1)?.getOrNull(c), "left" to engine.getOrNull(r)?.getOrNull(c - 1), "leftBottom" to engine.getOrNull(r + 1)?.getOrNull(c - 1), "leftTop" to engine.getOrNull(r - 1)?.getOrNull(c - 1), "right" to engine.getOrNull(r)?.getOrNull(c + 1), "rightBottom" to engine.getOrNull(r + 1)?.getOrNull(c + 1), "rightTop" to engine.getOrNull(r - 1)?.getOrNull(c + 1) ) } private fun checkAdjacent(r: Int, c: Int, engine: List<List<Char>>): Boolean { for (cord in findCords(r, c, engine).values) { if (cord != null && cord != '.' && !cord.isDigit()) return true } return false } private fun part1(input: List<String>, engine: List<List<Char>>): Number { val numsRegex = Regex("""\d+""") var total = 0 for (i in input.indices) { val row = input[i] val results = numsRegex.findAll(row) for (r in results) { val range = r.range for (col in range.first..range.last) { if (!checkAdjacent(i, col, engine)) continue total += r.value.toInt() break } } } return total } private class PartNumber(val r: Int, val cs: Int, val ce: Int, val num: Int) private fun findNumbers(input: List<String>): List<PartNumber> { val numsRegex = Regex("""\d+""") val partNumbers: MutableList<PartNumber> = mutableListOf() for (i in input.indices) { val row = input[i] val results = numsRegex.findAll(row) for (r in results) { partNumbers.add(PartNumber(i, r.range.first, r.range.last, r.value.toInt())) } } return partNumbers } private class Asterisk(val r: Int, val c: Int) private fun findPossibleGears(input: List<String>): List<Asterisk> { val gearRegex = Regex("""\*""") val asterisks: MutableList<Asterisk> = mutableListOf() for (i in input.indices) { val row = input[i] val gearFinds = gearRegex.findAll(row) for (gearFind in gearFinds) { asterisks.add(Asterisk(i, gearFind.range.first)) } } return asterisks } private fun findN(r: Int, c: Int, pn: List<PartNumber>): List<PartNumber> { // bottom val rb = pn.filter { p -> p.r == r + 1 && c >= p.cs - 1 && c <= p.ce + 1 } // top val rt = pn.filter { p -> p.r == r - 1 && c >= p.cs - 1 && c <= p.ce + 1 } // left & right val rlr = pn.filter { p -> p.r == r && c >= p.cs - 1 && c <= p.ce + 1 } return rb + rt + rlr } private fun part2(input: List<String>): Number { val partNumbers = findNumbers(input) val gears = findPossibleGears(input).map {pg -> findN(pg.r, pg.c, partNumbers) }.filter { pg -> pg.size == 2 } return gears.fold(0) {acc, gear -> acc + (gear[0].num*gear[1].num) } } fun main() { val inputTest = readInput("Day03_test") val engineTest: List<List<Char>> = inputTest.map { row -> row.toCharArray().toList() } check(part1(inputTest, engineTest) == 4361) check(part2(inputTest) == 467835) val input = readInput("Day03") val engine: List<List<Char>> = input.map { row -> row.toCharArray().toList() } part1(input, engine).println() // 557705 part2(input).println() // 84266818 }
0
Kotlin
0
0
69a80acdc8d7ba072e4789044ec2d84f84500e00
3,423
advent-of-code-2023
MIT License
day12/src/Day12.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day12(private val path: String) { private val connection = mutableMapOf<String, MutableSet<String>>() private val paths = mutableListOf<List<String>>() init { File(path).forEachLine { val parts = it.split("-") if (parts[0] != "end" && parts[1] != "start") { connection.getOrPut(parts[0]) { mutableSetOf() }.add(parts[1]) } if (parts[0] != "start" && parts[1] != "end") { connection.getOrPut(parts[1]) { mutableSetOf() }.add(parts[0]) } } } private fun isSmallCave(name: String): Boolean { return name[0] in 'a'..'z' } private fun countDistinct(start: String, visited: Set<String>, currentPath: List<String>) { connection[start]?.forEach { if (it == "end") { paths.add(currentPath.plus("end")) } else { if (!visited.contains(it)) { val newVisited = if (isSmallCave(it)) visited.plus(it) else visited countDistinct(it, newVisited, currentPath.plus(it)) } } } } /*private fun countDistinct2(start: String, visited: Set<String>, currentPath: List<String>, visitedTwice: String, depth: Int) { connection[start]?.forEach { if (it == "end") { paths.add(currentPath.plus("end")) } else { if (!visited.contains(it)) { var newVisited = visited var newVisitedTwice = visitedTwice if (isSmallCave(it)) { if (visitedTwice == "") { newVisitedTwice = it } else { newVisited = visited.plus(it) } } countDistinct2(it, newVisited, currentPath.plus(it), newVisitedTwice, depth + 1) } } } }*/ private fun countDistinct2(start: String, visited: Set<String>, currentPath: List<String>, visitedTwice: Boolean, depth: Int) { connection[start]?.forEach { next -> /*for (i in 0 until depth) { print(" ") } println(next)*/ if (next == "end") { paths.add(currentPath.plus("end")) } else { if (isSmallCave(next)) { if (visited.contains(next)) { if (!visitedTwice) { // Allow two visits to one small cave and record the double visit countDistinct2(next, visited, currentPath.plus(next), true, depth + 1) } } else { countDistinct2(next, visited.plus(next), currentPath.plus(next), visitedTwice, depth + 1) } } else { countDistinct2(next, visited, currentPath.plus(next), visitedTwice, depth + 1) } } } } fun part1(): Int { countDistinct("start", emptySet(), listOf("start")) //paths.forEach { println(it) } return paths.size } fun part2(): Int { countDistinct2("start", emptySet(), listOf("start"), false, 0) paths.forEach { println(it) } return paths.size } } fun main() { val aoc = Day12("day12/input.txt") //println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
3,547
aoc2021
Apache License 2.0
src/y2021/d06/Day06.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2021.d03 import println import readInput fun main() { val classPath = "y2021/d06" fun part1(input: List<String>, days: Int): Int { var fishes = input[0].split(",").map { it.toInt() } var nextFishes: List<Int> for (i in 1..days) { nextFishes = fishes.map { if (it == 0) 6 else it - 1 } fishes.count { it == 0 }.let { 1.rangeTo(it).forEach { _ -> nextFishes.addLast(8) } } fishes = nextFishes } return fishes.size } fun part2(input: List<String>, days: Int): Int { var fishes = input[0].split(",").map { it.toInt() } fishes.let { println(it) } // 18 // 3, 4, 3, 1, 2 // 21, 22, 21, 19, 20 // 22 15 8 1 // 22/7 = 3 // newFish(daysLeft - 7 * 1) = newFish(22 - 7) = newFish(15) // newFish(daysLeft - 7 * 2) = newFish(22 - 14) = newFish(8) // newFish(daysLeft - 7 * 3) = newFish(22 - 21) = newFish(1) return fishes .map { days + (6 - it) } // .also { println(it) } .map { oldFish(it) } // .also { println(it) } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") // part1(testInput, 18).println() for (i in 1..20) { part2(testInput, 2).println() } val input = readInput("${classPath}/input") // part1(input).println() // part2(input, 80).println() } fun newFish(daysLeft: Int): Int { // println("newFish(${daysLeft})") if (daysLeft < 0) return 0 return 1 + oldFish(daysLeft - 9) } fun oldFish(daysLeft: Int): Int { // println("oldFish(${daysLeft})") if (daysLeft < 0) return 0 return 1 + 1.rangeTo(daysLeft / 7).map { newFish(daysLeft - 7 * it) }.sum() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
1,833
aoc
Apache License 2.0
src/main/kotlin/day3/Day3.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day3 import readToList import kotlin.reflect.KFunction2 private val input = readToList("day3.txt") .map { it.toCharArray() }.toTypedArray() fun main() { println(part1()) println(part2()) } fun part1(): Int { val transposed = transpose(input) val gammaBits = transposed.map { column -> if (column.count { it == '0' } > column.size / 2) '0' else '1' }.toCharArray() val epsilonBits = inverse(gammaBits) val gamma = toInt(gammaBits) val epsilon = toInt(epsilonBits) return gamma * epsilon } private fun inverse(gammaBits: CharArray) = gammaBits.map { if (it == '0') '1' else '0' }.toCharArray() fun part2(): Int { val n1 = filterReport(::mostCommon) val n2 = filterReport(::leastCommon) return n1 * n2 } private fun filterReport(decider: KFunction2<List<Char>, Char, Boolean>): Int { var result = input var index = 0 while (result.size != 1) { val transposed = transpose(result) val column = transposed[index] result = if (decider(column, '1')) { filterNumber(result, index, '1') } else { filterNumber(result, index, '0') } index++ } return toInt(result[0]) } private fun mostCommon(column: List<Char>, bit: Char) = column.count { it == bit } >= column.size / 2.0 private fun leastCommon(column: List<Char>, bit: Char) = !mostCommon(column, bit) private fun filterNumber( currentInput: Array<CharArray>, index: Int, bit: Char ) = currentInput.filter { row -> row[index] == bit }.toTypedArray() private fun toInt(bits: CharArray): Int { return Integer.parseInt(String(bits), 2) } private fun transpose(source: Array<CharArray>) = (source.first().indices).map { i -> (source.indices).map { j -> source[j][i] } }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
1,841
aoc2021
Apache License 2.0
src/main/kotlin/_2022/Day7.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2022 import REGEX_LINE_SEPARATOR import REGEX_WHITESPACE import aoc import format fun main() { aoc(2022, 7) { aocRun { input -> process(input).values.filter { it.size <= 100000 }.sumOf { it.size } } aocRun { input -> val dirs = process(input) val totalSize = dirs["/"]!!.size val spaceNeeded = 30000000 - (70000000 - totalSize) println("Total: ${totalSize.format()}, Need: ${spaceNeeded.format()}") return@aocRun dirs.values.sortedBy { it.size }.first { it.size >= spaceNeeded }.size } } } private fun process(input: String): Map<String, Dir> { val path = mutableListOf("/") fun pathToString() = path[0] + path.asSequence().drop(1).joinToString(separator = "/") val dirs = mutableMapOf<String, Dir>() dirs["/"] = Dir("/", null) fun getDir(): Dir { val pathString = pathToString() return dirs.getOrPut(pathString) { val parent = pathString.substringBeforeLast('/').let { if (it.isEmpty()) dirs["/"] else dirs[it] } Dir(pathString, parent) } } input.splitToSequence(REGEX_LINE_SEPARATOR).map { it.split(REGEX_WHITESPACE) }.forEach { line -> when (line[0]) { "$" -> { when (line[1]) { "cd" -> when (line[2]) { "/" -> path.apply { clear() add("/") } ".." -> path.removeLast() else -> path.add(line[2]) } "ls" -> Unit else -> error("Unknown command: $line") } } "dir" -> getDir().subDirs += line[1] else -> { val fileSize = line[0].toLong() var dir = getDir() dir.files += (line[1] to fileSize) dir.size += fileSize while (dir.parentDir != null) { dir = dir.parentDir!! dir.size += fileSize } } } } // dirs.values.sortedBy { it.path }.forEach { println("${it.path} -> ${it.size}") } return dirs } private data class Dir( val path: String, val parentDir: Dir?, var size: Long = 0, val subDirs: MutableList<String> = mutableListOf(), val files: MutableList<Pair<String, Long>> = mutableListOf() ) private val testInput = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent()
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
2,231
AdventOfCode
Creative Commons Zero v1.0 Universal
src/day11/Day11.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day11 import readInput fun main (){ val day11Input = readInput("day11") val monkeysListPartOne = parseInput(day11Input) val monkeysListPartTwo = parseInput(day11Input) println(monkeyBusiness(monkeys = monkeysListPartOne, rounds = 20, worryDivisor = 3L)) println(monkeyBusiness(monkeys = monkeysListPartTwo, rounds = 10000, worryDivisor = 0L)) } // Using the solution from Todd Ginsberg solution for day 11 fun List<Monkey>.getTestProduct(): Long { var product = 1L this.forEach { monkey -> product *= monkey.testCondition } return product } private fun monkeyBusiness(monkeys: List<Monkey>, rounds: Int = 20, worryDivisor: Long = 3L): Long { repeat(rounds) { monkeys.forEach { monkey -> // Monkey to move to - index of item to move val itemsToMove = mutableListOf<Pair<Int, Int>>() monkey.items.forEachIndexed { index, _ -> // Make the human worried val product = monkeys.getTestProduct() monkey.updateWorryLevel(index, product) // Monkey inspects item monkey.inspectItem(index, worryDivisor) // Monkey decided who it's going to throw to if (monkey.isTheHumanWorried(index)) { itemsToMove.add(monkey.trueMonkey to index) } else { itemsToMove.add(monkey.falseMonkey to index) } } // Monkey throws the items itemsToMove.forEach { val otherMonkey = monkeys[it.first] otherMonkey.items.add(monkey.items[it.second]) } monkey.itemsInspected += monkey.items.size monkey.items.clear() } } // monkeys.forEach(::println) val deviousMonkeys = monkeys.sortedByDescending { it.itemsInspected } return deviousMonkeys[0].itemsInspected * deviousMonkeys[1].itemsInspected } data class Monkey(val items: MutableList<Long>, val operation: Operation, val testCondition: Long, val trueMonkey: Int, val falseMonkey: Int, var itemsInspected: Long = 0L){ fun inspectItem(itemIndex: Int, divisor : Long = 3L){ if(divisor > 0) { items[itemIndex] = items[itemIndex] / divisor } } fun updateWorryLevel(itemIndex: Int){ val item = items[itemIndex] items[itemIndex] = operation.operate(item) } // Using the solution from Todd Ginsberg solution for day 11 fun updateWorryLevel(itemIndex: Int, testProduct : Long){ val item = items[itemIndex] items[itemIndex] = operation.operate(item) % testProduct } fun isTheHumanWorried(itemIndex: Int): Boolean { val item = items[itemIndex] return item % testCondition == 0L } } data class Operation(private val type: String, private val amount: Long, val useOld: Boolean){ fun operate(item: Long): Long { return if(useOld){ when(type){ "*" -> item * item else -> item + item } } else { when(type){ "*" -> item * amount else -> item + amount } } } } fun parseInput(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() var i = 0 while(i < input.size){ // If the input is M I assume it's a Monkey if(input[i].isNotEmpty() && input[i].first() == 'M'){ val startItemInputStartIndex = input[i + 1].indexOfFirst { it.isDigit() } val startingItems = input[i + 1].slice(startItemInputStartIndex until input[i + 1].length).split(",").map(String::trim).map(String::toLong) // println(startingItems) val operationStartIndex = if(input[i + 2].contains("*")) input[i + 2].indexOf("*") else input[i + 2].indexOf("+") val operationList = input[i + 2].slice(operationStartIndex until input[i + 2].length).split(" ") val operation = Operation(type = operationList.first(), useOld = operationList.last() == "old", amount = if(operationList.last() == "old") 1L else operationList.last().toLong()) // println(operation) val testStartIndex = input[i + 3].indexOfFirst { it.isDigit() } val testAmount = input[i + 3].slice(testStartIndex until input[i + 3].length).toLong() // println(testAmount) val trueStartIndex = input[i + 4].indexOfFirst { it.isDigit() } val trueMonkey = input[i + 4].slice(trueStartIndex until input[i + 4].length).toInt() // println(trueMonkey) val falseStartIndex = input[i + 5].indexOfFirst { it.isDigit() } val falseMonkey = input[i + 5].slice(falseStartIndex until input[i + 5].length).toInt() // println(falseMonkey) val monkey = Monkey(items = startingItems.toMutableList(), operation = operation, testCondition = testAmount, trueMonkey = trueMonkey, falseMonkey = falseMonkey) monkeys.add(monkey) i += 5 } i++ } return monkeys }
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
5,134
advent-of-code-kotlin-2022
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day3.kt
sviams
115,921,582
false
null
object AoC_Day3 { fun solvePt1(input: Int) : Int { val bottomRights = (1..(Math.sqrt(input.toDouble()).toInt()+2)).filter { it % 2 != 0 }.map { it * it }.asReversed() if (bottomRights.contains(input)) return (bottomRights.size-2)*2 val width = (bottomRights[0] - bottomRights[1]) / 4 val cartesians = (0..3).map { bottomRights[0] - width * it - width / 2 } return Math.abs(input - cartesians.first { Math.abs(input - it) < width/2 }) + bottomRights.size - 1 } data class GridNode(val x: Int, val y: Int, val value: Int) data class State(val w: Int, val x: Int, val y: Int, val side: Int, val nodes: List<GridNode>) fun sumNeighbours(x: Int, y: Int, neighbours: List<GridNode>) : Int = (-1..1).fold(0) { accX, ix -> accX + (-1..1).fold(0) { accY, iy -> accY + (neighbours.firstOrNull { node -> node.x == x + ix && node.y == y + iy }?.value ?: 0) } } fun solvePt2(input: Int) : Int = generateSequence(State(1, 1, 0, 0, listOf(GridNode(0,0,1)))) { val newNodes = it.nodes.plus(GridNode(it.x, it.y, sumNeighbours(it.x, it.y, it.nodes))) val halfWidth = (it.w +1)/2 when (it.side) { 0 -> if (Math.abs(it.y+1) > halfWidth) State(it.w, it.x-1, it.y, it.side+1, newNodes) else State(it.w, it.x, it.y+1, it.side, newNodes) 1 -> if (Math.abs(it.x-1) > halfWidth) State(it.w, it.x, it.y-1, it.side+1, newNodes) else State(it.w, it.x-1, it.y, it.side, newNodes) 2 -> if (Math.abs(it.y-1) > halfWidth) State(it.w, it.x+1, it.y, it.side+1, newNodes) else State(it.w, it.x, it.y-1, it.side, newNodes) else -> if (Math.abs(it.x+1) > halfWidth) State(it.w+2, it.x+1, it.y, 0, newNodes) else State(it.w, it.x+1, it.y, it.side, newNodes) } }.takeWhileInclusive { it.nodes.last().value <= input }.last().nodes.last().value }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,957
aoc17
MIT License
src/main/kotlin/aoc2022/Day18.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import kotlin.math.abs // https://adventofcode.com/2022/day/18 object Day18 : AoCDay<Int>( title = "Boiling Boulders", part1ExampleAnswer = 64, part1Answer = 3396, part2ExampleAnswer = 58, part2Answer = 2044, ) { private data class Cube(val x: Int, val y: Int, val z: Int) private fun parseCubes(input: String) = input .lineSequence() .map { line -> line.split(',', limit = 3) } .map { (x, y, z) -> Cube(x.toInt(), y.toInt(), z.toInt()) } .toSet() private fun manhattanDistance(c1: Cube, c2: Cube) = abs(c1.x - c2.x) + abs(c1.y - c2.y) + abs(c1.z - c2.z) private infix fun Cube.isAdjacentTo(other: Cube) = manhattanDistance(this, other) == 1 private const val CUBE_SIDES = 6 override fun part1(input: String): Int { val cubes = parseCubes(input) return cubes.sumOf { c1 -> CUBE_SIDES - cubes.count { c2 -> c1 isAdjacentTo c2 } } } override fun part2(input: String): Int { val cubes = parseCubes(input) val minX = cubes.minOf { it.x } val maxX = cubes.maxOf { it.x } val minY = cubes.minOf { it.y } val maxY = cubes.maxOf { it.y } val minZ = cubes.minOf { it.z } val maxZ = cubes.maxOf { it.z } val grid = Array(maxX - minX + 1) { Array(maxY - minY + 1) { BooleanArray(maxZ - minZ + 1) } } for ((x, y, z) in cubes) { grid[x - minX][y - minY][z - minZ] = true } val xs = 1..<(maxX - minX) val ys = 1..<(maxY - minY) val zs = 1..<(maxZ - minZ) val airPocketMemory = HashMap<Cube, Boolean>() fun isAirPocketWithDFS(cube: Cube, visited: MutableSet<Cube>): Boolean { val (x, y, z) = cube if (x !in xs || y !in ys || z !in zs) return false fun searchNeighbor(x: Int, y: Int, z: Int): Boolean { if (grid[x][y][z]) return true val neighbor = Cube(x, y, z) return if (visited.add(neighbor)) { airPocketMemory[neighbor] ?: isAirPocketWithDFS(cube = neighbor, visited).also { airPocketMemory[neighbor] = it } } else true } return searchNeighbor(x - 1, y, z) && searchNeighbor(x + 1, y, z) && searchNeighbor(x, y - 1, z) && searchNeighbor(x, y + 1, z) && searchNeighbor(x, y, z - 1) && searchNeighbor(x, y, z + 1) } val airPockets = buildSet { for (x in xs) { for (y in ys) { for (z in zs) { if (grid[x][y][z]) continue val cube = Cube(x, y, z) if (isAirPocketWithDFS(cube, visited = hashSetOf(cube))) { add(Cube(x + minX, y + minY, z + minZ)) } } } } } return cubes.sumOf { c1 -> CUBE_SIDES - cubes.count { c2 -> c1 isAdjacentTo c2 } - airPockets.count { airPocket -> c1 isAdjacentTo airPocket } } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,167
advent-of-code-kotlin
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-08.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2021, "08-input") val test1 = readInputLines(2021, "08-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val entries = input.map { Entry.parse(it) } val lengths = setOf(2, 4, 3, 7) return entries.sumOf { it.value.count { it.size in lengths } } } private fun part2(input: List<String>): Int { val entries = input.map { Entry.parse(it) } return entries.sumOf { it.decode() } } private fun Entry.decode(): Int { val one = patterns.first { it.size == 2 } val four = patterns.first { it.size == 4 } val seven = patterns.first { it.size == 3 } val eight = patterns.first { it.size == 7 } val top = (seven - one).single() val bottom = patterns.eliminate(6, four + seven) val middle = patterns.eliminate(5, seven + bottom) val topLeft = (four - one - middle).single() val bottomRight = patterns.eliminate(5, setOf(top, topLeft, middle, bottom)) val topRigth = (one - bottomRight).single() val bottomLeft = (eight - top - bottom - middle - bottomRight - topLeft - topRigth).single() val mapping = mapOf( top to 'a', topLeft to 'b', topRigth to 'c', middle to 'd', bottomLeft to 'e', bottomRight to 'f', bottom to 'g' ) fun Set<Char>.toDigit(): Int = segmentsMap[this.map { mapping[it] }.toSet()]!! val digits = value.map { it.toDigit() } return digits.fold(0) { acc, item -> 10 * acc + item } } private fun List<Set<Char>>.eliminate(size: Int, set: Set<Char>) = filter { it.size == size } .single { it.containsAll(set) } .let { it - set } .single() private data class Entry(val patterns: List<Set<Char>>, val value: List<Set<Char>>) { companion object { fun parse(input: String): Entry { val (patterns, value) = input.split(" | ") fun String.toSets() = split(" ").map { it.toSet() } return Entry(patterns.toSets(), value.toSets()) } } } private val segmentsMap = mapOf( "abcefg".toSet() to 0, "cf".toSet() to 1, "acdeg".toSet() to 2, "acdfg".toSet() to 3, "bcdf".toSet() to 4, "abdfg".toSet() to 5, "abdefg".toSet() to 6, "acf".toSet() to 7, "abcdefg".toSet() to 8, "abcdfg".toSet() to 9 ) /* 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 */
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,248
advent-of-code
MIT License
src/questions/KDiffPairs.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. * A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: * * `0 <= i < j < nums.length` * * `abs(nums[i] - nums[j]) == k` * * [Source](https://leetcode.com/problems/k-diff-pairs-in-an-array/) */ @UseCommentAsDocumentation private fun findPairs(nums: IntArray, k: Int): Int { val countMap = mutableMapOf<Int, Int>() nums.forEach { countMap[it] = countMap.getOrDefault(it, 0) + 1 } val seen = mutableSetOf<Pair<Int, Int>>() for (it in nums.distinct()) { val other = k + it val pair = Pair(minOf(other, it), maxOf(other, it)) // already seen if (seen.contains(pair)) { continue } // other == it is the case when k = 0 // It requires preventing self match in the [countMap] if (other == it && countMap[it]!! > 1) { // given k=0, [it] is repeated in the [nums] seen.add(pair) continue } else if (other == it) { // given k=0, [it] is not repeated so don't add this to [seen] continue } if (countMap.containsKey(other)) { seen.add(pair) } } return seen.size } fun main() { findPairs(nums = intArrayOf(1, 3, 1, 5, 4), k = 0) shouldBe 1 findPairs(nums = intArrayOf(1, 1, 1, 1, 1), k = 0) shouldBe 1 findPairs(nums = intArrayOf(1, 2, 4, 4, 3, 3, 0, 9, 2, 3), k = 3) shouldBe 2 // (1, 3) and (3, 5) findPairs(nums = intArrayOf(3, 1, 4, 1, 5), k = 2) shouldBe 2 //(1, 2), (2, 3), (3, 4) and (4, 5). findPairs(nums = intArrayOf(1, 2, 3, 4, 5), k = 1) shouldBe 4 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,802
algorithms
MIT License
src/main/kotlin/advent/of/code/day11/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day11 const val id = 5535 val squareResults = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() fun powerLevel(x: Int, y: Int) = (((((x + 10) * y + id) * (x + 10)) / 100) % 10) - 5 fun part1(): String { val result = (1..298).map { x -> (1..298).map { y -> val power = (0..2).map { powerX -> (0..2).map { powerY -> powerLevel(x + powerX, y + powerY) }.sum() }.sum() Triple(x, y, power) }.maxBy { it.third } }.maxBy { it?.third ?: 0 } return "${result?.first},${result?.second}" } fun part2(): String { var max = 0 var maxRegion: Triple<Int, Int, Int>? = null for (size in (1..300)) { for (x in (1..(301 - size))) { for (y in (1..(301 - size))) { val power = if (size > 1) { squareResults[Pair(x, y)]?.first!! + (x..(x + size - 2)).map { powerLevel(it, y + size - 1) }.sum() + (y..(y + size - 2)).map { powerLevel(x + size - 1, it) }.sum() + powerLevel(x + size - 1, y + size - 1) } else { (x..(x + size - 1)).map { innerX -> (y..(y + size - 1)).map { innerY -> powerLevel(innerX, innerY) }.sum() }.sum() } if (power > max) { max = power maxRegion = Triple(x, y, size) } squareResults[Pair(x, y)] = Pair(power, size) } } } return "${maxRegion?.first},${maxRegion?.second},${maxRegion?.third}" }
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
1,872
advent_of_code_2018
The Unlicense
Advent-of-Code-2023/src/Day18.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
import kotlin.math.abs private const val AOC_DAY = "Day18" private const val TEST_FILE = "${AOC_DAY}_test" private const val INPUT_FILE = AOC_DAY private val directions = mapOf( "U" to Position(-1, 0), "D" to Position(1, 0), "L" to Position(0, -1), "R" to Position(0, 1) ) private fun part1(input: List<String>): Int { val points = mutableListOf(Position(0, 0)) var perimeter = 0 input.forEach { line -> val (direction, meters, _) = line.split(" ") val (dirRow, dirCol) = directions[direction]!! val num = meters.toInt() perimeter += num val (row, col) = points.last() points.add(Position(row + dirRow * num, col + dirCol * num)) } // Using Shoelace formula to calculate the area of the polygon val area = abs(points.indices.sumOf { points[it].row * (points[if (it - 1 < 0) points.size - 1 else it - 1].col - points[(it + 1) % points.size].col) }) / 2 // Using Pick's theorem to calculate the number of points inside the polygon val i = area - perimeter / 2 + 1 return i + perimeter } private fun part2(input: List<String>): Long { val directionDigits = listOf("R", "D", "L", "U") val points = mutableListOf(Position(0, 0)) var perimeter = 0L input.forEach { line -> val (_, _, instruction) = line.split(" ") val (dirRow, dirCol) = directions[directionDigits[instruction[instruction.length - 2].digitToInt()]]!! val num = instruction.substring(instruction.length - 7, instruction.length - 2).toInt(radix = 16) perimeter += num val (row, col) = points.last() points.add(Position(row + dirRow * num, col + dirCol * num)) } val area = abs(points.indices.sumOf { points[it].row * (points[if (it - 1 < 0) points.size - 1 else it - 1].col - points[(it + 1) % points.size].col).toLong() }) / 2L val i = area - perimeter / 2 + 1 return i + perimeter } fun main() { createTestFiles(AOC_DAY) val testInput = readInputToList(TEST_FILE) val part1ExpectedRes = 62 println("---| TEST INPUT |---") println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes") val part2ExpectedRes = 952408144115L println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n") val input = readInputToList(INPUT_FILE) val improving = true println("---| FINAL INPUT |---") println("* PART 1: ${part1(input)}${if (improving) "\t== 56678" else ""}") println("* PART 2: ${part2(input)}${if (improving) "\t== 79088855654037" else ""}") }
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
2,577
Advent-of-Code-2023
Apache License 2.0
src/Day08.kt
thiyagu06
572,818,472
false
{"Kotlin": 17748}
import aoc22.printIt import java.io.File fun main() { fun parseInput(): List<List<Int>> { return File("input.txt/day07.txt").readLines().map { row -> row.map { it.digitToInt() } } } fun star1(input: List<List<Int>>): Int { return input.mapIndexed { rowNum, row -> List(row.size) { isVisible(rowNum, it, input) }.count { it } }.sumOf { it }.printIt() } fun star2(input: List<List<Int>>): Int { return input.mapIndexed { rowNum, row -> row.mapIndexed { colNum, tree -> val currentColumn = input.map { row -> row[colNum] } val leftScore = input[rowNum].subList(0, colNum).reversed().findScore(tree) val rightScore = input[rowNum].subList(colNum + 1, input[rowNum].size).findScore(tree) val topScore = currentColumn.subList(0, rowNum).reversed().findScore(tree) val bottomScore = currentColumn.subList(rowNum + 1, currentColumn.size).findScore(tree) leftScore * rightScore * topScore * bottomScore }.maxOf { it } }.maxOf { it }.printIt() } val grid = parseInput() // test if implementation meets criteria from the description, like: check(star1(grid) == 1854) check(star2(grid) == 527340) } private fun List<Int>.findScore(element: Int): Int { var count = 0 forEach { otherTree -> if (otherTree < element) { count += 1 } else { return count + 1 } } return count } fun isVisible(row: Int, col: Int, grid: List<List<Int>>): Boolean { if (row == 0 || row == grid.size - 1) return true if (col == 0 || col == grid.first().size - 1) return true val element = grid[row][col] val currentColumn = grid.map { r -> r[col] } when { (grid[row].subList(0, col).maxOf { it } < element) -> return true (grid[row].subList(col + 1, grid[row].size).maxOf { it } < element) -> return true (currentColumn.subList(0, row).maxOf { it } < element) -> return true (currentColumn.subList(row + 1, currentColumn.size).maxOf { it } < element) -> return true } return false }
0
Kotlin
0
0
55a7acdd25f1a101be5547e15e6c1512481c4e21
2,207
aoc-2022
Apache License 2.0
src/Day07.kt
hijst
572,885,261
false
{"Kotlin": 26466}
private typealias Commands = List<List<String>> fun main() { data class File(val name: String, val size: Long) class Directory(val name: String, val parent: Directory?) { val children: MutableList<Directory> = mutableListOf() val files: MutableList<File> = mutableListOf() var size: Long = 0 fun calculateSizeOfAllNested(): Long { val size = files.sumOf { it.size } + children.sumOf { it.calculateSizeOfAllNested() } this.size = size return size } } class FileSystem { val root: Directory = Directory("root", null) var currentDirectory: Directory = root fun createDirectory(name: String) { currentDirectory.children.add(Directory(name, currentDirectory)) } fun changeDirectory(name: String) { currentDirectory = when (name) { "/" -> root ".." -> currentDirectory.parent ?: throw Error("Can't switch to null") else -> currentDirectory.children.first { directory -> directory.name == name } } } fun flatMapDirectories(): List<Directory> { val directories = mutableListOf<Directory>() fun getAllDirectoriesRec(dir: Directory) { directories.add(dir) dir.children.forEach { child -> getAllDirectoriesRec(child) } } getAllDirectoriesRec(root) return directories.toList() } } var currentFileSystem = FileSystem() fun Commands.execute(): FileSystem { val fileSystem = FileSystem() with(fileSystem) { forEach { command -> when (command[0]) { "dir" -> if (currentDirectory.children.none { it.name == command[1] }) createDirectory(command[1]) "$" -> if (command[1] == "cd") changeDirectory(command[2]) else -> currentDirectory.files.add(File(command[1], command[0].toLong())) } } root.calculateSizeOfAllNested() } currentFileSystem = fileSystem return fileSystem } fun part1(commands: Commands): Long = commands .execute() .flatMapDirectories() .filter { it.size <= 100000L } .sumOf { it.size } fun part2(fileSystem: FileSystem): Long = fileSystem .flatMapDirectories() .map { it.size } .sorted() .first { it > 30000000L - (70000000L - fileSystem.root.size) } //val testInput = readInputWords("Day07_test") //check(part1(testInput) == 95437L) //check(part2(currentFileSystem) == 24933642L) val input = readInputWords("Day07_input") println(part1(input)) println(part2(currentFileSystem)) }
0
Kotlin
0
0
2258fd315b8933642964c3ca4848c0658174a0a5
2,816
AoC-2022
Apache License 2.0
src/Day05.kt
georgiizorabov
573,050,504
false
{"Kotlin": 10501}
fun main() { fun readStacks(input: List<String>): List<List<Char>> { val stacks = input.takeWhile { it != "" }.map { it.toList().filterIndexed { index, _ -> index % 4 == 1 } }.dropLast(1) val stacksConv: MutableList<MutableList<Char>> = Array(stacks.maxBy { it.size }.size) { ArrayList<Char>() }.toMutableList() stacks.forEach { it.withIndex().forEach { elem -> stacksConv[elem.index].add(elem.value) } } return stacksConv.map { it.filter { elem -> elem != ' ' } } } fun makeCommand(stacks: List<List<Char>>, command: List<String>, crateMoverVersion: Int = 9000): List<List<Char>> { val newStacks = stacks.toMutableList() var stacksToMove = newStacks[command[3].toInt() - 1].withIndex().takeWhile { it.index <= command[1].toInt() - 1 } .map { it.value } newStacks[command[3].toInt() - 1] = newStacks[command[3].toInt() - 1].withIndex() .map { if (it.index <= command[1].toInt() - 1) ' ' else it.value } if (crateMoverVersion == 9000) { stacksToMove = stacksToMove.reversed() } newStacks[command[5].toInt() - 1] = stacksToMove + newStacks[command[5].toInt() - 1] return newStacks.map { it.filter { elem -> elem != ' ' } } } fun readCommands(input: List<String>): List<List<String>> { return input.dropWhile { it != "" } .map { it.filter { elem -> elem.isDigit() || elem == ' ' }.split(" ") }.drop(1) } fun solve(input: List<String>, crateMoverVersion: Int = 9000): String { val stacks = (readStacks(input)) val commands = readCommands(input) var mutableStacks = stacks.toMutableList() for (command in commands) { mutableStacks = makeCommand(mutableStacks, command, crateMoverVersion).toMutableList() } return mutableStacks.map { it.first() }.joinToString(separator = "") } fun part1(input: List<String>): String { return solve(input) } fun part2(input: List<String>): String { return solve(input, 9001) } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bf84e55fe052c9c5f3121c245a7ae7c18a70c699
2,239
aoc2022
Apache License 2.0
src/day15/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day15 import java.io.File import kotlin.math.abs const val workingDir = "src/day15" fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample, 10)}") // 26 println("Step 1b: ${runStep1(input1, 2000000)}") // 5147333 println("Step 2a: ${runStep2(sample, 20)}") // 56000011 println("Step 2b: ${runStep2(input1, 4_000_000)}") // 13734006908372 } data class Position(val x: Int, val y: Int) { fun distanceTo(other: Position) = abs(x - other.x) + abs(y - other.y) val tuningFrequency: Long by lazy { x.toLong() * 4_000_000L + y } } data class Sensor(val position: Position, val nearestBeacon: Beacon) { private val distanceToBeacon by lazy { position.distanceTo(nearestBeacon) } fun emptySpotsAtRow(y: Int): List<IntRange> { val dX = distanceToBeacon - abs(position.y - y) if (dX < 0) return emptyList() val minX = position.x - dX val maxX = position.x + dX return listOf(minX..maxX) .flatMap { if (position.y == y && position.x in it) { when (position.x) { it.first -> listOf((it.first + 1..it.last)) it.last -> listOf((it.first until it.last)) else -> listOf((it.first until position.x), (position.x + 1..it.last)) } } else listOf(it) }.flatMap { if (nearestBeacon.y == y && nearestBeacon.x in it) { when (nearestBeacon.x) { it.first -> listOf((it.first + 1..it.last)) it.last -> listOf((it.first until it.last)) else -> listOf((it.first until nearestBeacon.x), (nearestBeacon.x + 1..it.last)) } } else listOf(it) } } } typealias Beacon = Position fun String.remove(str: String) = replace(str, "") fun String.remove(vararg strs: String) = strs.fold(this) { acc, s -> acc.remove(s) } fun File.toSensors() = readLines().map { val (p1, p2) = it .remove("Sensor at x=", ": closest beacon is at ", " ", "y=") .split("x=") .map { it.split(",").map { it.toInt() } } .map { (x, y) -> Position(x, y) } Sensor(p1, p2) } fun List<IntRange>.findHoles(min: Int, max: Int): List<Int> { val ret = ArrayList<Int>() if (minOf { it.first } > min) ret.addAll(min until minOf { it.first }) if (maxOf { it.last } < max) ret.addAll(maxOf { it.last } + 1..max) var current = min filter { it.last >= min && it.first <= max }.sortedBy { it.first }.forEach { if (it.first <= current && it.last >= current) current = it.last + 1 else if (it.last <= current) Unit else { ret.addAll(current until it.first) current = it.last + 1 } } return ret } val IntRange.size: Int get() = (last - first) + 1 fun runStep1(input: File, rowNum: Int): String { val sensors = input.toSensors() val beacons = sensors.map { it.nearestBeacon } val takenSpots = sensors.map { it.position } + beacons val emptySpotsAtRow = input.toSensors().flatMap { it.emptySpotsAtRow(rowNum) } val taken = takenSpots.filter { it.y == rowNum }.map { it.x } return ((emptySpotsAtRow.minOf { it.first }..emptySpotsAtRow.maxOf { it.last }) - taken.toSet()).size.toString() } fun runStep2(input: File, maxCoord: Int): String { val sensors = input.toSensors() val beacons = sensors.map { it.nearestBeacon } val takenSpots = sensors.map { it.position } + beacons (0..maxCoord).forEach { y -> val taken = takenSpots.filter { it.y == y }.map { it.x } val foo = sensors.flatMap { it.emptySpotsAtRow(y) }.findHoles(0, maxCoord).filter { it !in taken } if (foo.isNotEmpty()) return Position(foo.first(), y).tuningFrequency.toString() } TODO() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
3,972
advent-of-code-2022
Apache License 2.0
src/Day04/Day04.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
import java.lang.IllegalStateException fun main() { fun prepare(input: List<String>): Pair<List<Int>, List<List<List<Int>>>> { val fst = input[0].split(',').map { it.toInt() } val snd = arrayListOf<List<List<Int>>>() val res = input.slice(2 until input.size) var remainder = arrayListOf<List<Int>>() for (e in res) { if (e == "") { snd.add(remainder) remainder = arrayListOf() } else { remainder.add(e.trim().replace("\\s+".toRegex(), " ").split(" ").map { it.toInt() }) } } snd.add(remainder) return Pair(fst, snd) } fun part1(sequence: List<Int>, grids: List<List<List<Int>>>): Int { var gridsWc = grids for (e in sequence) { gridsWc = gridsWc.map { e1 -> e1.map { e2 -> e2.map { if (it == e) 0 else it } } } for (x in gridsWc) { for (i in 0 until 5) { if (x[i].sum() == 0) { return x.sumOf { it.sum() } * e } if (x.mapIndexed { index, list -> if (index == i) list.sum() else 0 }.sum() == 0) { return x.sumOf { it.sum() } * e } } } } throw IllegalStateException("Nobody won") } fun part2(sequence: List<Int>, grids: List<List<List<Int>>>): Int { var gridsWc = grids var loser = -1 for (e in sequence) { gridsWc = gridsWc.map { e1 -> e1.map { e2 -> e2.map { if (it == e) 0 else it } } } var loseCount = 0 for ((gridIndex, x) in gridsWc.withIndex()) { var won = false for (i in 0 until 5) { if (x[i].sum() == 0) { won = true break } if (x.sumOf { it.filterIndexed { index, _ -> index == i }[0] } == 0) { won = true break } } if (!won) { loseCount++ loser = gridIndex } } if (loseCount == 0) { return gridsWc[loser].sumOf { it.sum() } * e } } throw IllegalStateException("Nobody won last") } val (testSequence, testGrids) = prepare(readInput(4, true)) val (sequence, grids) = prepare(readInput(4)) check(part1(testSequence, testGrids) == 4512) println(part1(sequence, grids)) check(part2(testSequence, testGrids) == 1924) println(part2(sequence, grids)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
2,709
advent-of-code-2021
Apache License 2.0
src/day20/first/Solution.kt
verwoerd
224,986,977
false
null
package day20.first import tools.Coordinate import tools.adjacentCoordinates import tools.origin import tools.priorityQueueOf import tools.timeSolution const val START = "AA" const val END = "ZZ" fun main() = timeSolution { val (maze, portals) = parseMaze() println(maze.findPath(portals)) } private fun Maze.findPath(portals: Portals): Int { val startCoordinate = portals.getValue(START).first val endCoordinate = portals.getValue(END).first val seen = mutableSetOf(startCoordinate) val portalIndexes = portals.values.filter { it.second != origin } .flatMap { listOf(it.first to it.second, it.second to it.first) } .toMap() val queue = priorityQueueOf(Comparator { o1, o2 -> o1.second.compareTo(o2.second) }, startCoordinate to 0) while (queue.isNotEmpty()) { val (coordinate, distance) = queue.poll() when (coordinate) { endCoordinate -> return distance } adjacentCoordinates(coordinate).filter { seen.add(it) }.filter { (x, y) -> get(y)[x] == '.' } .map { target -> when (target) { in portalIndexes.keys -> portalIndexes.getValue(target) to distance + 2 else -> target to distance + 1 } }.toCollection(queue) } error("No path found") } typealias Maze = List<CharArray> typealias Portals = MutableMap<String, Pair<Coordinate, Coordinate>> fun parseMaze(): Pair<Maze, Portals> { val input: Maze = System.`in`.bufferedReader().readLines().map { it.toCharArray() } val portals: Portals = mutableMapOf() for (y in 2..input.size - 2) { if (input[y][2] == ' ') continue for (x in 2..input[y].size - 2) { when (input[y][x]) { '.' -> input.checkPortal(x, y, portals) } } } return input to portals } private fun Maze.checkPortal(x: Int, y: Int, portals: Portals): Boolean { val label = when { get(y)[x - 1] in 'A'..'Z' -> "${get(y)[x - 2]}${get(y)[x - 1]}" get(y)[x + 1] in 'A'..'Z' -> "${get(y)[x + 1]}${get(y)[x + 2]}" get(y - 1)[x] in 'A'..'Z' -> "${get(y - 2)[x]}${get(y - 1)[x]}" get(y + 1)[x] in 'A'..'Z' -> "${get(y + 1)[x]}${get(y + 2)[x]}" else -> "" } return when (label) { "" -> false in portals.keys -> { portals[label] = portals.getValue(label).first to Coordinate(x, y) true } else -> { portals[label] = Coordinate(x, y) to origin true } } }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
2,369
AoC2019
MIT License
src/Day02.kt
sk0g
572,854,602
false
{"Kotlin": 7597}
import Move.* import RoundResult.* fun parseInput(input: List<String>): List<List<Char>> { return input .map { it.toCharArray() .toList() .filter { it != ' ' } } } enum class Move { Rock, Paper, Scissors } fun getRoundResult(opponentInput: Char, playerInput: Char): Int { val opponentMove = mapOf('A' to Rock, 'B' to Paper, 'C' to Scissors)[opponentInput]!! val playerMove = mapOf('X' to Rock, 'Y' to Paper, 'Z' to Scissors)[playerInput]!! return when (opponentMove to playerMove) { Rock to Rock -> 1 + 3 Rock to Paper -> 2 + 6 Rock to Scissors -> 3 + 0 Paper to Rock -> 1 + 0 Paper to Paper -> 2 + 3 Paper to Scissors -> 3 + 6 Scissors to Rock -> 1 + 6 Scissors to Paper -> 2 + 0 Scissors to Scissors -> 3 + 3 else -> 0 } } enum class RoundResult { Lose, Draw, Win } fun getMoveForOutcome(opponentInput: Char, advisedOutcome: Char): Char { val opponentMove = mapOf('A' to Rock, 'B' to Paper, 'C' to Scissors)[opponentInput]!! val intendedOutcome = mapOf('X' to Lose, 'Y' to Draw, 'Z' to Win)[advisedOutcome]!! return when (opponentMove to intendedOutcome) { Rock to Lose -> 'Z' Rock to Draw -> 'X' Rock to Win -> 'Y' Paper to Lose -> 'X' Paper to Draw -> 'Y' Paper to Win -> 'Z' Scissors to Lose -> 'Y' Scissors to Draw -> 'Z' Scissors to Win -> 'X' else -> 'X' } } fun main() { fun part1(input: List<String>): Int = parseInput(input) .map { getRoundResult(it[0], it[1]) } .sum() fun part2(input: List<String>): Int = parseInput(input) .map { getRoundResult(it[0], getMoveForOutcome(it[0], it[1])) } .sum() val input = readInput("Day02") assert(getRoundResult('A', 'Y') == 8) assert(getRoundResult('B', 'X') == 1) assert(getRoundResult('C', 'Z') == 6) println("Part 1: ${part1(input)}") assert(getRoundResult('A', getMoveForOutcome('A', 'Y')) == 4) assert(getRoundResult('B', getMoveForOutcome('B', 'X')) == 1) assert(getRoundResult('C', getMoveForOutcome('C', 'Z')) == 7) println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
cd7e0da85f71d40bc7e3761f16ecfdce8164dae6
2,287
advent-of-code-22
Apache License 2.0
src/day05/Day05Answer1.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day05 import readInput /** * Answers from [Advent of Code 2022 Day 5 | Kotlin](https://youtu.be/lKq6r5Nt8Yo) */ fun main() { val lines = readInput("day05") val day05 = Day05() // Calculate number of stacks needed val numberOfStacks = day05.numberOfStacks(lines) val stacks = List(numberOfStacks) { ArrayDeque<Char>() } // Fill the stacks day05.populateStacks(lines) { stackNumber, value -> stacks[stackNumber].addLast(value) } // Get the moves val moves = lines.filter { it.contains("move") }.map { Move.of(it) } // Perform the moves println(day05.partOne(stacks.map { ArrayDeque(it) }, moves)) // BZLVHBWQF println(day05.partTwo(stacks, moves)) // TDGJQTZSL } class Day05 { fun numberOfStacks(lines: List<String>): Int { return lines .dropWhile { it.contains("[") } .first() .split(" ") .filter { it.isNotBlank() } .maxOf { it.toInt() } } fun partOne(stacks: List<ArrayDeque<Char>>, moves: List<Move>): String { moves.forEach { step -> repeat(step.quantity) { stacks[step.target].addFirst(stacks[step.source].removeFirst()) } } return stacks.map { it.first() }.joinToString(separator = "") } fun partTwo(stacks: List<ArrayDeque<Char>>, moves: List<Move>): String { moves.map { step -> stacks[step.source] .subList(0, step.quantity) .asReversed() .onEach { stacks[step.target].addFirst(it) } .onEach { stacks[step.source].removeFirst() } } return stacks.map { it.first() }.joinToString(separator = "") } fun populateStacks(lines: List<String>, onCharacterFound: (Int, Char) -> Unit) { lines .filter { it.contains("[") } .map { line -> line.mapIndexed { index, char -> if (char.isLetter()) { val stackNumber = index / 4 val value = line[index] onCharacterFound(stackNumber, value) } } } } } data class Move(val quantity: Int, val source: Int, val target: Int) { companion object { fun of(line: String): Move { return line .split(" ") .filterIndexed { index, _ -> index % 2 == 1 } .map { it.toInt() } .let { Move(it[0], it[1] - 1, it[2] - 1) } } } }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
2,560
advent-of-code-2022
Apache License 2.0
src/Day07.kt
mkulak
573,910,880
false
{"Kotlin": 14860}
fun main() { fun part1(input: List<String>): Long { val root = Dir("/", null) var currentDir = root input.forEach { line -> when { line == "\$ cd .." -> currentDir = currentDir.parent!! line == "\$ cd /" -> currentDir = root line.startsWith("\$ cd ") -> { val newDir = Dir(line.drop(5), currentDir) currentDir.subDirs += newDir currentDir = newDir } line == "\$ ls" -> {} line.startsWith("dir ") -> {} else -> { val size = line.takeWhile { it.isDigit() }.toInt() currentDir.addFileSize(size) } } } suspend fun SequenceScope<Dir>.iterate(dir: Dir) { yield(dir) dir.subDirs.forEach { iterate(it) } } val allDirs = sequence { iterate(root) } return allDirs.filter { it.filesSize <= 100000 }.sumOf { it.filesSize } } fun part2(input: List<String>): Long { val root = Dir("/", null) var currentDir = root input.forEach { line -> when { line == "\$ cd .." -> currentDir = currentDir.parent!! line == "\$ cd /" -> currentDir = root line.startsWith("\$ cd ") -> { val newDir = Dir(line.drop(5), currentDir) currentDir.subDirs += newDir currentDir = newDir } line == "\$ ls" -> {} line.startsWith("dir ") -> {} else -> { val size = line.takeWhile { it.isDigit() }.toInt() currentDir.addFileSize(size) } } } val total = 70000000 val requiredFree = 30000000 val currentFree = total - root.filesSize val deleteAtLeast = requiredFree - currentFree val allDirs = generateSequence(listOf(root)) { dirs -> dirs.flatMap { it.subDirs }.takeIf { it.isNotEmpty() } }.flatten() return allDirs.filter { it.filesSize >= deleteAtLeast }.minBy { it.filesSize }.filesSize } val input = readInput("Day07") println(part1(input)) println(part2(input)) } data class Dir( val name: String, val parent: Dir?, var filesSize: Long = 0, val subDirs: MutableList<Dir> = ArrayList() ) { fun addFileSize(value: Int) { filesSize += value parent?.addFileSize(value) } override fun toString(): String = "[$name $filesSize]" } fun printDirTree(dir: Dir, indent: Int = 0) { println(" ".repeat(indent) + "${dir.name} ${dir.filesSize}") dir.subDirs.forEach { printDirTree(it, indent + 4) } }
0
Kotlin
0
0
3b4e9b32df24d8b379c60ddc3c007d4be3f17d28
2,828
AdventOfKo2022
Apache License 2.0
src/Day05.kt
manuel-martos
574,260,226
false
{"Kotlin": 7235}
import java.util.* fun main() { println("part01 -> ${solveDay05Part01()}") println("part02 -> ${solveDay05Part02()}") } private fun solveDay05Part01(): String = solver(::applyMovements) private fun solveDay05Part02(): String = solver(::applyMultipleMovements) private fun solver(block: (Map<Int, LinkedList<Char>>, List<Triple<Int, Int, Int>>) -> Unit): String { val input = readInput("day05") val index = input.indexOf("") val stacks = input.subList(0, index) val movements = input.subList(index + 1, input.size) val parsedStacks = parseStacks(stacks) val parsedMovements = parseMovements(movements) block(parsedStacks, parsedMovements) return parsedStacks.keys.sorted().joinToString(separator = "") { parsedStacks[it]!!.first().toString() } } private fun parseStacks(stackConfig: List<String>): Map<Int, LinkedList<Char>> { val stackIds = stackConfig .last() .split(" ") .map { try { it.toInt() } catch (e: Throwable) { "" } } .filterIsInstance<Int>() val result = stackIds.associateWith { LinkedList<Char>() } val items = stackConfig.reversed().subList(1, stackConfig.size) items.forEach { for (entry in result.entries) { val startIndex = (entry.key - 1) * 4 + 1 val endIndex = (entry.key - 1) * 4 + 2 val content = it.substring(startIndex, endIndex)[0] if (content.isLetter()) { entry.value.push(content) } } } return result } private fun parseMovements(movements: List<String>): List<Triple<Int, Int, Int>> { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() return movements .map { val groups = regex.find(it)?.groupValues ?: error("Nope") groups.subList(1, groups.size).map(String::toInt) } .map { Triple(it[0], it[1], it[2]) } } private fun applyMovements(stacks: Map<Int, LinkedList<Char>>, movements: List<Triple<Int, Int, Int>>) { movements.forEach { val source = it.second val target = it.third repeat(it.first) { stacks[target]!!.push(stacks[source]!!.pop()) } } } private fun applyMultipleMovements(stacks: Map<Int, LinkedList<Char>>, movements: List<Triple<Int, Int, Int>>) { movements.forEach { val source = it.second val target = it.third val temp = LinkedList<Char>() repeat(it.first) { temp.push(stacks[source]!!.pop()) } repeat(it.first) { stacks[target]!!.push(temp.pop()) } } }
0
Kotlin
0
0
5836682fe0cd88b4feb9091d416af183f7f70317
2,689
advent-of-code-2022
Apache License 2.0
src/Day02.kt
ked4ma
573,017,240
false
{"Kotlin": 51348}
import java.lang.RuntimeException /** * [Day02](https://adventofcode.com/2022/day/2) */ fun main() { fun judge(self: Shape, opponent: Shape): Int = when { self.winTo() == opponent -> 6 self == opponent -> 3 else -> 0 } fun part1(input: List<String>): Int { fun convToStrategies(input: List<String>): List<Pair<Shape, Shape>> = input.map { it.split(" ").let { (l, r) -> Shape.parse(l) to Shape.parse(r) } } val strategy = convToStrategies(input) return strategy.sumOf { (opponent, self) -> judge(self, opponent) + self.score } } fun part2(input: List<String>): Int { fun convToStrategies(input: List<String>): List<Pair<Shape, String>> = input.map { it.split(" ").let { (l, r) -> Shape.parse(l) to r } } val strategy = convToStrategies(input) return strategy.sumOf { (opponent, str) -> val self = when (str) { "X" -> opponent.winTo() "Y" -> opponent "Z" -> opponent.loseTo() else -> throw RuntimeException() } judge(self, opponent) + self.score } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } private enum class Shape(val score: Int) { Rock(1) { override fun winTo() = Scissors override fun loseTo() = Paper }, Paper(2) { override fun winTo() = Rock override fun loseTo() = Scissors }, Scissors(3) { override fun winTo() = Paper override fun loseTo() = Rock }; abstract fun winTo(): Shape abstract fun loseTo(): Shape companion object { fun parse(s: String) = when (s) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw RuntimeException() } } }
1
Kotlin
0
0
6d4794d75b33c4ca7e83e45a85823e828c833c62
2,179
aoc-in-kotlin-2022
Apache License 2.0
src/Day04.kt
meierjan
572,860,548
false
{"Kotlin": 20066}
import Interval.Companion.parseLine data class Interval( val from: Int, val to: Int, ) { fun fullyContains(other: Interval) : Boolean { return this.from <= other.from && this.to >= other.to } fun overlap(other: Interval) : Boolean { return if(this.from <= other.from) { this.to >= other.from } else { other.to >= this.from } } companion object { fun parse(text: String): Interval { val sides = text.split("-") return Interval( sides[0].toInt(), sides[1].toInt() ) } fun parseLine(line: String) : Pair<Interval, Interval> { val splitLine = line.split(",") return Pair(parse(splitLine[0]), parse(splitLine[1])) } } } fun day4_part1(input: List<String>): Int = input.map { parseLine(it) } .map { it.first.fullyContains(it.second) || it.second.fullyContains(it.first)} .count { it } fun day4_part2(input: List<String>): Int = input.map { parseLine(it) } .map { it.first.overlap(it.second)} .count { it } fun main() { // // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_1_test") println(day4_part1(testInput)) check(day4_part1(testInput) == 2) val input = readInput("Day04_1") println(day4_part1(input)) println(day4_part2(testInput)) check(day4_part2(testInput) == 4) println(day4_part2(input)) }
0
Kotlin
0
0
a7e52209da6427bce8770cc7f458e8ee9548cc14
1,540
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2023/src/Day11.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import lib.matrix.Matrix import lib.matrix.Position import kotlin.math.abs private typealias SpaceImage = Matrix<Char> private const val DAY = "Day11" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 374 measureAnswer { part1(input()) } } "Part 2" { solve(testInput(), shiftMultiplier = 100) shouldBe 8410 measureAnswer { part2(input()) } } } private fun part1(space: SpaceImage) = solve(space, shiftMultiplier = 2) private fun part2(space: SpaceImage) = solve(space, shiftMultiplier = 1_000_000) private fun solve(space: SpaceImage, shiftMultiplier: Int): Long { return findGalaxies(space, calculateShift = { it * (shiftMultiplier - 1) }) .combinations() .sumOf { (galaxyA, galaxyB) -> (galaxyA distanceTo galaxyB).toLong() } } // Can I make this method more clear? private fun findGalaxies(space: SpaceImage, calculateShift: (Int) -> Int): List<Position> = buildList { val emptyRows = space.rowIndices.filterAllEmpty(space::row) val emptyColumns = space.columnIndices.filterAllEmpty(space::column) var emptyRowsCount = 0 for (row in space.rowIndices) { if (row in emptyRows) { emptyRowsCount++ } else { var emptyColumnsCount = 0 for (col in space.columnIndices) { if (space[row, col] == '#') { val position = Position( row + calculateShift(emptyRowsCount), col + calculateShift(emptyColumnsCount), ) add(position) } else if (col in emptyColumns) { emptyColumnsCount++ } } } } } private fun IntRange.filterAllEmpty(chars: (Int) -> List<Char>): Set<Int> { return filterTo(mutableSetOf()) { i -> chars(i).all { it == '.' } } } private fun readInput(name: String) = readMatrix(name) // region Utils private fun <T> List<T>.combinations(): Sequence<Pair<T, T>> = sequence { for (i in 0..<lastIndex) { for (j in (i + 1)..lastIndex) { yield(get(i) to get(j)) } } } private infix fun Position.distanceTo(other: Position): Int { return abs(this.row - other.row) + abs(this.column - other.column) } // endregion
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,380
advent-of-code
Apache License 2.0
src/main/kotlin/dp/WeaklyInc.kt
yx-z
106,589,674
false
null
package dp import util.get import util.max import util.set // longest weakly increasing subsequence // X[1..n] is weakly increasing if 2 * X[i] > X[i - 1] + X[i - 2], for all i > 2 // find the length of longest weakly increasing subsequence of A[1..n] fun main(args: Array<String>) { val A = intArrayOf(1, 2, 3, 3, 3, 4) println(wis(A)) // [1, 2, 3, 3, 4] -> 5 } fun wis(A: IntArray): Int { val n = A.size if (n < 3) { return n } // dp(i, j): len of lwis of A with first two elements A[i] and A[j] // assume max{ } = 0 // dp(i, j) = 0 if i, j !in 0 until n || i >= j // = 2 if j = n // = 1 + max{ dp(j, k) } where k in j + 1 until n and 2 * A[k] > A[j] + A[i] o/w // we want max{ dp(i, j) } var max = Int.MIN_VALUE // use a 2d array dp[1..n, 1..n] : dp[i, j] = dp(i, j) // space complexity: O(n^2) val dp = Array(n) { IntArray(n) } // base case, a special case of wis when the length is only 2 for (i in 0 until n) { dp[i, n - 1] = 2 } // dp(i, j) depends on dp(j, k) for all k > j // so the evaluation order should be i from bottom up, i.e. n to 1 // , and j from right to left, i.e. n to i + 1 // time complexity: O(n^2 * n) = O(n^3) for (i in n - 3 downTo 0) { for (j in n - 2 downTo i + 1) { dp[i, j] = 1 + (dp[j] .filterIndexed { k, _ -> k in j + 1 until n && 2 * A[k] > A[j] + A[i] } .max() ?: 0) max = max(max, dp[i, j]) } } return max }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,424
AlgoKt
MIT License
aoc-2023/src/main/kotlin/aoc/aoc25.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.getDayInput import aoc.util.pairwise import aoc.util.second import aoc.util.triples val testInput = """ jqt: rhn xhk nvd rsh: frs pzl lsr xhk: hfx cmg: qnr nvd lhk bvb rhn: xhk bvb hfx bvb: xhk hfx pzl: lsr hfx nvd qnr: nvd ntq: jqt hfx bvb xhk nvd: lhk lsr: lhk rzs: qnr cmg lsr rsh frs: qnr lhk lsr """.parselines fun Map<String, Set<String>>.symmetric(): Map<String, Set<String>> { val sym = mutableMapOf<String, MutableSet<String>>() forEach { (k, v) -> sym.getOrPut(k) { mutableSetOf() }.addAll(v) v.forEach { vv -> sym.getOrPut(vv) { mutableSetOf() }.add(k) } } return sym } class Graph(val links: Map<String, Set<String>>) { val vertices get() = links.keys + links.values.flatten().toSet() val wires get() = links.entries.flatMap { (k, v) -> v.map { setOf(k, it) } }.toSet() fun neighborhood(v: String, dist: Int, disallow: String? = null): Set<String> { if (dist == 0) return setOf(v) val adj = links[v]!! - setOfNotNull(disallow) return adj + adj.flatMap { neighborhood(it, dist - 1, disallow) } } fun components(): Set<Set<String>> { var comps = vertices.map { setOf(it) }.toSet() links.forEach { (v, adj) -> val joinComps = comps.filter { it.contains(v) || it.intersect(adj).isNotEmpty() }.toSet() val joined = joinComps.flatten().toSet() comps = (comps - joinComps) + setOf(joined) } return comps.toSet() } fun cutWires(wires: Set<Set<String>>): Graph { val newLinks = links.mapValues { (v, adj) -> adj - wires.filter { v in it }.flatten().toSet() } return Graph(newLinks) } fun triangles(): Set<Set<String>> { return vertices.flatMap { v -> links[v]!!.toList().pairwise().filter { it.first() in links[it.second()]!! }.map { setOf(v, it.first(), it.second()) } }.toSet() } } // part 1 fun String.parse() = substringBefore(":") to substringAfter(":").trim().split(" ").map { it.trim() }.toSet() var i = 0 fun List<String>.part1(): Int { val links = associate { it.parse() }.symmetric() val graph = Graph(links) // do some stats with neighborhood sizes to see if something stands out // (2..5).forEach { dist -> // val nbhds = graph.vertices.associateWith { graph.neighborhood(it, dist) } // println("Vertex neighborhoods of distance $dist: " + nbhds.mapValues { it.value.size }.entries.sortedByDescending { it.value }) // } // do some stats with wire neighborhoods (both ends) to see if something stands out // (2..5).forEach { dist -> // val nbhds = graph.wires.associateWith { graph.neighborhood(it.first(), dist) + graph.neighborhood(it.second(), dist) } // println("Wire neighborhoods of distance $dist: " + nbhds.mapValues { it.value.size }.entries.sortedByDescending { it.value }) // } // do some stats with wire neighborhoods (intersection of nbhds if we remove the wire) to see if something stands out (2..4).forEach { dist -> val nbhds = graph.wires.associateWith { val n1 = graph.neighborhood(it.first(), dist, disallow = it.second()) val n2 = graph.neighborhood(it.second(), dist, disallow = it.first()) n1.intersect(n2) } println("Wire intersecting neighborhoods of distance $dist: " + nbhds.mapValues { it.value.size }.entries.sortedBy { it.value }.take(50) + "...") } val wiresBySize = graph.wires.associateWith { val n1 = graph.neighborhood(it.first(), dist = 4, disallow = it.second()) val n2 = graph.neighborhood(it.second(), dist = 4, disallow = it.first()) n1.intersect(n2) }.entries.sortedBy { it.value.size }.map { it.key } var indexSum = 3 var check = 0 while (true) { (0..minOf(indexSum, wiresBySize.size - 1)).forEach { i1 -> val wire1 = wiresBySize[i1] val graph1 = graph.cutWires(setOf(wire1)) (i1+1..minOf(indexSum, wiresBySize.size - 1)).forEach { i2 -> val i3 = indexSum - i1 - i2 if (i3 > i2 && i3 < wiresBySize.size) { val wire2 = wiresBySize[i2] val wire3 = wiresBySize[i3] val toCut = setOf(wire1, wire2, wire3) if (toCut.flatten().size == 6) { check++ val redGraph = graph1.cutWires(setOf(wire2, wire3)) val comps = redGraph.components() if (comps.size == 2) { println("After $check iterations, cutting $toCut leaves ${comps.size} components") if (comps.first().size < 100) { println(" First component: ${comps.first()}") println(" Second component: ${comps.second()}") } return comps.first().size * comps.second().size } } } } } indexSum++ } } fun List<String>.part1b(): Int { val links = associate { it.parse() }.symmetric() val graph = Graph(links) graph.wires.toList().triples().filter { it.flatten().toSet().size == 6 }.forEach { i++ val redGraph = graph.cutWires(it) val comps = redGraph.components() if (comps.size == 2) { println("Cutting $it leaves ${comps.size} components: $comps") return comps.first().size * comps.second().size } } return -1 } // part 2 fun List<String>.part2() = "<NAME>mas!" // calculate answers val day = 25 val input = getDayInput(day, 2023) val testResult = testInput.part1().also { it.print } val testResult2 = testInput.part2().also { it.print } val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
6,244
advent-of-code
Apache License 2.0
src/day11/Day11.kt
TheJosean
573,113,380
false
{"Kotlin": 20611}
package day11 import readInput import splitList fun main() { data class Monkey( val id: Int, var items: MutableList<Int>, val divisibleBy: Int, val onTrue: Int, val onFalse: Int, val operation: (value: Long) -> Long, var inspects: Long = 0 ) fun parseMonkey(input: List<String>): Monkey { val (_, id) = input[0].split(' ') val (_, items) = input[1].split("Starting items: ") val (_, operation) = input[2].split("Operation: new = old ") val divisible = input[3].split(' ').last() val onTrue = input[4].split(' ').last() val onFalse = input[5].split(' ').last() return Monkey( id = id.dropLast(1).toInt(), items = items.split(", ").map { it.toInt() }.toMutableList(), divisibleBy = divisible.toInt(), onTrue = onTrue.toInt(), onFalse = onFalse.toInt(), operation = { value -> val (op, number) = operation.split(' ') val amount = number.toLongOrNull() ?: value when(op) { "+" -> value + amount "*" -> value * amount else -> value } } ) } fun getMonkeys(input: List<String>): Map<Int, Monkey> { return splitList(input) .map { parseMonkey(it) }.associateBy { it.id } } fun run(monkeys: Map<Int, Monkey>, rounds: Int, dividedBy: Int, module: Int): Long { (1..rounds).forEach { _ -> monkeys.values.forEach { it.inspects += it.items.size it.items.forEach { item -> var worryLevel = it.operation.invoke(item.toLong()) / dividedBy if (module != 0) worryLevel %= module monkeys.getValue(if (worryLevel % it.divisibleBy == 0L) it.onTrue else it.onFalse).items.add(worryLevel.toInt()) } it.items.clear() } } val (a, b) = monkeys.values.map { it.inspects }.sortedDescending().take(2) return a * b } fun part1(input: List<String>) = run(getMonkeys(input), 20, 3, 0) fun part2(input: List<String>) = getMonkeys(input).let { monkeys -> run(monkeys, 10000, 1, monkeys.values.map { it.divisibleBy }.reduce { acc, l -> acc * l}.toInt()) } // test if implementation meets criteria from the description, like: val testInput = readInput("/day11/Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("/day11/Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
798d5e9b1ce446ba3bac86f70b7888335e1a242b
2,719
advent-of-code
Apache License 2.0
src/Day08/Day08.kt
brhliluk
572,914,305
false
{"Kotlin": 16006}
fun main() { fun List<Int>.takeWhileInclusive(pred: (Int) -> Boolean): List<Int> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = pred(it) result } } fun List<Int>.takeLastWhileInclusive(pred: (Int) -> Boolean): List<Int> { var shouldContinue = true return takeLastWhile { val result = shouldContinue shouldContinue = pred(it) result } } fun <T> List<List<T>>.getColumn(index: Int): List<T> { val result = mutableListOf<T>() forEachIndexed { i, elemList -> result.add(elemList[index]) } return result } fun isVisible(row: List<Int>, index: Int): Boolean { if (index == 0 || index == row.size - 1) return true val leftMax = row.subList(0, index).max() val rightMax = row.subList(index + 1, row.size).max() val element = row[index] return element > rightMax || element > leftMax } fun isVisible(row: List<Int>, column: List<Int>, rowIdx: Int, columnIdx: Int) = isVisible(row, rowIdx) || isVisible(column, columnIdx) fun scenicScore(row: List<Int>, index: Int): Int { val tree = row[index] val leftTrees = if (index == 0) listOf() else row.subList(0, index) val rightTrees = if (index == row.size - 1) listOf() else row.subList(index + 1, row.size) val leftVisible = if (leftTrees.isEmpty()) leftTrees else leftTrees.takeLastWhileInclusive { it < tree } val rightVisible = if (rightTrees.isEmpty()) rightTrees else rightTrees.takeWhileInclusive { it < tree } return leftVisible.size * rightVisible.size } fun scenicScore(row: List<Int>, column: List<Int>, rowIdx: Int, columnIdx: Int) = scenicScore(row, rowIdx) * scenicScore(column, columnIdx) fun part1(input: List<String>): Int { val visibleTrees = mutableListOf<String>() val array = input.map { row -> row.toCharArray().map { it.digitToInt() } } array.forEachIndexed { i, trees -> trees.forEachIndexed { j, tree -> if (isVisible(trees, array.getColumn(j), j, i)) visibleTrees.add("$i$j") } } return visibleTrees.size } fun part2(input: List<String>): Int { val scores = mutableListOf<Int>() val array = input.map { row -> row.toCharArray().map { it.digitToInt() } } array.forEachIndexed { i, trees -> trees.forEachIndexed { j, tree -> scores.add(scenicScore(trees, array.getColumn(j), j, i)) } } return scores.max() } val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
96ac4fe0c021edaead8595336aad73ef2f1e0d06
2,830
kotlin-aoc
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day14.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import twentytwentytwo.Structures.Point2d fun main() { val input = {}.javaClass.getResource("input-14.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val day = Day14(input) println(day.part1()) println(day.part2()) } class Day14(val input: List<String>) { private val origin: Point2d = Point2d(500, 0) fun part1(): Int { val grid = createGrid(getRocks(input)) drop(origin, grid) return grid.sumOf { it.count { c -> c == 'o' } } } fun part2(): Int { val rocks = getRocks(input) val y = rocks.maxBy { it.y }.y + 2 val extended = rocks + (Point2d(500 - y , y).lineTo(Point2d(500 + y, y))) val grid = createGrid(extended) drop(origin, grid) return grid.sumOf { it.count { c -> c == 'o' } } } private fun drop(source: Point2d, grid: Array<CharArray>) { var point = source while (point.down in grid && grid[point] != 'o') { when { grid[point.down] !in rockOrSand -> { point = point.down } grid[point.downLeft] !in rockOrSand -> { point = point.downLeft } grid[point.downRight] !in rockOrSand -> { point = point.downRight } else -> { grid[point] = 'o' point = source } } } } private fun createGrid(rocks: List<Point2d>): Array<CharArray> { val maxX = rocks.maxBy { it.x }.x val maxY = rocks.maxBy { it.y }.y val grid: Array<CharArray> = (0..maxY).map { CharArray(maxX + 2).apply { fill('.') } }.toTypedArray() rocks.forEach { rock -> grid[rock] = '#' } return grid } private fun getRocks(input: List<String>): List<Point2d> { return input.flatMap { row -> val points = row.split(" -> ").map { p -> p.split(",").map { it.toInt() } }.map { (x, y) -> Point2d(x, y) } points.windowed(2, 1).map { (from, to) -> from lineTo to }.flatten() } } companion object { private val rockOrSand = setOf('#', 'o') } private operator fun Array<CharArray>.get(point: Point2d): Char = this[point.y][point.x] private operator fun Array<CharArray>.set(point: Point2d, to: Char) { this[point.y][point.x] = to } private operator fun Array<CharArray>.contains(point: Point2d): Boolean = point.x >= 0 && point.x < this[0].size && point.y >= 0 && point.y < this.size }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
2,670
aoc202xkotlin
The Unlicense
src/day02/Day02.kt
gagandeep-io
573,585,563
false
{"Kotlin": 9775}
package day02 import readInput fun main() { fun part1(input: List<String>): Int { fun scoreForShape(shape: Char): Int = shape - 'X' + 1 fun scoreForRound(theirShape: Char, myShape: Char): Int = when(theirShape to myShape) { 'B' to 'X', 'C' to 'Y', 'A' to 'Z' -> 0 'A' to 'X', 'B' to 'Y', 'C' to 'Z' -> 3 'C' to 'X', 'A' to 'Y', 'B' to 'Z' -> 6 else -> error("Invalid move choices") } return input.sumOf { round -> val (theirShape, _ , myShape) = round scoreForShape(myShape) + scoreForRound(theirShape, myShape) } } fun part2(input: List<String>): Int { fun Char.beats() : Char = when(this) { 'B' -> 'A' 'C' -> 'B' 'A' -> 'C' else -> error("Invalid shape") } fun Char.beatenBy() : Char = 'A' + (((this - 'A') + 1) % 3) fun scoreForShape(shape: Char): Int = shape - 'A' + 1 fun chooseMyShape(theirShape: Char, expectedResult: Char): Char = when(expectedResult) { 'X' -> theirShape.beats() 'Y' -> theirShape 'Z' -> theirShape.beatenBy() else -> error("invalid shape") } fun scoreForRound(expectedResult: Char): Int = (expectedResult - 'X') * 3 return input.sumOf { round -> val (theirShape, _ , expectedResult) = round val myShape = chooseMyShape(theirShape, expectedResult) scoreForShape(myShape) + scoreForRound(expectedResult) } } val input = readInput("Day02_test") println(part1(input)) println(part2(input)) } private operator fun String.component1(): Char = this[0] private operator fun String.component2(): Char = this[1] private operator fun String.component3(): Char = this[2]
0
Kotlin
0
0
952887dd94ccc81c6a8763abade862e2d73ef924
1,834
aoc-2022-kotlin
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day02.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput("Day02") Day02.part1(input).println() Day02.part2(input).println() } object Day02 { private val gameIdPattern = "(Game) (\\d+)".toRegex().toPattern() private val greenPattern = "(\\d+) (green)".toRegex().toPattern() private val bluePattern = "(\\d+) (blue)".toRegex().toPattern() private val redPattern = "(\\d+) (red)".toRegex().toPattern() fun part1(input: List<String>): Int { return input .filter { game -> game.split(";") .all { isValid(it) } } .sumOf { extractGameId(it) } } fun part2(input: List<String>): Int { return input .sumOf { game -> calculatePower(game) } } private fun isValid( it: String, maxBlue: Int = 14, maxGreen: Int = 13, maxRed: Int = 12 ): Boolean { val blueMatcher = bluePattern.matcher(it) val redMatcher = redPattern.matcher(it) val greenMatcher = greenPattern.matcher(it) val blue = if (blueMatcher.find()) blueMatcher.group(1).toInt() else 0 val red = if (redMatcher.find()) redMatcher.group(1).toInt() else 0 val green = if (greenMatcher.find()) greenMatcher.group(1).toInt() else 0 return blue <= maxBlue && green <= maxGreen && red <= maxRed } private fun extractGameId(set: String): Int { val gameIdMatcher = gameIdPattern.matcher(set) return when { !gameIdMatcher.find() -> 0 else -> gameIdMatcher.group(2).toInt() } } private fun calculatePower(game: String): Int { var maxBlue = 0 var maxRed = 0 var maxGreen = 0 for (set in game.split(";")) { val blueMatcher = bluePattern.matcher(set) if (blueMatcher.find()) { val blue = blueMatcher.group(1).toInt() if (blue > maxBlue) { maxBlue = blue } } val redMatcher = redPattern.matcher(set) if (redMatcher.find()) { val red = redMatcher.group(1).toInt() if (red > maxRed) { maxRed = red } } val greenMatcher = greenPattern.matcher(set) if (greenMatcher.find()) { val green = greenMatcher.group(1).toInt() if (greenMatcher.group(1).toInt() > maxGreen) { maxGreen = green } } } return maxGreen * maxRed * maxBlue } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
2,660
advent-of-code
MIT License
src/Day03.kt
AndreiShilov
572,661,317
false
{"Kotlin": 25181}
fun main() { fun intersectSum(intersect: Set<Char>) = intersect .map { charInIntersect: Char -> charInIntersect.code } .map { code -> println("Code ${code}") val i = when (code) { in 97..122 -> code - 96 in 65..90 -> code - 64 + 26 else -> throw IllegalStateException("Boom") } println(i) i }.sum() fun part1(input: List<String>): Int { return input.map { val length = it.length val split = length / 2 val firstBag = it.substring(0, split).toCharArray() val secondBag = it.substring(split).toCharArray() println("First [${String(firstBag)}] Second [${String(secondBag)}]") val intersect = firstBag.intersect(secondBag.asIterable().toSet()) println("Intersect [$intersect]") intersectSum(intersect) }.sum() } fun part2(input: List<String>): Int { return input.chunked(3).map { val first = it[0].toCharArray() val second = it[1].toCharArray() val third = it[2].toCharArray() first.intersect(second.toSet()).intersect(third.toSet()) val intersect = first.intersect(second.toSet()).intersect(third.toSet()) println("Intersect [$intersect]") intersectSum(intersect) }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
852b38ab236ddf0b40a531f7e0cdb402450ffb9a
1,725
aoc-2022
Apache License 2.0
src/Day12.kt
jinie
572,223,871
false
{"Kotlin": 76283}
class Day12 { fun part1(input:List<String>): Int = parseMap(input) .let { (map, start, end) -> findShortestPath(mutableListOf(map[start]!!), map, end) } fun part2(input:List<String>): Int = parseMap(input) .let { (map, _, end) -> map.values .filter { it.height == 'a' } .map { findShortestPath(mutableListOf(it), parseMap(input).first, end) } .minOf { it } } private fun parseMap(input:List<String>): Triple<Map<Point2d,Point>,Point2d,Point2d>{ val map = mutableMapOf<Point2d, Point>() var start = Point2d(-1,-1) var end = Point2d(-1, -1) input.forEachIndexed{ y, line -> line.toCharArray().forEachIndexed { x, c -> when(c) { 'S' -> { start = Point2d(x,y); map[start] = Point(coordinates = start, height = 'a')} 'E' -> { end = Point2d(x,y); map[end] = Point(coordinates = end, height = 'z')} else -> {val pt = Point2d(x,y); map[pt] = Point(coordinates = pt, height = c)} } } } return Triple(map, start, end) } private fun findShortestPath(toVisit: MutableList<Point>, allNodes: Map<Point2d, Point>, end: Point2d): Int{ var steps = 0 while(toVisit.isNotEmpty()) { steps++ val nextStop = mutableSetOf<Point>() toVisit.forEach{ point -> point.coordinates.neighbors().filter{ it in allNodes }.filter{ allNodes[it]!!.height.code <= point.height.code+1}.filter{ !allNodes[it]!!.visited }.forEach { nextStop.add(allNodes[it]!!) } point.visited = true } if(nextStop.any { it.coordinates == end }) return steps else{ toVisit.clear() toVisit.addAll(nextStop) } } return Int.MAX_VALUE } } data class Point( val coordinates: Point2d, val height: Char, var visited: Boolean = false ) fun main() { measureTimeMillisPrint { val input = readInput("Day12") println(Day12().part1(input)) println(Day12().part2(input)) } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
2,287
aoc-22-kotlin
Apache License 2.0
2021/src/day06/Day06.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day06 import readInput fun part1(lines: List<String>) : Int { val fishes = lines.first().split(",").map{ it.toInt() }.toMutableList() val iterations = 80 for (i in 1..iterations) { var numberAdded = 0 for (idx in fishes.indices) { when (fishes[idx]) { 0 -> { fishes[idx] = 6 numberAdded++ } else -> fishes[idx]-- } } fishes.addAll(List(numberAdded) { 8 }) } return fishes.size } fun part2(lines: List<String>) : Long { val initial = lines.first().split(",").map{ it.toInt() }.toMutableList() val fishes = LongArray(9) { 0 } // from 0 to 8 included val iterations = 256 for (fish in initial) fishes[8 - fish]++ for (i in 1..iterations) { val babies = fishes[8] for (j in 8 downTo 1) { fishes[j] = fishes[j - 1] } fishes[0] = babies fishes[8 - 6] += babies } return fishes.sum() } fun main() { val testInput = readInput("day06/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day06/input") println("part1(input) => " + part1(input)) println("part1(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,346
advent-of-code
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day14/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day14 import com.kingsleyadio.adventofcode.util.readInput private fun solution(template: String, map: Map<String, Char>, steps: Int): Long { val mem = hashMapOf<String, Map<Char, Long>>() fun memo(a: Char, b: Char, step: Int, func: (Char, Char, Int) -> Map<Char, Long>): Map<Char, Long> { val key = "$a$b-$step" return mem.getOrPut(key) { func(a, b, step) } } fun Map<Char, Long>.mergeTo(other: MutableMap<Char, Long>) { forEach { (char, count) -> other[char] = other.getOrDefault(char, 0) + count } } fun synthesize(a: Char, b: Char, step: Int): Map<Char, Long> { if (step == 0) return emptyMap() val product = map.getValue("$a$b") return buildMap { put(product, 1L) memo(a, product, step - 1, ::synthesize).mergeTo(this) memo(product, b, step - 1, ::synthesize).mergeTo(this) } } val counter = hashMapOf<Char, Long>() for (char in template) counter[char] = counter.getOrDefault(char, 0) + 1 template.zipWithNext { a, b -> memo(a, b, steps, ::synthesize).mergeTo(counter) } val counts = counter.values.sorted() return counts.last() - counts.first() } fun main() { readInput(2021, 14).useLines { lines -> val iterator = lines.iterator() val template = iterator.next() iterator.next() val map = buildMap { for (line in iterator) line.split(" -> ").let { (k, v) -> put(k, v[0]) } } println(solution(template, map, 10)) println(solution(template, map, 40)) } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,605
adventofcode
Apache License 2.0
src/Day05.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution05(val input: List<String>) { private val moves = ArrayList<Triple<Int, Int, Int>>() private var stacks = ArrayList<ArrayDeque<Char>>() fun init() { val separatorIndex = input.indexOfFirst { it.isBlank() } val numberOfStacks = input[separatorIndex - 1].split(" ").count { it.isNotBlank() } stacks.clear() for (i in (1..numberOfStacks)) stacks.add(ArrayDeque()) for (line in input.subList(0, separatorIndex - 1)) { for (s in 0..(line.length / 4)) { val item = line[s * 4 + 1] if (item.isLetter()) stacks[s].addFirst(item) } } moves.clear() for (line in input.subList(separatorIndex + 1, input.size)) { val splitted = line.split(" ") moves.add(Triple(splitted[1].toInt(), splitted[3].toInt(), splitted[5].toInt())) } } private fun doMove(move: Triple<Int, Int, Int>, reverseBatch: Boolean) { val from = move.second val to = move.third val size = move.first val batch = ArrayList<Char>() for (i in 0 until size) { batch.add(stacks[from - 1].last()) stacks[from - 1].removeLast() } if (reverseBatch) batch.reverse() for (item in batch) stacks[to - 1].addLast(item) } fun part1() : String { init() moves.forEach { doMove(it, false) } return stacks.map { if (it.isEmpty()) ' ' else it.last() }.joinToString("") } fun part2(): String { init() moves.forEach { doMove(it, true) } return stacks.map { if (it.isEmpty()) ' ' else it.last() }.joinToString("") } } fun main() { val testSolution = Solution05(readInput("Day05_test")) check(testSolution.part1() == "CMZ") check(testSolution.part2() == "MCD") val solution = Solution05(readInput("Day05")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
1,980
aoc-2022
Apache License 2.0
src/aoc2023/Day05.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInputText fun main() { val (year, day) = "2023" to "Day05" fun fillMap(group: String): Map<Range, Long> { val map = mutableMapOf<Range, Long>() group.split("\n").drop(1).forEach { line -> val (destination, source, length) = line.split(" ").map { n -> n.toLong() } map[Range(source, source + length - 1)] = destination } return map } fun parseAlmanac(input: String): Almanac { val groups = input.split("\n\n") val almanac = Almanac( seeds = groups[0].split(" ").drop(1).map { it.toLong() }, seedToSoil = fillMap(groups[1]), soilToFertilizer = fillMap(groups[2]), fertilizerToWater = fillMap(groups[3]), waterToLight = fillMap(groups[4]), lightToTemperature = fillMap(groups[5]), temperatureToHumidity = fillMap(groups[6]), humidityToLocation = fillMap(groups[7]), ) return almanac } fun Map<Range, Long>.retrieve(ranges: List<Range>): List<Range> { return ranges.flatMap { (min, max) -> val rangeDest = mutableListOf<Range>() val inter = mutableListOf<Range>() for ((range, dest) in this) { val rmin = maxOf(min, range.min) val rmax = minOf(max, range.max) if (rmin <= rmax) { inter.add(Range(rmin, rmax)) rangeDest.add(Range(rmin - range.min + dest, rmax - range.min + dest)) } } inter.sortBy { it.min } var pivot = min for ((rmin, rmax) in inter) { if (rmin > pivot) { rangeDest.add(Range(pivot, rmin - 1)) } pivot = rmax + 1 } if (pivot <= max) { rangeDest.add(Range(pivot, max)) } rangeDest } } fun seedToLocationRange(almanac: Almanac, seedRange: List<Range>): List<Range> { val soil = almanac.seedToSoil.retrieve(seedRange) val fertilizer = almanac.soilToFertilizer.retrieve(soil) val water = almanac.fertilizerToWater.retrieve(fertilizer) val light = almanac.waterToLight.retrieve(water) val temperature = almanac.lightToTemperature.retrieve(light) val humidity = almanac.temperatureToHumidity.retrieve(temperature) return almanac.humidityToLocation.retrieve(humidity) } fun minToLocation(input: String, convertRanges: (List<Long>) -> List<Range>): Long { val almanac = parseAlmanac(input) val seedRanges = convertRanges(almanac.seeds) return seedToLocationRange(almanac, seedRanges).minOf { it.min } } fun part1(input: String) = minToLocation(input) { it.map { Range(it, it) } } fun part2(input: String) = minToLocation(input) { it.chunked(2).map { (min, len) -> Range(min, min + len) } } val testInput = readInputText(name = "${day}_test", year = year) val input = readInputText(name = day, year = year) checkValue(part1(testInput), 35) println(part1(input)) checkValue(part2(testInput), 46) println(part2(input)) } data class Almanac( val seeds: List<Long> = listOf(), val seedToSoil: Map<Range, Long> = mapOf(), val soilToFertilizer: Map<Range, Long> = mapOf(), val fertilizerToWater: Map<Range, Long> = mapOf(), val waterToLight: Map<Range, Long> = mapOf(), val lightToTemperature: Map<Range, Long> = mapOf(), val temperatureToHumidity: Map<Range, Long> = mapOf(), val humidityToLocation: Map<Range, Long> = mapOf(), ) data class Range(val min: Long, val max: Long)
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
3,811
aoc-kotlin
Apache License 2.0
src/day13/Day13.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day13 import java.io.File import kotlin.math.min fun main() { val data = parse("src/day13/Day13.txt") println("🎄 Day 13 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private typealias Pattern = List<List<Char>> private fun parse(path: String): List<Pattern> = File(path) .readText() .split("\n\n", "\r\n\r\n") .map { it.lines().map(String::toList) } private fun Pattern.row(index: Int): List<Char> = this[index] private fun Pattern.col(index: Int): List<Char> = this.indices.map { this[it][index] } private fun verticalDifference(pattern: Pattern, y: Int): Int { val distance = min(y, pattern.size - y) return (0..<distance).sumOf { dy -> val lineTop = pattern.row(y - dy - 1) val lineBottom = pattern.row(y + dy) lineTop.zip(lineBottom).count { (a, b) -> a != b } } } private fun horizontalDifference(pattern: Pattern, x: Int): Int { val distance = min(x, pattern[0].size - x) return (0..<distance).sumOf { dx -> val lineLeft = pattern.col(x - dx - 1) val lineRight = pattern.col(x + dx) lineLeft.zip(lineRight).count { (a, b) -> a != b } } } private fun solve(data: List<Pattern>, tolerance: Int): Int { return data.sumOf { pattern -> val height = pattern.size for (y in 1..<height) { if (verticalDifference(pattern, y) == tolerance) { return@sumOf 100 * y } } val width = pattern[0].size for (x in 1..<width) { if (horizontalDifference(pattern, x) == tolerance) { return@sumOf x } } error("Reflection line could not be found.") } } private fun part1(data: List<Pattern>): Int = solve(data, tolerance = 0) private fun part2(data: List<Pattern>): Int = solve(data, tolerance = 1)
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
2,071
advent-of-code-2023
MIT License
src/main/kotlin/com/adventofcode/Day05.kt
keeferrourke
434,321,094
false
{"Kotlin": 15727, "Shell": 1301}
package com.adventofcode import kotlin.math.roundToInt data class Point(val x: Int, val y: Int) : Comparable<Point> { override fun compareTo(other: Point): Int { val xeq = x.compareTo(other.x) return if (xeq != 0) xeq else y.compareTo(other.y) } } data class Line(val start: Point, val end: Point) { val isHorizontal: Boolean = start.y == end.y val isVertical: Boolean = start.x == end.x private val slope: Double get() = if (isVertical) Double.NaN else (start.y - end.y).toDouble() / (start.x - end.x) val points: List<Point> by lazy { when { isVertical -> (minOf(start.y, end.y)..maxOf(start.y, end.y)).map { y -> Point(start.x, y) } isHorizontal -> (minOf(start.x, end.x)..maxOf(start.x, end.x)).map { x -> Point(x, start.y) } else -> interpolate() } } private fun interpolate(): List<Point> { val (x1, y1) = minOf(start, end) val (x2, _) = maxOf(start, end) return (x1..x2).map { x -> Point(x, (y1 + (x - x1) * slope).roundToInt()) } } } private fun parse(input: String): List<Line> = input.lines() .map { line -> val (a, _, b) = line.split(" ") val (x1, y1) = a.split(",").map { it.toInt() } val (x2, y2) = b.split(",").map { it.toInt() } Line(Point(x1, y1), Point(x2, y2)) } fun findVents(input: String, excludeDiagonals: Boolean) = when (excludeDiagonals) { true -> findVents(input) { it.isVertical || it.isHorizontal } false -> findVents(input) { true } } private fun findVents(input: String, filter: (Line) -> Boolean): Int = parse(input) .filter(filter) .flatMap { it.points } .fold(mutableMapOf<Point, Int>()) { acc, point -> acc.apply { merge(point, 1) { v, _ -> v + 1 } } } .count { it.value > 1 } fun day05(input: String, args: List<String> = listOf("p1")) { when (args.first().lowercase()) { "p1" -> println(findVents(input, excludeDiagonals = true)) "p2" -> println(findVents(input, excludeDiagonals = false)) } }
0
Kotlin
0
0
44677c6ae0ba1a8a8dc80dfa68c17b9c315af8e2
1,978
aoc2021
ISC License
y2018/src/main/kotlin/adventofcode/y2018/Day13.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import adventofcode.y2018.Day13.Direction.* object Day13 : AdventSolution(2018, 13, "Mine Cart Madness") { override fun solvePartOne(input: String): String { val (track, carts) = parse(input) while (true) { for (cart in carts.sortedBy { it.p.y * 10000 + it.p.x }) { cart.move(track) if (carts.count { it.p == cart.p } > 1) return cart.position() } } } override fun solvePartTwo(input: String): String { val (track, carts) = parse(input) while (true) { for (cart in carts.sortedBy { it.p.y * 10000 + it.p.x }) { cart.move(track) if (carts.count { it.p == cart.p } > 1) carts.removeIf { it.p == cart.p } } if (carts.size == 1) return carts[0].position() } } private fun Cart.move(track: List<String>) { if (p.x < 0 || p.y < 0) return p += d.vector when (track[p.y][p.x]) { '/' -> d = when (d) { UP -> RIGHT RIGHT -> UP DOWN -> LEFT LEFT -> DOWN } '\\' -> d = when (d) { UP -> LEFT LEFT -> UP DOWN -> RIGHT RIGHT -> DOWN } '+' -> { when (t) { 0 -> d = d.left() 2 -> d = d.right() } t = (t + 1) % 3 } } } private fun parse(input: String): Pair<List<String>, MutableList<Cart>> { val track = input.lines() val carts = mutableListOf<Cart>() track.forEachIndexed { y, r -> r.forEachIndexed { x, ch -> when (ch) { '^' -> carts += Cart(Point(x, y), UP, 0) 'v' -> carts += Cart(Point(x, y), DOWN, 0) '<' -> carts += Cart(Point(x, y), LEFT, 0) '>' -> carts += Cart(Point(x, y), RIGHT, 0) } } } return track to carts } private data class Cart(var p: Point, var d: Direction, var t: Int) { fun position() = "${p.x},${p.y}" } private enum class Direction(val vector: Point) { UP(Point(0, -1)), RIGHT(Point(1, 0)), DOWN(Point(0, 1)), LEFT(Point(-1, 0)); fun left() = turn(3) fun right() = turn(1) private fun turn(i: Int): Direction = values().let { it[(it.indexOf(this) + i) % it.size] } } private data class Point(val x: Int, val y: Int) { operator fun plus(o: Point) = Point(x + o.x, y + o.y) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,798
advent-of-code
MIT License
src/Day04.kt
atsvetkov
572,711,515
false
{"Kotlin": 10892}
data class Assignment(val left: Int, val right: Int) { companion object { fun parse(input: String) = Assignment(input.split('-')[0].toInt(), input.split('-')[1].toInt()) } fun contains(other: Assignment) = this.left <= other.left && this.right >= other.right fun overlapsWith(other: Assignment): Boolean = !(this.right < other.left || this.left > other.right) } data class AssignmentPair(val first: Assignment, val second: Assignment) { companion object { fun parse(input: String) = AssignmentPair(Assignment.parse(input.split(',')[0]), Assignment.parse(input.split(',')[1])) } fun hasFullContainment() = first.contains(second) || second.contains(first) fun hasOverlap() = first.overlapsWith(second) } fun main() { fun part1(input: List<String>): Int { return input.count { line -> AssignmentPair.parse(line).hasFullContainment() } } fun part2(input: List<String>): Int { return input.count { line -> AssignmentPair.parse(line).hasOverlap() } } val testInput = readInput("Day04_test") println("Test Part 1: " + part1(testInput)) println("Test Part 2: " + part2(testInput)) println() val input = readInput("Day04") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
01c3bb6afd658a2e30f0aee549b9a3ac4da69a91
1,300
advent-of-code-2022
Apache License 2.0
src/Day03.kt
msernheim
573,937,826
false
{"Kotlin": 32820}
fun main() { fun getPriority(item: Char): Int { return when { item.isLowerCase() -> item.code - 96 item.isUpperCase() -> item.code - 38 else -> 0 } } fun getDuplicates(head: String, tail: String): String { return head.filter { item -> tail.contains(item) } } fun part1(input: List<String>): Int { val duplicates = mutableListOf<Char>() input.forEach { items -> val head = items.slice(IntRange(0, items.length / 2 - 1)) val tail = items.drop(items.length / 2) duplicates.add(getDuplicates(head, tail).first()); } return duplicates.map(::getPriority).sum() } fun getBadgeForGroup(group: List<String>): Char { val commons = getDuplicates(group[0], group[1]) return getDuplicates(commons, group[2]).first() } fun part2(input: List<String>): Int { val badges = mutableListOf<Char>() for (i in input.indices) { if (i % 3 == 0) badges.add(getBadgeForGroup(input.slice(IntRange(i, i+2)))) } return badges.map(::getPriority).sum() } val input = readInput("Day03") val part1 = part1(input) val part2 = part2(input) println("Result part1: $part1") println("Result part2: $part2") }
0
Kotlin
0
3
54cfa08a65cc039a45a51696e11b22e94293cc5b
1,329
AoC2022
Apache License 2.0
src/Day04.kt
tigerxy
575,114,927
false
{"Kotlin": 21255}
fun main() { fun part1(input: List<String>): Int = input .parse() .map { it.fullyContainsOther() } .sum() fun part2(input: List<String>): Int = input .parse() .map { it.overlapsOther() } .sum() val day = "04" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") val testOutput1 = part1(testInput) println("part1_test=$testOutput1") assert(testOutput1 == 13) val testOutput2 = part2(testInput) println("part2_test=$testOutput2") assert(testOutput1 == 0) val input = readInput("Day$day") println("part1=${part1(input)}") println("part2=${part2(input)}") } private fun Pair<IntRange,IntRange>.overlapsOther() = first.contains(second.first) || first.contains(second.last) || second.contains(first.first) || second.contains(first.last) private fun Pair<IntRange,IntRange>.fullyContainsOther() = first.inside(second) || second.inside(first) private fun IntRange.inside(other: IntRange): Boolean = first <= other.first && other.last <= last private fun List<String>.parse(): List<Pair<IntRange, IntRange>> = map { line -> line.split(',', '-') .asSequence() .map { it.toInt() } .chunked(2) .map { IntRange(it[0], it[1]) } .chunked(2) .map { Pair(it[0], it[1]) } .first() }
0
Kotlin
0
1
d516a3b8516a37fbb261a551cffe44b939f81146
1,485
aoc-2022-in-kotlin
Apache License 2.0
src/aoc2022/Day09.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList import kotlin.math.abs import kotlin.math.sign fun main() { data class Point(val x: Int, val y: Int) fun Point.isNear(other: Point) : Boolean { return (x == other.x && y == other.y) || (x == other.x + 1 && y == other.y) || (x == other.x - 1 && y == other.y) || (x == other.x && y == other.y + 1) || (x == other.x && y == other.y - 1) || (x == other.x - 1 && y == other.y - 1) || (x == other.x + 1 && y == other.y + 1) || (x == other.x - 1 && y == other.y + 1) || (x == other.x + 1 && y == other.y - 1) } fun part1(input: List<String>) : Any { val points = mutableListOf<Point>() points.add(Point(0, 0)) var head = Point(0, 0) var tail = Point(0, 0) for(line in input) { val (direction, count) = line.split(" ") repeat(count.toInt()) { when(direction) { "R" -> { head = head.copy(x = head.x + 1) if (!tail.isNear(head)) tail = head.copy(x = head.x - 1) } "L" -> { head = head.copy(x = head.x - 1) if (!tail.isNear(head)) tail = head.copy(x = head.x + 1) } "U" -> { head = head.copy(y = head.y - 1) if (!tail.isNear(head)) tail = head.copy(y = head.y + 1) } "D" -> { head = head.copy(y = head.y + 1) if (!tail.isNear(head)) tail = head.copy(y = head.y - 1) } } points.add(tail) } } return points.distinct().size } fun part2(input: List<String>) : Any { val rope = Array(10) { 0 to 0 } val visited = mutableSetOf<Pair<Int, Int>>() visited.add(rope.last()) for(line in input){ val (direction, count) = line.split(" ") val step = when(direction) { "R" -> 1 to 0 "L" -> -1 to 0 "U" -> 0 to 1 "D" -> 0 to -1 else -> error("you're never going to error") } repeat(count.toInt()){ rope[0] = rope[0].first + step.first to rope[0].second + step.second for(i in 0 until rope.lastIndex) { val head = rope[i] val tail = rope[i+1] rope[i+1] = if(abs(head.first - tail.first) > 1 || abs(head.second - tail.second) > 1) { val tailX = if (head.first == tail.first) 0 else (head.first - tail.first).sign val tailY = if (head.second == tail.second) 0 else (head.second - tail.second).sign tail.first + tailX to tail.second + tailY } else tail } visited += rope.last() } } return visited.size } val input = readInputAsList("Day09", "2022") println(part1(input)) println(part2(input)) val testInput = readInputAsList("Day09_test", "2022") check(part1(testInput) == 13) check(part2(testInput) == 1) }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
3,428
AOC-2022-Kotlin
Apache License 2.0
src/Day05.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
fun main() { val input = readInput("Day05") println(Day05.part1(input)) println(Day05.part2(input)) } data class Move(val size: Int, val from: Int, val to: Int) class Day05 { companion object { fun part1(input: List<String>): String { val (initial, rawActions) = input.partitionOnElement("") val numberOfStacks = initial.maxOf { it.length } / 3 val stacks: List<ArrayDeque<Char>> = (1..numberOfStacks).toList().map { ArrayDeque<Char>(initial.size * 2) } val initialReversed = initial.dropLast(1).reversed() for (level in initialReversed) { for (i in 1..numberOfStacks) { val value = level.getOrNull((4 * i) - 3) if (value != null && value != ' ') { stacks[i - 1].addLast(value) } } } val actions = rawActions.map { it.split("move ", " from ", " to ").subList(1, 4).map { v -> v.toInt() } } .map { (size, from, to) -> Move(size, from, to) } for (action in actions) { for (i in 0 until action.size) { stacks[action.to - 1].addLast(stacks[action.from - 1].removeLast()) } } return stacks.mapNotNull { it.removeLastOrNull() }.joinToString("") } fun part2(input: List<String>): String { val (initial, rawActions) = input.partitionOnElement("") val numberOfStacks = initial.maxOf { it.length } / 3 val stacks: MutableList<ArrayDeque<Char>> = (1..numberOfStacks).toList().map { ArrayDeque<Char>(initial.size * 2) }.toMutableList() val initialReversed = initial.dropLast(1).reversed() for (level in initialReversed) { for (i in 1..numberOfStacks) { val value = level.getOrNull((4 * i) - 3) if (value != null && value != ' ') { stacks[i - 1].addLast(value) } } } val actions = rawActions.map { it.split("move ", " from ", " to ").subList(1, 4).map { v -> v.toInt() } } .map { (size, from, to) -> Move(size, from, to) } for (action in actions) { val splitPoint = stacks[action.from - 1].size - action.size val newFrom = stacks[action.from - 1].subList(0, splitPoint) val swap = stacks[action.from - 1].subList(splitPoint, stacks[action.from - 1].size) stacks[action.from - 1] = ArrayDeque(newFrom) stacks[action.to - 1].addAll(swap) } return stacks.mapNotNull { it.removeLastOrNull() }.joinToString("") } } }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
2,820
advent-of-code-22
Apache License 2.0
src/day3/Day3.kt
jorgensta
573,824,365
false
{"Kotlin": 31676}
package day3 import readInput fun main() { val day = "day3" val filename = "Day03" val alfabeth_lowercase = "abcdefghijklmnopqrstuvwxyz".lowercase() val alfabeth_uppercase = "abcdefghijklmnopqrstuvwxyz".uppercase() fun getCompartments(line: String) = Pair(line.slice(0 until line.length / 2), line.slice(line.length / 2 until line.length)) fun getPriority(char: Char): Int = when (char in alfabeth_lowercase) { true -> alfabeth_lowercase.indexOf(char) + 1 false -> alfabeth_uppercase.indexOf(char) + 26 + 1 } fun occurrenceInAllCollections(char: Char, window: List<String>): Boolean { return window.all { it.contains(char) } } fun getBadge(window: List<String>): Char { return (alfabeth_lowercase + alfabeth_uppercase) .toList() .first { occurrenceInAllCollections(it, window) } } fun part1(input: List<String>): Int { return input.sumOf { it -> val compartments = getCompartments(it) val intersect = compartments.first.toList().intersect(compartments.second.toList()) intersect.sumOf{ s -> getPriority(s) } } } fun part2(input: List<String>): Int { return input .windowed(3, 3) .sumOf { window -> val badge = getBadge(window) getPriority(badge) } } // test if implementation meets criteria from the description, like: val testInput = readInput("/$day/${filename}_test") val input = readInput("/$day/$filename") val partOneTest = part1(testInput) check(partOneTest == 157) println("Part one: ${part1(input)}") val partTwoTest = part2(testInput) check(partTwoTest == 70) println("Part two: ${part2(input)}") }
0
Kotlin
0
0
7243e32351a926c3a269f1e37c1689dfaf9484de
1,811
AoC2022
Apache License 2.0
src/main/kotlin/com/ab/advent/day01/Puzzle.kt
battagliandrea
574,137,910
false
{"Kotlin": 27923}
package com.ab.advent.day01 import com.ab.advent.utils.readLines /* PART 01 The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. thatthey've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line. For example, suppose the Elves finish writing their items' Calories and end up with the following list: 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 This list represents the Calories of the food carried by five Elves: The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. The second Elf is carrying one food item with 4000 Calories. The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. The fifth Elf is carrying one food item with 10000 Calories. In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf). Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? PART TWO By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks. To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups. In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000. Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? */ fun main(args: Array<String>) { println("Day 1 - Puzzle 1") val input = "puzzle_01_input.txt".readLines() println(elves(input)) println("Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?") println(answer1(input)) println("Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?") println(answer2(input)) } fun elves(input: List<String>) = input.chunked { it.isBlank() } .map { data -> Elf(inventory = data.map { it.toLong() }.map{ Food(calories = it)})} fun answer1(input: List<String>) = elves(input).maxBy { it.carriedCalories }.carriedCalories fun answer2(input: List<String>) = elves(input).sortedByDescending { it.carriedCalories }.take(3).sumOf { it.carriedCalories } fun <T> List<T>.chunked(regex: (T) -> Boolean): List<List<T>>{ val output = arrayListOf<List<T>>() var last = 0 this.forEachIndexed { index, value -> if(regex(value)){ output.add(subList(last, index)) last = index + 1 } } return output }
0
Kotlin
0
0
cb66735eea19a5f37dcd4a31ae64f5b450975005
3,165
Advent-of-Kotlin
Apache License 2.0
src/2022/Day09.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun part1(input: List<String>): Int { val uniqueTailPoints = mutableSetOf(Point(0, 0)) var head = Point(0, 0) var tail = Point(0, 0) input.forEach { val (direction, steps) = it.split(" ") repeat(steps.toInt()) { head = head.move(direction) tail = tail.moveTowards(head) uniqueTailPoints.add(tail) } } return uniqueTailPoints.size } fun part2(input: List<String>): Int { val uniqueTailPoints = mutableSetOf(Point(0, 0)) var head = Point(0, 0) var tails = List(9) { Point(0, 0) } input.forEach { val (direction, steps) = it.split(" ") repeat(steps.toInt()) { head = head.move(direction) tails = tails.moveTowards(head) uniqueTailPoints.add(tails.last()) } } return uniqueTailPoints.size } // 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)) } data class Point(val x: Int, val y: Int) fun Point.isNear(other: Point): Boolean { return x in (other.x - 1 .. other.x + 1) && y in (other.y - 1 .. other.y + 1) } fun Point.move(direction: String): Point { return when (direction) { "R" -> Point(x + 1, y) "L" -> Point(x - 1, y) "U" -> Point(x, y + 1) "D" -> Point(x, y - 1) else -> throw IllegalArgumentException("Unrecognized direction $direction") } } fun Point.moveTowards(other: Point): Point { if (isNear(other)) return this val newX = if (other.x > x) x + 1 else if (other.x < x) x - 1 else x val newY = if (other.y > y) y + 1 else if (other.y < y) y - 1 else y return Point(newX, newY) } fun List<Point>.moveTowards(head: Point): List<Point> { var nextHead = head return map { point -> nextHead = point.moveTowards(nextHead) nextHead } }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
2,192
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
timj11dude
572,900,585
false
{"Kotlin": 15953}
fun main() { fun setup(input: Collection<String>): Pair<Collection<String>, List<ArrayDeque<Char>>> { val crateRegex = "\\[(\\w)\\]".toRegex() return (input.dropWhile { it.isNotBlank() }.drop(1)) to ( input .takeWhile { it.isNotBlank() } .reversed() .let { newInput -> val size = newInput.first().last { it.isDigit() }.digitToInt() buildList<ArrayDeque<Char>>(size) { repeat(size) { add(ArrayDeque()) } }.also { output -> newInput .drop(1) .forEach { line -> line.windowed(3, 4) .mapIndexed { i, item -> crateRegex.matchEntire(item)?.groupValues?.get(1)?.single()?.also { output[i].addFirst(it) } } } } } ) } fun part1(input: Collection<String>): String { val (rem, stacks) = setup(input) val moveRegex = "move (\\d+) from (\\d) to (\\d)".toRegex() rem.forEach { instruction -> moveRegex.matchEntire(instruction)!!.groupValues.let { match -> repeat(match[1].toInt()) { stacks[match[3].toInt() - 1].addFirst(stacks[match[2].toInt() - 1].removeFirst()) } } } return stacks.joinToString("") { it.first().toString() } } fun part2(input: Collection<String>): String { val (rem, stacks) = setup(input) val moveRegex = "move (\\d+) from (\\d) to (\\d)".toRegex() rem.forEach { instruction -> moveRegex.matchEntire(instruction)!!.groupValues.let { match -> val (moveSize, fromStack, toStack) = match.drop(1).map(String::toInt).mapIndexed { i, it -> if (i > 0) it - 1 else it } val tempStack = ArrayDeque<Char>() repeat(moveSize) { tempStack.addFirst(stacks[fromStack].removeFirst()) } repeat(moveSize) { stacks[toStack].addFirst(tempStack.removeFirst()) } } } return stacks.joinToString("") { it.first().toString() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
28aa4518ea861bd1b60463b23def22e70b1ed481
2,833
advent-of-code-2022
Apache License 2.0
src/y2021/Day17.kt
Yg0R2
433,731,745
false
null
package y2021 import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val targetArea = input[0].getTargetArea() var maxHeight = 0 for (x in 0 until targetArea.second.first) { for (y in targetArea.second.second until targetArea.second.second * -1) { val initialVelocity = x to y var position = 0 to 0 var maxHeightInTry = 0 var stepCounter = -1 while ((position.first <= targetArea.second.first) && (position.second >= targetArea.second.second)) { stepCounter += 1 val newVelocity = initialVelocity.calculateTrajectory(stepCounter) position = position.first + newVelocity.first to position.second + newVelocity.second maxHeightInTry = max(maxHeightInTry, position.second) if (targetArea.targetHit(position)) { maxHeight = max(maxHeight, maxHeightInTry) break } } } } return maxHeight } fun part2(input: List<String>): Int { val targetArea = input[0].getTargetArea() var targetHitCount = 0 for (x in 0 until targetArea.second.first + 1) { for (y in targetArea.second.second until (targetArea.second.second * -1) + 1) { val initialVelocity = x to y var position = 0 to 0 var stepCounter = -1 while ((position.first <= targetArea.second.first) && (position.second >= targetArea.second.second)) { stepCounter += 1 val newVelocity = initialVelocity.calculateTrajectory(stepCounter) position = position.first + newVelocity.first to position.second + newVelocity.second if (targetArea.targetHit(position)) { targetHitCount += 1 break } } } } return targetHitCount } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") check(part1(testInput).also { println(it) } == 45) check(part2(testInput).also { println(it) } == 112) val input = readInput("Day17") println(part1(input)) println(part2(input)) } fun Pair<Int, Int>.calculateTrajectory(steps: Int): Pair<Int, Int> { var newX = first var newY = second for (step in 0 until steps) { newX = newX .let { if (it < 0) { it + 1 } else if (it > 0) { it - 1 } else { 0 } } newY -= 1 } return newX to newY } // ((x1 to y1) to (x2 to y2)) private fun String.getTargetArea(): Pair<Pair<Int, Int>, Pair<Int, Int>> { val xStart = indexOf("x=") + 2 val yStart = indexOf("y=") + 2 val xCoordinates = substring(xStart, indexOf(",", xStart)) .split("..") .map { it.toInt() } .sorted() val yCoordinates = substring(yStart) .split("..") .map { it.toInt() } .sortedDescending() return (xCoordinates[0] to yCoordinates[0]) to (xCoordinates[1] to yCoordinates[1]) } private fun Pair<Pair<Int, Int>, Pair<Int, Int>>.targetHit(position: Pair<Int, Int>): Boolean = position.first in (first.first..second.first) && position.second in (second.second..first.second)
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
3,634
advent-of-code
Apache License 2.0
src/Day02.kt
Derrick-Mwendwa
573,947,669
false
{"Kotlin": 8707}
fun main() { fun part1(input: List<String>): Int { // Assuming that we trust the input fun scoreOfShape(shape: Char) = when (shape) { 'X' -> 1 'Y' -> 2 else -> 3 } fun score(opponent: Char, player: Char) = when (opponent to player) { 'A' to 'Y', 'C' to 'X', 'B' to 'Z' -> 6 'A' to 'X', 'B' to 'Y', 'C' to 'Z' -> 3 else -> 0 } return input.sumOf { scoreOfShape(it[2]) + score(it[0], it[2]) } } fun part2(input: List<String>): Int { fun scoreOfShape(result: Pair<Char, Int>) = result.second + when (result.first) { 'X' -> 1 'Y' -> 2 else -> 3 } fun getOutcome(opponent: Char, outcome: Char): Pair<Char,Int> { val ch = when (outcome to opponent) { 'X' to 'A', 'Y' to 'C', 'Z' to 'B' -> 'Z' 'X' to 'B', 'Y' to 'A', 'Z' to 'C' -> 'X' else -> 'Y' } return ch to (outcome - 'X') * 3 } return input.sumOf { scoreOfShape(getOutcome(it[0], it[2])) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7870800afa54c831c143b5cec84af97e079612a3
1,383
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05.kt
ka1eka
574,248,838
false
{"Kotlin": 36739}
fun main() { fun Sequence<String>.chunkedOnNull(): Sequence<List<String>> = sequence { val buffer = mutableListOf<String>() for (element in this@chunkedOnNull) { if (element.isEmpty()) { yield(buffer.toList()) buffer.clear() } else { buffer += element } } if (buffer.isNotEmpty()) yield(buffer) } fun initStacks(startingConfig: List<String>): List<ArrayDeque<Char>> { val longestLine = startingConfig.maxBy { it.length } val totalNumber = (longestLine.length + 1) / 4 val stacks = List(totalNumber) { ArrayDeque<Char>() } startingConfig .asSequence() .take(startingConfig.size - 1) .map { it.chunked(4) { crate -> crate[1] } } .forEach { it.forEachIndexed { crateIndex, crate -> if (crate.isLetter()) { stacks[crateIndex].addLast(crate) } } } return stacks } val moveRegex = "move\\s|\\sfrom\\s|\\sto\\s".toRegex() fun parseMove(move: String): List<Int> = move .splitToSequence(moveRegex) .filter { it.isNotBlank() } .map { it.toInt() } .toList() fun moveCrates9000(stacks: List<ArrayDeque<Char>>, moves: List<String>) { moves .map { parseMove(it) } .forEach { val count = it[0] val from = it[1] - 1 val to = it[2] - 1 repeat(count) { stacks[to].addFirst(stacks[from].removeFirst()) } } } fun moveCrates9001(stacks: List<ArrayDeque<Char>>, moves: List<String>) { moves .map { parseMove(it) } .forEach { val count = it[0] val from = it[1] - 1 val to = it[2] - 1 val current = ArrayDeque<Char>() repeat(count) { current.addLast(stacks[from].removeFirst()) } while (current.isNotEmpty()) { stacks[to].addFirst(current.removeLast()) } } } fun part1(input: List<String>): String = input .asSequence() .chunkedOnNull() .toList() .let { val crates = initStacks(it[0]) moveCrates9000(crates, it[1]) crates }.mapNotNull { it.firstOrNull() } .toCharArray() .concatToString() fun part2(input: List<String>): String = input .asSequence() .chunkedOnNull() .toList() .let { val crates = initStacks(it[0]) moveCrates9001(crates, it[1]) crates }.mapNotNull { it.firstOrNull() } .toCharArray() .concatToString() 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
4f7893448db92a313c48693b64b3b2998c744f3b
3,231
advent-of-code-2022
Apache License 2.0
2021/src/main/kotlin/day4_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Parser import utils.Solution fun main() { Day4Func.run() } object Day4Func : Solution<Pair<List<Int>, List<IntGrid>>>() { override val name = "day4" override val parser = Parser.compoundList(Parser.ints, IntGrid.table) override fun part1(input: Pair<List<Int>, List<IntGrid>>): Int { val (numbers, boards) = input return numbers.indices.asSequence() .map { count -> numbers.take(count).toSet() to boards } .flatMap { (numbers, boards) -> boards.map { numbers to it } } .first { (numbers, board) -> board.winning(numbers) } .let { (numbers, board) -> board.score(numbers) } } override fun part2(input: Pair<List<Int>, List<IntGrid>>): Number? { val (numbers, boards) = input return numbers.indices.asSequence() .map { count -> numbers.take(count).toSet() to boards } .flatMap { (numbers, boards) -> boards.map { numbers to it } } .last { (numbers, board) -> board.winning(numbers) && !board.winning(numbers - numbers.last()) } .let { (numbers, board) -> board.score(numbers) } } private fun IntGrid.winning(marked: Set<Int>): Boolean { return rows.any { row -> row.values.all { it in marked } } || columns.any { col -> col.values.all { it in marked } } } private fun IntGrid.score(marked: Set<Int>): Int { return (values.toSet() - marked).sum() * marked.last() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,401
aoc_kotlin
MIT License
src/main/kotlin/Day07.kt
ripla
573,901,460
false
{"Kotlin": 19599}
object Day7 { data class Directory( val name: String, val parent: Directory?, var directories: List<Directory> = emptyList(), var files: List<File> = emptyList() ) { fun getRoot(): Directory = parent?.getRoot() ?: this fun size(): Int = files.sumOf { it.size } + directories.sumOf { it.size() } fun subDirectoriesAsList(): List<Directory> = directories + directories.flatMap { it.subDirectoriesAsList() } } data class File(val name: String, val size: Int) private fun executeCommand(command: String, currentDir: Directory): Directory = when (val param = command.split(" ").last()) { "/" -> currentDir.getRoot() ".." -> currentDir.parent ?: currentDir "ls" -> currentDir // noop // cd abc else -> currentDir.directories.find { dir -> dir.name == param } ?: currentDir } private fun buildDirectoryTree( input: List<String>, root: Directory ) = input.fold(root) { currentDirectory, inputLine -> when { inputLine.startsWith("$") -> { val command = inputLine.drop(2) executeCommand(command, currentDirectory) } inputLine.startsWith("dir") -> { val (command, directoryName) = inputLine.split(" ") currentDirectory.directories = currentDirectory.directories + Directory(directoryName, currentDirectory) currentDirectory } inputLine.first().isDigit() -> { val (size, fileName) = inputLine.split(" ") currentDirectory.files = currentDirectory.files + File(fileName, size.toInt()) currentDirectory } else -> throw Error("Unknown $inputLine") } } fun part1(input: List<String>): Int { val root = Directory("", null) buildDirectoryTree(input, root) return root.subDirectoriesAsList() .filter { it.size() < 100000 } .sumOf { it.size() } } fun part2(input: List<String>): Int { val root = Directory("", null) buildDirectoryTree(input, root) val totalDiskSpace = 70000000 val currentlyUsedSpace = root.size() val unusedSpace = totalDiskSpace - currentlyUsedSpace val neededSpace = 30000000 return root.subDirectoriesAsList() .map { it.size() } .sorted() .find { unusedSpace + it >= neededSpace } ?: -1 } }
0
Kotlin
0
0
e5e6c0bc7a9c6eaee1a69abca051601ccd0257c8
2,574
advent-of-code-2022-kotlin
Apache License 2.0
src/Day04.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
fun main() { fun rangesContained(firstRange: ClosedRange<Int>, secondRange: ClosedRange<Int>): Boolean { if( // The first pair is contained in the second firstRange.start >= secondRange.start && firstRange.endInclusive <= secondRange.endInclusive // The first pair is contained in the second || firstRange.start <= secondRange.start && firstRange.endInclusive >= secondRange.endInclusive) { return true } return false } fun rangesIntersect(firstRange: ClosedRange<Int>, secondRange: ClosedRange<Int>): Boolean { for(i in firstRange.start..firstRange.endInclusive) { if(secondRange.contains(i)) { return true } } return false } fun part1(input: List<String>): Int { var containedPairs = 0 input.map {line -> val pairs = line.split(",").map { it.split("-") } val firstRange = pairs[0][0].toInt()..pairs[0][1].toInt() val secondRange = pairs[1][0].toInt()..pairs[1][1].toInt() if(rangesContained(firstRange, secondRange)) { containedPairs++ } } return containedPairs } fun part2(input: List<String>): Int { var containedPairs = 0 input.map {line -> val pairs = line.split(",").map { it.split("-") } val firstRange = pairs[0][0].toInt()..pairs[0][1].toInt() val secondRange = pairs[1][0].toInt()..pairs[1][1].toInt() if(rangesIntersect(firstRange, secondRange)) { containedPairs++ } } return containedPairs } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
1,852
KotlinAdvent2022
Apache License 2.0
src/Day04.kt
BionicCa
574,904,899
false
{"Kotlin": 20039}
fun main() { fun part1(input: List<String>): Int { val pairs = input.map { it.split(",") } var foundFullyContainedNumbers = 0 for ((first, second) in pairs) { val rangeFirst = first.split("-").let { it[0].toInt()..it[1].toInt() } val rangeSecond = second.split("-").let { it[0].toInt()..it[1].toInt() } foundFullyContainedNumbers += if (rangeFirst.all { it in rangeSecond } || rangeSecond.all { it in rangeFirst }) 1 else 0 } return foundFullyContainedNumbers } fun part2(input: List<String>): Int { val pairs = input.map { it.split(",") } var foundFullyContainedNumbers = 0 for ((first, second) in pairs) { val rangeFirst = first.split("-").let { it[0].toInt()..it[1].toInt() } val rangeSecond = second.split("-").let { it[0].toInt()..it[1].toInt() } val duplicates = rangeFirst.intersect(rangeSecond) if (duplicates.isNotEmpty()) foundFullyContainedNumbers += 1 } return foundFullyContainedNumbers } val testInput = readInput("Day04_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed8bda8067386b6cd86ad9704bda5eac81bf0163
1,297
AdventOfCode2022
Apache License 2.0
src/Day02.kt
handrodev
577,884,162
false
{"Kotlin": 7670}
fun main() { // A: Rock, B: Paper, C: Scissors // A < B < C < A val scoreMap = mapOf("A" to 1, "B" to 2, "C" to 3) val XYZ2ABC = mapOf("X" to "A", "Y" to "B", "Z" to "C") fun part1(input: List<String>): Int { var score = 0 for (line in input) { var (opponent, myPlayer) = line.replace("\n", "").split(" ") // Add score of played shape score += scoreMap[XYZ2ABC[myPlayer]]!! myPlayer = XYZ2ABC[myPlayer]!! // Add score of match result if (opponent == myPlayer) { // DRAW (3 points) score += 3 } else if ((opponent == "A" && myPlayer == "B") || (opponent == "B" && myPlayer == "C") || (opponent == "C" && myPlayer == "A") ) { // WIN (6 points): Rock > Scissors > Paper > Rock score += 6 } else { // LOST (0 points) // Do nothing } } return score } fun part2(input: List<String>): Int { var score = 0 val result2abc = mapOf( "A" to mapOf("X" to "C", "Y" to "A", "Z" to "B"), "B" to mapOf("X" to "A", "Y" to "B", "Z" to "C"), "C" to mapOf("X" to "B", "Y" to "C", "Z" to "A") ) val xyz2score = mapOf("X" to 0, "Y" to 3, "Z" to 6) for (line in input) { val (opponent, result) = line.replace("\n", "").split(" ") // Now X,Y,Z are the results: // X = lose, Y = draw, Z = win val myPlayer = result2abc[opponent]?.get(result) score += scoreMap[myPlayer]!! + xyz2score[result]!! } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
d95aeb85b4baf46821981bb0ebbcdf959c506b44
2,008
aoc-2022-in-kotlin
Apache License 2.0
src/y2015/Day18.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.getNeighbors import util.printMatrix import util.readInput object Day18 { private fun parse(input: List<String>): List<List<Boolean>> { return input.map { line -> line.map { it == '#' } } } fun part1(input: List<String>, steps: Int): Int { var lights = parse(input) repeat(steps) { lights = nextLights(lights) } printMatrix(lights) { if (it) "##" else " " } return lights.flatten().count { it } } private fun nextLights(lights: List<List<Boolean>>): List<List<Boolean>> { return lights.mapIndexed { row, ls -> ls.mapIndexed { col, on -> switch(on, getNeighbors(lights, row to col)) } } } private fun switch(on: Boolean, neighbors: List<Boolean>): Boolean { val neighborsOn = neighbors.count { it } return if (on) { neighborsOn in listOf(2, 3) } else { neighborsOn == 3 } } fun part2(input: List<String>, steps: Int): Int { var lights = withCornersOn(parse(input)) repeat(steps) { lights = withCornersOn(nextLights(lights)) } return lights.flatten().count { it } } private fun withCornersOn(lights: List<List<Boolean>>): List<List<Boolean>> { val corners = setOf( 0 to 0, 0 to lights.size - 1, lights.size - 1 to 0, lights.size - 1 to lights.size - 1 ) return lights.mapIndexed { rowIdx, row -> row.mapIndexed { col, on -> if(rowIdx to col in corners) true else on } } } } fun main() { val testInput = """ .#.#.# ...##. #....# ..#... #.#..# ####.. """.trimIndent().split("\n") println("------Tests------") println(Day18.part1(testInput, 4)) println(Day18.part2(testInput, 5)) println("------Real------") val input = readInput("resources/2015/day18") println(Day18.part1(input, 100)) println(Day18.part2(input, 100)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,161
advent-of-code
Apache License 2.0
codeforces/globalround7/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.globalround7 private fun solve() { val s = readLn() var i = 0 while (i < s.length - 1 - i && s[i] == s[s.length - 1 - i]) i++ println(s.take(i) + solve(s.drop(i).dropLast(i)) + s.takeLast(i)) } private fun solve(s: String): String { val n = s.length val h = Hashing(s + s.reversed()) for (i in n downTo 0) { if (h.hash(0, i) == h.hash(2 * n - i, 2 * n)) return s.take(i) if (h.hash(n - i, n) == h.hash(n, n + i)) return s.takeLast(i) } error(s) } private const val M = 1_000_000_007 class Hashing(s: String, x: Int = 566239) { val h = IntArray(s.length + 1) val t = IntArray(s.length + 1) fun hash(from: Int, to: Int): Int { var res = ((h[to] - h[from] * t[to - from].toLong()) % M).toInt() if (res < 0) res += M return res } init { t[0] = 1 for (i in s.indices) { t[i + 1] = (t[i] * x.toLong() % M).toInt() h[i + 1] = ((h[i] * x.toLong() + s[i].toLong()) % M).toInt() } } } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,059
competitions
The Unlicense
src/main/kotlin/day09/Day09.kt
daniilsjb
434,765,082
false
{"Kotlin": 77544}
package day09 import java.io.File fun main() { val data = parse("src/main/kotlin/day09/Day09.txt") val answer1 = part1(data.toHeightmap()) val answer2 = part2(data.toHeightmap()) println("🎄 Day 09 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private fun parse(path: String): Triple<Int, Int, List<Int>> { val lines = File(path).readLines() val width = lines.first().length val height = lines.size val locations = lines.flatMap { line -> line.map(Char::digitToInt) } return Triple(width, height, locations) } private fun Triple<Int, Int, List<Int>>.toHeightmap() = let { (width, height, locations) -> Heightmap(width, height, locations.map(::Location)) } private data class Heightmap( val width: Int, val height: Int, val locations: List<Location>, ) private data class Location( val height: Int, var visited: Boolean = false, ) private operator fun Heightmap.get(x: Int, y: Int) = locations[y * width + x] private fun adjacentNodes(x: Int, y: Int, width: Int, height: Int) = listOfNotNull( if (x - 1 >= 0) x - 1 to y else null, if (x + 1 < width) x + 1 to y else null, if (y - 1 >= 0) x to y - 1 else null, if (y + 1 < height) x to y + 1 else null, ) private fun part1(heightmap: Heightmap): Int { var sum = 0 val (width, height) = heightmap for (y in 0 until height) { for (x in 0 until width) { val node = heightmap[x, y] val isLowestPoint = adjacentNodes(x, y, width, height) .all { (nx, ny) -> heightmap[nx, ny].height > node.height } if (isLowestPoint) { sum += node.height + 1 } } } return sum } private fun Location.isInsideUnexploredBasin() = !visited && height != 9 private fun Location.visit() { visited = true } private fun countNodesInBasin(heightmap: Heightmap, x: Int, y: Int): Int { val nodesToVisit = ArrayDeque(listOf(x to y)) var count = 0 while (nodesToVisit.isNotEmpty()) { val (nx, ny) = nodesToVisit.removeLast() val node = heightmap[nx, ny] if (node.isInsideUnexploredBasin()) { node.visit() count += 1 adjacentNodes(nx, ny, heightmap.width, heightmap.height) .forEach(nodesToVisit::addLast) } } return count } private fun part2(heightmap: Heightmap): Int { val basins = mutableListOf<Int>() val (width, height) = heightmap for (y in 0 until height) { for (x in 0 until width) { val node = heightmap[x, y] if (node.isInsideUnexploredBasin()) { basins.add(countNodesInBasin(heightmap, x, y)) } } } return basins .sortedDescending() .take(3) .fold(1, Int::times) }
0
Kotlin
0
1
bcdd709899fd04ec09f5c96c4b9b197364758aea
2,999
advent-of-code-2021
MIT License
src/Day23.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
fun main() { class Direction(var dirs: List<Vec2>) class Elf(var pos: Vec2) { var nextPos: Vec2? = null } class Result(val stableRound: Int, val freeCells: Int) fun solve(input: List<String>, rounds: Int?): Result { val elves = mutableListOf<Elf>() for (i in input.indices) { for (j in input[i].indices) { if (input[i][j] == '#') elves += Elf(Vec2(i, j)) } } val directions = mutableListOf( Direction(listOf(Vec2(-1, 0), Vec2(-1, -1), Vec2(-1, 1))), // N Direction(listOf(Vec2(1, 0), Vec2(1, -1), Vec2(1, 1))), // S Direction(listOf(Vec2(0, -1), Vec2(-1, -1), Vec2(1, -1))), // W Direction(listOf(Vec2(0, 1), Vec2(-1, 1), Vec2(1, 1))), // E ) repeat(rounds ?: Int.MAX_VALUE) { currentRound -> val elvesPositions = elves.map { it.pos }.toSet() val proposed = mutableMapOf<Vec2, Int>() fun Elf.propose() { if (pos.allNeighbours.all { it !in elvesPositions }) return for (mainDir in directions) { if (mainDir.dirs.all { it + pos !in elvesPositions }) { nextPos = pos + mainDir.dirs[0] proposed.compute(nextPos!!) { _, value -> (value ?: 0) + 1 } return } } } fun Elf.move() { nextPos?.let { if (proposed[it] == 1) { pos = it } } nextPos = null } elves.forEach { it.propose() } if (elves.all { it.nextPos == null }) { return Result(currentRound + 1, -1) } elves.forEach { it.move() } directions.add(directions.removeAt(0)) } val xRange = elves.maxOf { it.pos.x } - elves.minOf { it.pos.x } val yRange = elves.maxOf { it.pos.y } - elves.minOf { it.pos.y } return Result(-1, (yRange + 1) * (xRange + 1) - elves.size) } fun part1(input: List<String>) = solve(input, 10).freeCells fun part2(input: List<String>) = solve(input, null).stableRound val testInput = readInputLines("Day23_test") check(part1(testInput), 110) check(part2(testInput), 20) val input = readInputLines("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
2,484
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day15.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2021 import se.saidaspen.aoc.util.* import java.util.* fun main() = Day15.run() object Day15 : Day(2021, 15) { var map = toMap(input).mapValues { it.value.toString().toInt() }.toMutableMap() override fun part1(): Any { val start = P(0, 0) val end = P(map.entries.map { it.key }.maxOfOrNull { it.first }!!, map.entries.map { it.key }.maxOfOrNull { it.second }!!) return djikstraL(start, end) } private fun djikstraL(start: P<Int, Int>, end: P<Int, Int>): Int { // Keep track of cheapest cost to move to any given point val costs = mutableMapOf<P<Int, Int>, Int>() // Stack of points to visit next together with their cost (to keep the cost here is optimization, to avoid having to do some look-ups in costs map) val queue = PriorityQueue<P<P<Int, Int>, Int>>(compareBy { it.second }) costs[start] = 0 queue.add(P(start, 0)) while (queue.isNotEmpty()) { val (pos, cost) = queue.poll() val adjacentPoints = listOf(pos + P(-1, 0), pos + P(0, -1), pos + P(0, 1), pos + P(1, 0)).filter { map.containsKey(it) } for (n in adjacentPoints) { val newCost = map[n]!! + cost // The cost of getting to n through the path we currently are investigating val oldCost = costs[n] // Previously cheapest cost to get to n // If the path we are on, is more expensive than some prior path to this node, then we can just ignore this path, it will never be the quickest to get here. if (oldCost != null && oldCost <= newCost) { continue } else { costs[n] = newCost queue.add(P(n, newCost)) } } } return costs[end]!! } override fun part2(): Any { val width = map.entries.map { it.key }.maxOfOrNull { it.first }!! +1 val height = map.entries.map { it.key }.maxOfOrNull { it.second }!!+1 val newMap = mutableMapOf<P<Int, Int>, Int>() for (x in 0 until 5) { for (y in 0 until 5) { newMap.putAll(map.entries .associate { P(it.key.first + (width * x), it.key.second + (height * y)) to if (it.value + (x+y) > 9) it.value + (x+y) - 9 else it.value + (x+y) }) } } map = newMap val start = P(0, 0) val end = P(map.entries.map { it.key }.maxOfOrNull { it.first }!!, map.entries.map { it.key }.maxOfOrNull { it.second }!!) return djikstraL(start, end) } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,634
adventofkotlin
MIT License
src/main/kotlin/aoc/solutions/day2/Day2Solution.kt
KenVanHoeylandt
112,967,846
false
null
package aoc.solutions.day2 import aoc.Solution class Day2Solution : Solution(2) { override fun solvePartOne(input: String): String { return splitStringLines(input) .map(::getRowNumbers) .map(::calculateHashForRow) .sum() .toString() } override fun solvePartTwo(input: String): String { return splitStringLines(input) .map(::getRowNumbers) .map(::getDivisibleRowValue) .sum() .toString() } } /** * Iterate through all values in the row and return the division result of the compatible values. */ private fun getDivisibleRowValue(rowNumbers: List<Int>): Int { return iterateRowCombinations(rowNumbers).map { rowIteration -> val matchResult = findDivisibleRowValue(rowIteration.first, rowIteration.second) if (matchResult != null) { rowIteration.first / matchResult } else { 0 } } .first { it != 0 } } /** * Find the value in the list that the base value can be divided by without having a remainder (if any). */ private fun findDivisibleRowValue(base: Int, list: List<Int>): Int? { return list.find { pairListItem -> (base % pairListItem) == 0 } } private fun splitStringLines(input: String): List<String> { return input.split("\n") } /** * Basic input parsing for a row. */ private fun getRowNumbers(input: String): List<Int> { return input.split("\t").map(String::toInt) } /** * Part 1 hash calculation for a row. */ private fun calculateHashForRow(numbers: List<Int>): Int { var lowest = numbers.first() var highest = numbers.first() numbers.forEach { number -> if (number < lowest) { lowest = number } else if (number > highest) { highest = number } } return highest - lowest } /** * Iterate through possible row combinations for part 2. */ private fun iterateRowCombinations(row: List<Int>): Iterable<Pair<Int, List<Int>>> { return (0..row.lastIndex).map { index -> // row that filters out the current indexed item val newRow = row.filterIndexed { filterIndex, _ -> filterIndex != index } Pair(row[index], newRow) } }
0
Kotlin
0
0
3e99b70d0b8b447c56cc15ee3621a65031e1cf6e
2,026
Advent-of-Code-2017
Apache License 2.0
src/Day05.kt
SimoneStefani
572,915,832
false
{"Kotlin": 33918}
fun main() { fun numberOfStacks(lines: List<String>) = lines.dropWhile { it.contains("[") }.first().trim().split(" ").maxOf { it.toInt() } fun loadStacks(input: List<String>): List<ArrayDeque<String>> { val numberOfStacks = numberOfStacks(input) val stacks = List(numberOfStacks) { ArrayDeque<String>() } input.filter { it.contains("[") }.forEach { line -> line.chunked(4).mapIndexed { index, s -> if (s.isNotBlank()) stacks[index].addLast(s.trim().removeSurrounding("[", "]")) } } return stacks } fun parseMove(line: String): Triple<Int, Int, Int> { val captures = "move (\\d*) from (\\d*) to (\\d*)".toRegex().find(line)!!.groupValues val amount = captures[1].toInt() val from = captures[2].toInt() val to = captures[3].toInt() return Triple(amount, from, to) } fun part1(input: List<String>): String { val stacks = loadStacks(input) input.filter { it.startsWith("move") }.forEach { line -> val (amount, from, to) = parseMove(line) repeat(amount) { stacks[to - 1].addFirst(stacks[from - 1].removeFirst()) } } return stacks.joinToString("") { it.first() } } fun part2(input: List<String>): String { val stacks = loadStacks(input) input.filter { it.startsWith("move") }.forEach { line -> val (amount, from, to) = parseMove(line) stacks[from - 1].subList(0, amount).asReversed() .map { stacks[to - 1].addFirst(it) } .map { stacks[from - 1].removeFirst() } } return stacks.joinToString("") { it.first() } } 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
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
1,935
aoc-2022
Apache License 2.0
src/day13/puzzle13.kt
brendencapps
572,821,792
false
{"Kotlin": 70597}
package day13 import Puzzle import PuzzleInput import org.json.JSONArray import java.io.File import java.lang.Integer.min fun day13Puzzle() { Day13PuzzleSolution().solve(Day13PuzzleInput("inputs/day13/example.txt", 13)) Day13PuzzleSolution().solve(Day13PuzzleInput("inputs/day13/input.txt", 5675)) Day13Puzzle2Solution().solve(Day13Puzzle2Input("inputs/day13/example2.txt", 140)) Day13Puzzle2Solution().solve(Day13Puzzle2Input("inputs/day13/input2.txt", 20383)) } class Packet(val input: String) : Comparable<Packet> { private val packet = JSONArray(input) override fun compareTo(other: Packet): Int { return compare(packet, other.packet) } private fun compare(me: JSONArray, them: JSONArray): Int { for(i in 0 until min(me.length(), them.length())) { if(me.get(i) is Int && them[i] is Int) { val mine = me.getInt(i) val theirs = them.getInt(i) if(mine < theirs) return -1 if(theirs < mine) return 1 } else { val result = compare(getJSONArray(me, i), getJSONArray(them, i)) if(result != 0) return result } } return (me.length() - them.length()).coerceIn(-1, 1) } private fun getJSONArray(array: JSONArray, index: Int): JSONArray { return if(array.get(index) is Int) { val newArray = JSONArray() newArray.put(array.getInt(index)) newArray } else { array.getJSONArray(index) } } } class Day13PuzzleInput(val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) { val packetPairs: List<Pair<Packet, Packet>> = File(input).readText().split("\r\n\r\n").map { packetPairs -> val packetInput = packetPairs.lines() Pair(Packet(packetInput[0]), Packet(packetInput[1])) } } class Day13Puzzle2Input(val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) { val packets: List<Packet> = File(input).readLines().filter { it.isNotBlank() }.map { Packet(it)} } class Day13PuzzleSolution : Puzzle<Int, Day13PuzzleInput>() { override fun solution(input: Day13PuzzleInput): Int { return input.packetPairs.mapIndexed { index, pair -> if(pair.first <= pair.second) { index + 1 } else { 0 } }.sum() } } class Day13Puzzle2Solution : Puzzle<Int, Day13Puzzle2Input>() { override fun solution(input: Day13Puzzle2Input): Int { var divider1 = 0 var divider2 = 0 input.packets.sorted().forEachIndexed { index, packet -> //println(packet.input) if(packet.input == "[[2]]") { divider1 = index + 1 } else if(packet.input == "[[6]]") { divider2 = index + 1 } } return divider1 * divider2 } }
0
Kotlin
0
0
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
3,085
aoc_2022
Apache License 2.0
src/main/kotlin/Day07.kt
uipko
572,710,263
false
{"Kotlin": 25828}
const val totalSpace = 70_000_000 const val neededFreeSpace = 30_000_000 fun main() { val total = dirsSize("Day07.txt", 100_000) println("Total size $total") val freeUp = freeUpSpace("Day07.txt") println("Total size $freeUp") } data class Folder(val name: String, val folders: MutableList<Folder> = ArrayList(), var size: Int = 0) fun dirsSize(fileName: String, max: Int): Int { return getFolderSizes(fileName).filterValues { it < max }.values.sum() } fun freeUpSpace(fileName: String): Int { val folders = getFolderSizes(fileName) val needed = neededFreeSpace - (totalSpace - folders[listOf("/")]!!) return folders.filterValues { it > needed }.values.minOf { it } } private fun getFolderSizes(fileName: String): LinkedHashMap<List<String>, Int> { var key = mutableListOf<String>("/") var key1 = key return readInput(fileName).drop(1) .fold(linkedMapOf<List<String>, Int>(mutableListOf("/") to 0)) { initial, element -> var acc = initial with(element) { when { equals("$ cd ..") -> key1 = key1.dropLast(1).toMutableList() startsWith("$ cd") -> key1.add(substring(5)) startsWith("dir ") -> { acc.put(key1.plus(split(" ").last()), 0) } "^\\d+ ".toRegex().containsMatchIn(this) -> { var update = mutableListOf<String>() key1.forEach { update.add(it) acc[update] = acc[update]!! + this.split(" ").first().toInt() } } else -> null //ignore } } acc } }
0
Kotlin
0
0
b2604043f387914b7f043e43dbcde574b7173462
1,785
aoc2022
Apache License 2.0
src/Day02.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import kotlin.math.absoluteValue import kotlin.math.sign /** * Rock, Paper, Scissors: extendable to any odd number */ private enum class Throw { A, B, C; // Rock, Paper, Scissors val value = ordinal + 1 /** * This is similar to `compareTo`: Returns zero if this Throw * draws the other Throw, a negative number if it loses, or a * positive number if it wins. */ fun beats(other: Throw): Int { val difference = ordinal - other.ordinal return if (difference.absoluteValue > Throw.values().size / 2) { difference - difference.sign * Throw.values().size } else { difference } } fun score(other: Throw) = value + values().size * (1 + beats(other).sign) /** * Return a Throw that loses to this one if `outcome` is * negative, wins if it is positive, or draws otherwise. */ fun fromOutcome(outcome: Int) = values()[(ordinal + outcome.sign).mod(values().size)] } fun main() { val strategyGuide = readInput("Day02").map { it.split(" ") } val partOneKey = mapOf("X" to Throw.A, "Y" to Throw.B, "Z" to Throw.C) println( strategyGuide.sumOf { (them, us) -> val ourThrow = partOneKey[us]!! // If it doesn't exist, strategy guide is malformed val theirThrow = Throw.valueOf(them) ourThrow.score(theirThrow) } ) val partTwoKey = mapOf("X" to -1, "Y" to 0, "Z" to 1) println( strategyGuide.sumOf { (them, us) -> val outcome = partTwoKey[us]!! // If it doesn't exist, strategy guide is malformed val theirThrow = Throw.valueOf(them) val ourThrow = theirThrow.fromOutcome(outcome) ourThrow.score(theirThrow) } ) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
1,773
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day14.kt
andrewrlee
434,584,657
false
{"Kotlin": 29493, "Clojure": 14117, "Shell": 398}
import java.io.File import java.nio.charset.StandardCharsets.UTF_8 import kotlin.collections.Map.Entry object Day14 { object Part1 { private fun toRule(s: String): Pair<List<Char>, Char> { val (pair, value) = s.split(" -> ") return pair.toCharArray().let { listOf(it[0], it[1]) } to value[0] } private fun step( input: List<Char>, rules: Map<List<Char>, Char> ) = input.windowed(2, 1) .flatMap { p -> rules[p]?.let { listOf(p[0], it) } ?: listOf(p[0]) } + input.last() fun run() { val lines = File("day14/input-real.txt").readLines(UTF_8) val input = lines.first().toCharArray().toList() val rules = lines.drop(2).associate(::toRule) val result = generateSequence(input) { step(it, rules) }.drop(10).first() val freqs = result.groupingBy { it }.eachCount().entries val max = freqs.maxOf { it.value } val min = freqs.minOf { it.value } println(max - min) } } object Part2 { private fun toRule(s: String): Pair<List<Char>, Char> { val (pair, value) = s.split(" -> ") return pair.toCharArray().let { listOf(it[0], it[1]) } to value[0] } private fun toTransitions() = { (k, v): Entry<List<Char>, Char> -> (k[0] to k[1]) to listOf(k[0] to v, v to k[1]) } private fun step( values: MutableMap<Pair<Char, Char>, Long>, transitions: Map<Pair<Char, Char>, List<Pair<Char, Char>>> ): MutableMap<Pair<Char, Char>, Long> { val newValues = values.flatMap { (k, v) -> val new = transitions[k]!! new.map { it to v } }.groupBy({ it.first }, { it.second }).mapValues { it.value.sum() } return newValues.toMutableMap(); } fun run() { val lines = File("day14/input-real.txt").readLines(UTF_8) val input = lines.first().toCharArray().toList() val rules = lines.drop(2).associate(::toRule) val transitions = rules.map(toTransitions()).toMap() val initialFreqs = input .windowed(2, 1) .map { it[0] to it[1] } .groupingBy { it } .eachCount() .mapValues { it.value.toLong() } .toMutableMap() val result = generateSequence(initialFreqs) { step(it, transitions) }.drop(40).first() val freqs = result.entries .groupBy({ it.key.first }, { it.value }) .mapValues { it.value.sum() } .toMutableMap().also { // Add single last character in it[input.last()] = 1L + it[input.last()]!! } val max = freqs.maxOf { it.value } val min = freqs.minOf { it.value } println(max - min) } } } fun main() { Day14.Part1.run() Day14.Part2.run() }
0
Kotlin
0
0
aace0fccf9bb739d57f781b0b79f2f3a5d9d038e
3,090
adventOfCode2021
MIT License
src/day09/Day09.kt
treegem
572,875,670
false
{"Kotlin": 38876}
package day09 import common.readInput fun main() { fun part1(input: List<String>): Int { val head = Head() val tail = FollowingKnot(head) input .toDirections() .forEach { head.move(it) tail.adjustToLeadingKnot() } return tail.visitedDistinctPositions.size } fun part2(input: List<String>): Int { val head = Head() val middleKnots = mutableListOf(FollowingKnot(head)) repeat((3..9).count()) { middleKnots.add(FollowingKnot(middleKnots.last())) } val tail = FollowingKnot(middleKnots.last()) input .toDirections() .forEach { head.move(it) middleKnots.forEach(FollowingKnot::adjustToLeadingKnot) tail.adjustToLeadingKnot() } return tail.visitedDistinctPositions.size } val day = "09" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) } private fun List<String>.toDirections() = this.map(::Command) .flatMap { command -> List(command.repetition) { command.direction } } private class Command(string: String) { private val commandComponents = string.split(" ") val repetition = commandComponents.last().toInt() val direction = Direction.fromString(commandComponents.first()) }
0
Kotlin
0
0
97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8
1,591
advent_of_code_2022
Apache License 2.0
src/Day04.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
fun main() { fun part1(input: String): Int { return input.split("\n") .map { var rangeOne = it.split(",")[0].split("-") var rangeTwo = it.split(",")[1].split("-") val setOne =(rangeOne[0].toInt() .. rangeOne[1].toInt()).toMutableSet() val setTwo = (rangeTwo[0].toInt() .. rangeTwo[1].toInt()).toMutableSet() val setOneSize = setOne.size val setTwoSize = setTwo.size setOne.retainAll(setTwo) if (setOne.size == setOneSize || setOne.size == setTwoSize) 1 else 0 }.sumOf { it } } fun part2(input: String): Int { return input.split("\n") .map { var rangeOne = it.split(",")[0].split("-") var rangeTwo = it.split(",")[1].split("-") val setOne =(rangeOne[0].toInt() .. rangeOne[1].toInt()).toMutableSet() val setTwo = (rangeTwo[0].toInt() .. rangeTwo[1].toInt()).toMutableSet() val setOneSize = setOne.size val setTwoSize = setTwo.size setOne.retainAll(setTwo) if (setOne.size > 0) 1 else 0 }.sumOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val output = part1(testInput) check(output== 2) val outputTwo = part2(testInput) check(outputTwo== 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
1,735
aoc-kotlin
Apache License 2.0