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/Day02.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | fun main() {
val input = readInput("Day02")
println(Day02.part1(input))
println(Day02.part2(input))
}
class Day02 {
companion object {
private fun checkGuessRound(it: String): Int {
val (a, b) = it.split(" ").map { it.toCharArray().first() }
val selectionPoints = b.code - 87
val score = when (selectionPoints == a.code - 64) {
true -> 1
false -> when (b) {
'X' -> when (a) {
'C' -> 2
else -> 0
}
'Y' -> when (a) {
'A' -> 2
else -> 0
}
'Z' -> when (a) {
'B' -> 2
else -> 0
}
else -> 0
}
}
return selectionPoints + (score * 3)
}
fun part1(input: List<String>): Int {
return input.sumOf { checkGuessRound(it) }
}
private fun checkExpectedRound(it: String): Int {
val (a, b) = it.split(" ").map { it.toCharArray().first() }
val score = (b.code - 88)
val selectionPoints = when (score) {
0 -> when (a) {
'A' -> 3
'B' -> 1
else -> 2
}
1 -> when (a) {
'A' -> 1
'B' -> 2
else -> 3
}
2 -> when (a) {
'A' -> 2
'B' -> 3
else -> 1
}
else -> 0
}
return selectionPoints + (score * 3)
}
fun part2(input: List<String>): Int {
return input.sumOf { checkExpectedRound(it) }
}
}
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 1,928 | advent-of-code-22 | Apache License 2.0 |
src/Day16b.kt | jrmacgill | 573,065,109 | false | {"Kotlin": 76362} | import java.lang.Integer.min
class Day16b {
val inputLineRegex = """Valve ([A-Z]*) has flow rate=(\d+); tunnel[s]? lead[s]? to valve[s]? (.*)""".toRegex()
val data = mutableMapOf<String, Room>()
val compactData = mutableMapOf<String, CompactRoom>()
val maxTicks = 30
var best = 0
class Room(val id : String, val flow : Int, val links : List<String>) {
}
class CompactRoom(val id : String, val flow : Int, val links : List<Pair<String,Int>>) {
}
fun maxRemain(open : List<String>, tick : Int) : Int {
var remain = 0
compactData.forEach { v ->
if (!open.contains(v.key)) {
remain += v.value.flow * (maxTicks-tick)
}
}
return remain
}
fun step(room : CompactRoom , tick : Int, open : List<String>, score:Int) {
if (tick == maxTicks) {
println("Done with: " + score)
if (score > best) {
best = score
best = score
}
return
}
if (open.size == compactData.size) {
println("All open with " + score)
return
}
if (maxRemain(open, tick)+score <= best) {
//println("Crap, giveup")
return
}
if (!open.contains(room.id)) {
var next = open.toMutableList()
next.add(room.id)
step(room, tick+1,next, score + (room.flow*(maxTicks-(tick+1))))
}
room.links.forEach{
if (!open.contains(it.first)) {
// println("step to " + it.trim())
step(compactData[it.first.trim()]!!, tick + it.second, open, score)
}
}
}
fun cost(room : String, target : String, visited : List<String>, cost: Int) : Int {
if (room.trim() == target.trim()) return cost;
var best = Int.MAX_VALUE
data[room.trim()]!!.links.filter { r -> !visited.contains(r) }.forEach{
var c = cost(it, target, visited+room, cost+1)
best = min(c, best)
}
return best
}
fun compact(room: Room) : CompactRoom{
//var visited = listOf<String>()
var costLinks = mutableListOf<Pair<String, Int>>()
data.forEach{
if (it.key != room.id) {
if (data[it.key]!!.flow > 0) {
var cost = cost(room.id, it.key, listOf(), 0)
costLinks.add(Pair(it.key, cost))
}
}
}
return CompactRoom(room.id, room.flow, costLinks)
}
fun parse(line : String) {
val match = inputLineRegex
.find(line)!!
println(match)
val (code, flow, links) = match.destructured
data[code] = Room(code, flow.toInt(), links.split(","))
}
fun go() {
var lines =readInput("day16_test")
lines.forEach(::parse)
println("compacting")
compactData["AA"] = compact(data["AA"]!!)
data.forEach {
if(it.value.flow > 0) {
println("compact " + it.key)
compactData[it.key] = compact(it.value)
}
}
println(compactData)
println("find:")
step(compactData["AA"]!!, 0, listOf<String>(), 0)
println(best)
}
}
fun main() {
Day16b().go()
} | 0 | Kotlin | 0 | 1 | 3dcd590f971b6e9c064b444139d6442df034355b | 3,358 | aoc-2022-kotlin | Apache License 2.0 |
src/main/java/Main.kt | Koallider | 557,760,682 | false | {"Kotlin": 8930} | import kotlin.math.min
fun main() {
val trie = buildTrieForResource("words.txt")
println("Enter letters to solve")
val letters = "SAGNETISD".lowercase().toCharArray()
//val letters = readLine()!!.toCharArray()
println(searchForAllPermutations(trie, letters).subList(0, 10))
}
fun searchForAllPermutations(trie: Trie, chars: CharArray): List<String> {
val results = HashSet<String>()
val size = chars.size
chars.sort()
var isFinished = false
while (!isFinished) {
val searchResult = trie.searchAll(String(chars))
results.addAll(searchResult.words)
var i = min(searchResult.longestMatch, size - 2)
//by doing this we throw away all permutations from index i
//which are not in the dictionary
chars.sortDescending(i + 1, size)
while (i >= 0) {
if (chars[i] < chars[i + 1])
break
i--
}
if (i == -1) {
isFinished = true
} else {
val ceilIndex = chars.findCeil(i)
chars.swap(i, ceilIndex)
chars.reverse(i + 1, size - 1)
}
}
return results.toList().sortedByDescending { it.length }
}
private fun CharArray.swap(a: Int, b: Int) {
val tmp = this[a]
this[a] = this[b]
this[b] = tmp
}
fun CharArray.reverse(fromIndex: Int, toIndex: Int) {
var l = fromIndex
var r = toIndex
while (l < r) {
swap(l, r)
l++
r--
}
}
// This function finds the index of the smallest
// character which is greater than this[fromIndex] character
// and goes after fromIndex
fun CharArray.findCeil(fromIndex: Int): Int {
var ceilIndex = fromIndex + 1
for (i in fromIndex + 1 until this.size){
if (this[i] > this[fromIndex] && this[i] <= this[ceilIndex]){
ceilIndex = i
}
}
return ceilIndex
}
| 0 | Kotlin | 0 | 0 | 9faa2e3e14d1daba1d6a9e4530f03b22ddeace77 | 1,889 | 8OO10CDC | Apache License 2.0 |
y2020/src/main/kotlin/adventofcode/y2020/Day24.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
fun main() = Day24.solve()
object Day24 : AdventSolution(2020, 24, "Lobby Layout")
{
override fun solvePartOne(input: String) = blackTiles(input).size
override fun solvePartTwo(input: String) = generateSequence(Conway(blackTiles(input)), Conway::next)
.take(101).last().activeCells.size
private fun blackTiles(input: String): Set<Vec2> = input.lines()
.map(::parse)
.map(this::toCoordinate)
.groupingBy { it }
.eachCount()
.filterValues { it % 2 == 1 }
.keys
private fun parse(input: String): List<Direction> = buildList {
val iter = input.iterator()
while (iter.hasNext())
{
val new = when (iter.nextChar())
{
'e' -> Direction.E
'w' -> Direction.W
'n' -> if (iter.nextChar() == 'e') Direction.NE else Direction.NW
's' -> if (iter.nextChar() == 'e') Direction.SE else Direction.SW
else -> throw IllegalStateException()
}
add(new)
}
}
private fun toCoordinate(input: List<Direction>) = input.fold(Vec2.origin, Vec2::step)
}
private fun Vec2.step(d: Direction) = when (d)
{
Direction.NE -> Vec2(x + 1, y + 1)
Direction.E -> Vec2(x + 1, y)
Direction.SE -> Vec2(x, y - 1)
Direction.SW -> Vec2(x - 1, y - 1)
Direction.W -> Vec2(x - 1, y)
Direction.NW -> Vec2(x, y + 1)
}
private enum class Direction
{ NE, E, SE, SW, W, NW }
private data class Conway(val activeCells: Set<Vec2>)
{
fun next(): Conway = activeCells
.flatMapTo(mutableSetOf(), this::neighborhood)
.let {
it.retainAll(this::aliveInNext)
Conway(it)
}
private fun aliveInNext(c: Vec2): Boolean = neighborhood(c).count { it in activeCells } in if (c in activeCells) 2..3 else 2..2
private fun neighborhood(c: Vec2) = Direction.values().map(c::step) + c
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,054 | advent-of-code | MIT License |
src/main/kotlin/day23.kt | Gitvert | 725,292,325 | false | {"Kotlin": 97000} | import java.util.*
val DIRECTIONS = mutableListOf(Pos(1, 0), Pos(-1, 0), Pos(0, 1), Pos(0, -1))
var longestHike = -1
fun day23 (lines: List<String>) {
val hikes = mutableListOf(Hike(mutableSetOf(Pos(1, 0))))
val maxX = lines[0].indices.last
val maxY = lines.indices.last
while (hikes.isNotEmpty()) {
walk(lines, hikes, maxX, maxY)
}
longestHike--
println("Day 23 part 1: $longestHike")
val intersections = findIntersections(lines, maxX, maxY)
val paths = findPaths(lines, maxX, maxY, intersections)
dfs(paths, maxX, maxY)
println("Day 23 part 2: $longestHike")
println()
}
fun walk(lines: List<String>, hikes: MutableList<Hike>, maxX: Int, maxY: Int) {
val newHikes = mutableListOf<Hike>()
hikes.forEach { hike ->
if (hike.steps.contains(Pos(maxX - 1, maxY)) && hike.steps.size > longestHike) {
longestHike = hike.steps.size
}
val currentPos = hike.steps.last()
DIRECTIONS.forEach { dir ->
val nextSteps = getNextSteps(lines, currentPos, dir, hike.steps, maxX, maxY)
if (nextSteps.isNotEmpty()) {
val newHike = Hike(hike.steps.toMutableSet())
newHike.steps.addAll(nextSteps)
newHikes.add(newHike)
}
}
}
hikes.clear()
hikes.addAll(newHikes)
}
fun getNextSteps(lines: List<String>, pos: Pos, dir: Pos, steps: MutableSet<Pos>, maxX: Int, maxY: Int): List<Pos> {
if (pos == Pos(maxX - 15, maxY - 11) && dir != Pos(0, 1)) {
return listOf()
}
val nextStep = Pos(pos.x + dir.x, pos.y + dir.y)
if (nextStep.x in 0..maxX && nextStep.y in 0..maxY && lines[nextStep.y][nextStep.x] != '#' && !steps.contains(nextStep)) {
val cell = lines[nextStep.y][nextStep.x]
return when (cell) {
'>' -> {
if (!steps.contains(Pos(nextStep.x + 1, nextStep.y))) {
listOf(nextStep, Pos(nextStep.x + 1, nextStep.y))
} else {
listOf()
}
}
'v' -> {
if (!steps.contains(Pos(nextStep.x, nextStep.y + 1))) {
listOf(nextStep, Pos(nextStep.x, nextStep.y + 1))
} else {
listOf()
}
}
else -> listOf(nextStep)
}
}
return listOf()
}
fun dfs(paths: MutableMap<Pos, List<Pair<Pos, Int>>>, maxX: Int, maxY: Int) {
val target = Pos(maxX - 1, maxY)
val stack = ArrayDeque(listOf<DryHike>())
stack.addLast(DryHike(mutableSetOf(), Pos(1, 0), 0))
while (stack.isNotEmpty()) {
val current = stack.removeLast()
val currentIntersection = paths[current.pos]!!
if (current.pos == target) {
if (current.steps > longestHike) {
longestHike = current.steps
continue
}
}
if (currentIntersection.map { it.first }.any { it == target }) {
val intersection = currentIntersection.find { it.first == target }!!
val newVisited = current.visited.toMutableSet()
newVisited.add(intersection.first)
stack.addLast(DryHike(newVisited, intersection.first, current.steps + intersection.second))
continue
}
currentIntersection.forEach { intersection ->
if (!current.visited.contains(intersection.first)) {
val newVisited = current.visited.toMutableSet()
newVisited.add(intersection.first)
stack.addLast(DryHike(newVisited, intersection.first, current.steps + intersection.second))
}
}
}
}
fun bfs(lines: List<String>, maxX: Int, maxY: Int, start: Pos, intersections: Set<Pos>): MutableList<Pair<Pos, Int>> {
val queue: Queue<Path> = LinkedList()
val paths = mutableListOf<Pair<Pos, Int>>()
val visited = mutableListOf(start)
queue.add(Path(start, 0))
while(queue.isNotEmpty()) {
val current = queue.peek()
queue.remove()
DIRECTIONS.forEach { dir ->
val posToCheck = Pos(current.pos.x + dir.x, current.pos.y + dir.y)
if (posToCheck != start && intersections.contains(posToCheck)) {
paths.add(Pair(posToCheck, current.steps + 1))
} else if (isValid(lines, maxX, maxY, posToCheck, visited)) {
visited.add(posToCheck)
queue.add(Path(posToCheck, current.steps + 1))
}
}
}
return paths
}
fun isValid(lines: List<String>, maxX: Int, maxY: Int, pos: Pos, visited: MutableList<Pos>): Boolean {
if (visited.contains(pos)) {
return false
}
return isWalkable(lines, pos, maxX, maxY)
}
fun findPaths(lines: List<String>, maxX: Int, maxY: Int, intersections: Set<Pos>): MutableMap<Pos, List<Pair<Pos, Int>>> {
val paths = mutableMapOf<Pos, List<Pair<Pos, Int>>>()
intersections.forEach { intersection ->
paths[intersection] = bfs(lines, maxX, maxY, intersection, intersections)
}
return paths
}
fun findIntersections(lines: List<String>, maxX: Int, maxY: Int): MutableSet<Pos> {
val intersections = mutableSetOf(Pos(1, 0), Pos(maxX - 1, maxY))
for (y in lines.indices) {
for (x in lines[0].indices) {
if (lines[y][x] == '#') {
continue
}
var walkableDirections = 0
DIRECTIONS.forEach { dir ->
if (isWalkable(lines, Pos(x + dir.x, y + dir.y), maxX, maxY)) {
walkableDirections++
}
}
if (walkableDirections > 2) {
intersections.add(Pos(x, y))
}
}
}
return intersections
}
fun isWalkable(lines: List<String>, pos: Pos, maxX: Int, maxY: Int): Boolean {
return pos.x in 0..maxX && pos.y in 0..maxY && lines[pos.y][pos.x] != '#'
}
data class Path(val pos: Pos, val steps: Int)
data class Hike(val steps: MutableSet<Pos>)
data class DryHike(val visited: MutableSet<Pos>, val pos: Pos, val steps: Int) | 0 | Kotlin | 0 | 0 | f204f09c94528f5cd83ce0149a254c4b0ca3bc91 | 6,203 | advent_of_code_2023 | MIT License |
kotlin/src/com/leetcode/221_MaximalSquare.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import kotlin.math.max
/**
* We use the additional matrix of sides b.
* The b[i][j] representes the max side that is possible for the square,
* which right-down corner is placed in (i,j) coordinate.
*
* For instance, with given:
* 1 1 1 0 0
* 1 1 1 1 0
* 1 1 1 1 1
* 0 1 1 1 0
*
* we will have next b:
* 1 1 1 0 0
* 1 2 2 1 0
* 1 2 3 2 1
* 0 1 2 3 0
*
* While we building b array we can remember the max side we will face,
* which is 3 in the example above.
*
* Time: O(n*m). Space: O(n*m)
*/
private class Solution221 {
fun maximalSquare(matrix: Array<CharArray>): Int {
val maxSides = Array<IntArray>(matrix.size) { IntArray(matrix[it].size) }
var result = 0
matrix.forEachIndexed { i, row ->
row.forEachIndexed { j, c ->
if (c == '1') {
if (i == 0 || j == 0) {
maxSides[i][j] = 1
result = max(result, maxSides[i][j])
} else {
maxSides[i][j] = minOf(maxSides[i - 1][j - 1], maxSides[i - 1][j], maxSides[i][j - 1]) + 1
result = max(result, maxSides[i][j])
}
}
}
}
return result * result
}
}
fun main() {
println(Solution221().maximalSquare(arrayOf(
charArrayOf('1', '0', '1', '0', '0'),
charArrayOf('1', '0', '1', '1', '1'),
charArrayOf('1', '1', '1', '1', '1'),
charArrayOf('1', '0', '0', '1', '0')
)))
}
| 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 1,570 | problemsolving | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2977_minimum_cost_to_convert_string_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2977_minimum_cost_to_convert_string_ii
// #Hard #Array #String #Dynamic_Programming #Graph #Trie #Shortest_Path
// #2024_01_19_Time_697_ms_(100.00%)_Space_51.2_MB_(64.29%)
import kotlin.math.min
class Solution {
fun minimumCost(
source: String,
target: String,
original: Array<String>,
changed: Array<String>,
cost: IntArray
): Long {
val index = HashMap<String, Int>()
for (o in original) {
if (!index.containsKey(o)) {
index[o] = index.size
}
}
for (c in changed) {
if (!index.containsKey(c)) {
index[c] = index.size
}
}
val dis = Array(index.size) { LongArray(index.size) }
for (i in dis.indices) {
dis[i].fill(Long.MAX_VALUE)
dis[i][i] = 0
}
for (i in cost.indices) {
dis[index[original[i]]!!][index[changed[i]]!!] =
min(dis[index[original[i]]!!][index[changed[i]]!!], cost[i].toLong())
}
for (k in dis.indices) {
for (i in dis.indices) {
if (dis[i][k] < Long.MAX_VALUE) {
for (j in dis.indices) {
if (dis[k][j] < Long.MAX_VALUE) {
dis[i][j] = min(dis[i][j], (dis[i][k] + dis[k][j]))
}
}
}
}
}
val set = HashSet<Int>()
for (o in original) {
set.add(o.length)
}
val dp = LongArray(target.length + 1)
dp.fill(Long.MAX_VALUE)
dp[0] = 0L
for (i in target.indices) {
if (dp[i] == Long.MAX_VALUE) {
continue
}
if (target[i] == source[i]) {
dp[i + 1] = min(dp[i + 1], dp[i])
}
for (t in set) {
if (i + t >= dp.size) {
continue
}
val c1 = index.getOrDefault(source.substring(i, i + t), -1)
val c2 = index.getOrDefault(target.substring(i, i + t), -1)
if (c1 >= 0 && c2 >= 0 && dis[c1][c2] < Long.MAX_VALUE) {
dp[i + t] = min(dp[i + t], (dp[i] + dis[c1][c2]))
}
}
}
return if (dp[dp.size - 1] == Long.MAX_VALUE) -1L else dp[dp.size - 1]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,434 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day17.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day17 : Solvable("17") {
override fun solveA(input: List<String>): String {
return maxHeight(getYRange(input.first()).first).toString()
}
override fun solveB(input: List<String>): String {
val yStepMap =
HashMap<Int, Set<YStep>>().also {
for (y in getYRange(input.first())) {
it[y] =
(y..(Math.abs(y) - 1))
.map { numStepsY(it, y) }
.filterNotNull()
.toSet()
}
}
val xStepMap =
HashMap<Int, Pair<Set<XStep>, XStep?>>().also {
for (x in getXRange(input.first())) {
val steps = (1..x).map { numStepsX(it, x) }.filterNotNull()
val lowestBound = steps.filter { it.unbounded }.minBy { it.steps }
val values =
steps
.filter { it.steps < lowestBound?.steps ?: Int.MAX_VALUE }
.toSet()
it[x] = Pair(values, lowestBound)
}
}
var positions = HashSet<Pair<Int, Int>>()
for (y in getYRange(input.first())) {
for (x in getXRange(input.first())) {
val ySteps = yStepMap[y]!!
val (xSteps, lowestBound) = xStepMap[x]!!
for (ys in ySteps) {
for (xs in xSteps) {
if (ys.steps == xs.steps ) {
positions.add(Pair(xs.x, ys.y))
} else if (lowestBound is XStep && ys.steps >= lowestBound.steps) {
positions.add(Pair(lowestBound.x, ys.y))
}
}
}
}
}
return positions.size.toString()
}
private fun numStepsX(x: Int, targetX: Int): XStep? {
var steps = 0
var xStep = x
var xPos = 0
while (xPos < targetX && xStep > 0) {
xPos += xStep--
steps++
}
return if (xPos == targetX) XStep(steps, x, xStep == 0) else null
}
private fun numStepsY(y: Int, targetY: Int): YStep? {
var steps = 0
var yStep = y
var yPos = 0
while (yPos > targetY) {
yPos += yStep--
steps++
}
return if (yPos == targetY) YStep(steps, y) else null
}
private fun maxHeight(y: Int) = (Math.abs(y) - 1).let { it * (it + 1) / 2 }
private fun getXRange(line: String): IntProgression {
val start = line.indexOfFirst({ it == '=' })
val end = line.indexOfFirst { it == ',' }
return getRange(line, start + 1, end)
}
private fun getYRange(line: String): IntProgression {
val start = line.lastIndexOf('=')
return getRange(line, start + 1, line.length)
}
private fun getRange(line: String, start: Int, end: Int): IntProgression {
val (l, r) = line.substring(start, end).split("..").map(String::toInt)
return l..r
}
}
abstract class Step(val steps: Int) {
override fun equals(other: Any?): Boolean = if (other is Step) steps == other.steps else false
override fun hashCode(): Int =steps.hashCode()
}
class XStep(steps: Int, val x: Int, val unbounded: Boolean) : Step(steps) {
override fun toString(): String = "$steps; $x; $unbounded"
}
class YStep(steps: Int, val y: Int) : Step(steps) {
override fun toString(): String = "$steps; $y"
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 3,722 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/day09/Day09.kt | tschens95 | 573,743,557 | false | {"Kotlin": 32775} | package day09
import readInput
import kotlin.math.abs
fun main() {
fun adjacent(h: Pair<Int, Int>, t: Pair<Int, Int>): Boolean {
val xDiff = abs(h.first - t.first)
val yDiff = abs(h.second - t.second)
return (xDiff == 0 && yDiff == 0) || (xDiff == 0 && yDiff == 1) || (xDiff == 1 && yDiff == 0)
}
fun diagonal(h: Pair<Int, Int>, t: Pair<Int, Int>): Boolean {
val xDiff = abs(h.first - t.first)
val yDiff = abs(h.second - t.second)
return (xDiff == 1 && yDiff == 1)
}
fun part1(input: List<String>): Int {
val positions: MutableSet<Pair<Int, Int>> = mutableSetOf()
var posH = (0 to 0)
var posT = posH
positions.add(posT)
val commands = input.map { Command(it.split(" ")[0], it.split(" ")[1].toInt()) }
commands.forEach {
when (it.direction) {
"R" -> for (i in 0 until it.value) {
posH = posH.copy(first = posH.first + 1)
if (!adjacent(posH, posT) && !diagonal(posH, posT)) {
posT = posT.copy(posT.first + 1, posH.second)
positions.add(posT)
}
}
"L" -> for (i in 0 until it.value) {
posH = posH.copy(first = posH.first - 1)
if (!adjacent(posH, posT) && !diagonal(posH, posT)) {
posT = posT.copy(posT.first - 1, posH.second)
positions.add(posT)
}
}
"U" -> for (i in 0 until it.value) {
posH = posH.copy(second = posH.second + 1)
if (!adjacent(posH, posT) && !diagonal(posH, posT)) {
posT = posT.copy(posH.first, posT.second + 1)
positions.add(posT)
}
}
"D" -> for (i in 0 until it.value) {
posH = posH.copy(second = posH.second - 1)
if (!adjacent(posH, posT) && !diagonal(posH, posT)) {
posT = posT.copy(posH.first, posT.second - 1)
positions.add(posT)
}
}
}
}
return positions.size
}
val testInput = "R 4\n" +
"U 4\n" +
"L 3\n" +
"D 1\n" +
"R 4\n" +
"D 1\n" +
"L 5\n" +
"R 2"
println(part1(testInput.split("\n")))
println(part1(readInput("09")))
} | 0 | Kotlin | 0 | 2 | 9d78a9bcd69abc9f025a6a0bde923f53c2d8b301 | 2,569 | AdventOfCode2022 | Apache License 2.0 |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day14/day14.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day14
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input14-test.txt"
const val FILENAME = "input14.txt"
const val NUMBER_OF_ITERATIONS = 1000000000
fun main() {
val platform = readLines(2023, FILENAME).let { Platform.parse(it) }
part1(platform)
part2(platform)
}
private fun part1(platform: Platform) {
val shifted = platform.shiftUp()
println(shifted.weight())
}
fun part2(platform: Platform) {
val cyclesPerPlatform = mutableMapOf<Platform, Int>()
val weights = mutableListOf<Int>()
var current = platform
var cycles = 0
while (true) {
current = current.cycle()
if (cyclesPerPlatform.containsKey(current)) {
break
}
val weight = current.weight()
cyclesPerPlatform[current] = cycles++
weights.add(weight)
}
val initial = cyclesPerPlatform[current]!!
val repetition = cycles - initial
val index = (NUMBER_OF_ITERATIONS - initial - 1) % repetition + initial
println(weights[index])
}
enum class Rock(val ch: Char) {
ROUND('O'),
CUBE('#'),
NONE('.');
companion object {
fun parse(ch: Char) = entries.first { it.ch == ch }
}
}
data class Platform(val size: Int, val rocks: List<Rock>) {
fun shiftUp(): Platform {
val newRocks = rocks.toMutableList()
fun get(x: Int, y: Int) = newRocks[index(x, y)]
fun set(x: Int, y: Int, rock: Rock) {
newRocks[index(x, y)] = rock
}
for (y in 0 until size) {
for (x in 0 until size) {
if (get(x, y) == Rock.ROUND) {
var newY = y
while (newY > 0 && get(x, newY - 1) == Rock.NONE) newY--
set(x, y, Rock.NONE)
set(x, newY, Rock.ROUND)
}
}
}
return Platform(size, newRocks)
}
private fun rotateRight(): Platform {
val newRocks = (0..<size).flatMap { y ->
(0..<size).map { x -> get(y, size - x - 1) }
}
return Platform(size, newRocks)
}
fun cycle(): Platform {
var current = this
for (i in 1..4) {
current = current.shiftUp().rotateRight()
}
return current
}
fun weight(): Int {
return (0..<size).sumOf { y ->
(0..<size).count { x -> get(x, y) == Rock.ROUND } * (size - y)
}
}
fun print() {
for (y in 0 until size) {
for (x in 0 until size) {
print(get(x, y).ch)
}
println()
}
println()
}
fun get(x: Int, y: Int) = rocks[index(x, y)]
private fun index(x: Int, y: Int) = y * size + x
companion object {
fun parse(input: List<String>): Platform {
val size = input[0].length
val rocks = input.flatMap { line -> line.toCharArray().map { Rock.parse(it) } }
return Platform(size, rocks)
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,543 | advent-of-code | Apache License 2.0 |
src/Day11.kt | ricardorlg-yml | 573,098,872 | false | {"Kotlin": 38331} | data class Monkey(
val id: Int,
private val itemOperation: (Long) -> Long,
private val reliefOperation: (Long) -> Long,
val divisibleBy: Int,
private val nextMonkeyIdOnTrue: Int,
private val nextMonkeyIdOnFalse: Int,
private val items: MutableList<Long>,
) {
private fun addItem(item: Long) {
items.add(item)
}
fun processItems(monkeys: List<Monkey>, includeRelief: Boolean, upperLimit: Int): Int {
var counter = 0
while (items.isNotEmpty()) {
counter += 1
var worryLevel = items.removeFirst()
worryLevel = itemOperation(worryLevel)
worryLevel = (if (includeRelief) reliefOperation(worryLevel) else worryLevel) % upperLimit
if (worryLevel % divisibleBy == 0L) {
monkeys[nextMonkeyIdOnTrue].addItem(worryLevel)
} else {
monkeys[nextMonkeyIdOnFalse].addItem(worryLevel)
}
}
return counter
}
override fun toString(): String {
return "Monkey $id: ${items.joinToString(", ")}"
}
}
class Day11Solver(private val data: List<List<String>>) {
fun solvePart1(printSteps: Boolean): Long {
return solve(rounds = 20, includeBoring = true, printSteps)
}
fun solvePart2(printSteps: Boolean): Long {
return solve(rounds = 10_000, includeBoring = false, printSteps)
}
private fun solve(rounds: Int, includeBoring: Boolean, printSteps: Boolean = false): Long {
val monkeys = processInput()
val roundsToPrint = listOf(1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000)
val maxDiv = monkeys.fold(1) { acc, monkey -> acc * monkey.divisibleBy }
val inspectedItemsByMonkey = monkeys.associate { it.id to 0 }.toMutableMap()
(1..rounds).forEach { round ->
if (printSteps)
println("Round $round")
monkeys.forEach { monkey ->
val inspected = monkey.processItems(monkeys, includeBoring, maxDiv)
inspectedItemsByMonkey[monkey.id] = inspectedItemsByMonkey[monkey.id]!! + inspected
}
if (printSteps) {
monkeys.forEach { monkey ->
println(monkey)
}
}
if (printSteps) {
if (round in roundsToPrint) {
println("Inspected items by monkey: after round $round")
inspectedItemsByMonkey.forEach { (monkeyId, inspectedItems) ->
println("Monkey $monkeyId: inspected items $inspectedItems times")
}
}
}
}
return inspectedItemsByMonkey
.values
.sorted()
.takeLast(2)
.map { it.toLong() }
.reduce(Long::times)
}
private fun processInput(): List<Monkey> {
return data.mapIndexed { index, monkeyData ->
val items = monkeyData[1].substringAfter(":").split(",").map { it.trim().toLong() }
Monkey(
id = index,
itemOperation = getOperation(monkeyData[2].substringAfterLast("=").trim()),
reliefOperation = { it / 3 },
divisibleBy = monkeyData[3].substringAfter("by").trim().toInt(),
nextMonkeyIdOnTrue = monkeyData[4].substringAfterLast(" ").trim().toInt(),
nextMonkeyIdOnFalse = monkeyData[5].substringAfterLast(" ").trim().toInt(),
items = items.toMutableList(),
)
}
}
private fun getOperation(operation: String): (Long) -> Long {
if (operation.contains("+")) {
val (a, b) = operation.split("+").map { it.trim() }
return {
(a.toLongOrNull() ?: it) + (b.toLongOrNull() ?: it)
}
}
if (operation.contains("*")) {
val (a, b) = operation.split("*").map { it.trim() }
return {
(a.toLongOrNull() ?: it) * (b.toLongOrNull() ?: it)
}
}
if (operation.contains("/")) {
val (a, b) = operation.split("/").map { it.trim() }
return {
(a.toLongOrNull() ?: it) / (b.toLongOrNull() ?: it)
}
}
if (operation.contains("-")) {
val (a, b) = operation.split("-").map { it.trim() }
return {
(a.toLongOrNull() ?: it) - (b.toLongOrNull() ?: it)
}
}
throw IllegalStateException("Unable to parse operation: $operation")
}
}
fun main() {
// val data = readInputString("Day11_test").split("\n\n").map { it.split("\n") }
// check(Day11Solver(data).solvePart1(false) == 10605L)
// check(Day11Solver(data).solvePart2(false) == 2713310158L)
val data = readInputString("Day11").split("\n\n").map { it.split("\n") }
println(Day11Solver(data).solvePart1(false))
println(Day11Solver(data).solvePart2(false))
} | 0 | Kotlin | 0 | 0 | d7cd903485f41fe8c7023c015e4e606af9e10315 | 5,002 | advent_code_2022 | Apache License 2.0 |
src/Day02.kt | anoniim | 572,264,555 | false | {"Kotlin": 8381} | fun main() {
Day2().run(
15,
12
)
}
private class Day2 : Day(2) {
override fun part1(input: List<String>): Int {
// What would your total score be if everything goes exactly according to your strategy guide?
return input.sumOf { GameRound(it).getScore() }
}
override fun part2(input: List<String>): Int {
// Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide?
return input.sumOf { GameRound(it).getScorePart2() }
}
}
private class GameRound(val input: String) {
fun getScore(): Int {
val shapes = input.split(" ").map { Shape.from(it).score }
return shapes[1] + resultScore(shapes)
}
private fun resultScore(shapes: List<Int>): Int {
if (shapes[0] == shapes[1]) {
return 3 // draw
}
val result = shapes[0] - shapes[1]
return if (result == -1 || result == 2) {
6 // win
} else {
0 // loss
}
}
fun getScorePart2(): Int {
val inputList = input.split(" ")
val theirShape = Shape.from(inputList[0])
return resultScorePart2(theirShape.score, inputList[1])
}
private fun resultScorePart2(theirShapeScore: Int, end: String): Int {
return when (end) {
"X" -> loseShape(theirShapeScore)
"Y" -> theirShapeScore + 3
"Z" -> winShape(theirShapeScore) + 6
else -> throw Exception("invalid input")
}
}
private fun loseShape(theirShapeScore: Int): Int {
val myShape = theirShapeScore - 1
return if (myShape == 0) 3 else myShape
}
private fun winShape(theirShapeScore: Int): Int {
val myShape = theirShapeScore + 1
return if (myShape == 4) 1 else myShape
}
}
enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
fun from(string: String): Shape {
return when (string) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw Exception("invalid input")
}
}
}
} | 0 | Kotlin | 0 | 0 | 15284441cf14948a5ebdf98179481b34b33e5817 | 2,261 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day19.kt | simonbirt | 574,137,905 | false | {"Kotlin": 45762} | fun main() {
Day19.printSolutionIfTest(33, 56*62)
}
object Day19 : Day<Int, Int>(19) {
override fun part1(lines: List<String>) = solve(lines, 24)
override fun part2Test(lines: List<String>) = solve2(lines, 32)
override fun part2(lines: List<String>) = solve2(lines.take(3), 32)
data class Blueprint(
val oreRobotCost: Int,
val clayRobotCost: Int,
val obsidianRobotOreCost: Int,
val obsidianRobotClayCost: Int,
val geodeRobotOreCost: Int,
val geodeRobotObsidianCost: Int
)
fun parseBlueprint(line: String) =
line.split(" ").mapNotNull { it.toIntOrNull() }.let { Blueprint(it[0], it[1], it[2], it[3], it[4], it[5]) }
fun solve(lines: List<String>, minutes: Int):Int {
return lines.map { parseBlueprint(it) }.map{ solveForBlueprint(minutes, it) }
.mapIndexed{ index, value -> (index+1)*value}.reduce(Int::plus)
}
fun solve2(lines: List<String>, minutes: Int):Int {
return lines.map { parseBlueprint(it) }.map{ solveForBlueprint(minutes, it) }
.reduce(Int::times)
}
fun solveForBlueprint(minutes: Int, blueprint: Blueprint):Int {
var states = listOf(State(0,0,0,0,1,0,0,0))
repeat(minutes) {states = tick(states, blueprint)}
//println(states.joinToString("\n"))
val result = states.maxOf { it.geode }
println(result)
return result
}
fun tick(start: List<State>, blueprint: Blueprint) = start.flatMap { state ->
//state.next().let {
listOfNotNull(
state.next(),
state.buyOreRobot(blueprint.oreRobotCost),
state.buyClayRobot(blueprint.clayRobotCost),
state.buyObsidianRobot(blueprint.obsidianRobotOreCost, blueprint.obsidianRobotClayCost),
state.buyGeodeRobot(blueprint.geodeRobotOreCost, blueprint.geodeRobotObsidianCost)
)
//}
}.distinct().sortedByDescending { s -> s.score() }.take( 1500 )
data class State(
val ore: Int,
val clay: Int,
val obsidian: Int,
val geode: Int,
val oreRobot: Int,
val clayRobot: Int,
val obsidianRobot: Int,
val geodeRobot: Int
) {
fun next() = copy(
ore = ore + oreRobot,
clay = clay + clayRobot,
obsidian = obsidian + obsidianRobot,
geode = geode + geodeRobot
)
fun buyOreRobot(oreCost: Int) =
(ore - oreCost).takeIf { it >= 0 }?.let { copy(ore = it).next().copy(oreRobot = oreRobot + 1) }
fun buyClayRobot(oreCost: Int) =
(ore - oreCost).takeIf { it >= 0 }?.let {
copy(ore = it).next().copy(clayRobot = clayRobot + 1)
}
fun buyObsidianRobot(oreCost: Int, clayCost: Int) =
(ore - oreCost).takeIf { it >= 0 }?.let{ newOre ->
(clay - clayCost).takeIf { it >= 0 }?.let{newClay ->
copy(ore = newOre, clay = newClay).next().copy(obsidianRobot = obsidianRobot + 1)
}
}
fun buyGeodeRobot(oreCost: Int, obsidianCost: Int) =
(ore - oreCost).takeIf { it >= 0 }?.let{ newOre ->
(obsidian - obsidianCost).takeIf { it >= 0 }?.let{newObsidian ->
copy(ore = newOre, obsidian = newObsidian).next().copy(geodeRobot = geodeRobot + 1)
}
}
fun score() = (ore + oreRobot) + 10*(clay + clayRobot) + 1000*(obsidian + obsidianRobot) + 100000 * (geode + geodeRobot)
}
}
| 0 | Kotlin | 0 | 0 | 962eccac0ab5fc11c86396fc5427e9a30c7cd5fd | 3,597 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day11.kt | goblindegook | 319,372,062 | false | null | package com.goblindegook.adventofcode2020
import com.goblindegook.adventofcode2020.input.load
fun main() {
val seats = load("/day11-input.txt")
println(countSeated(seats))
println(countSeatedRedux(seats))
}
fun countSeated(seats: String): Int = countSeated(seats.toRoom(), emptyMap(), 4, ::neighbours)
fun countSeatedRedux(seats: String): Int = countSeated(seats.toRoom(), emptyMap(), 5, ::lineOfSight)
private const val NEW_LINE = '\n'
private const val TAKEN = '#'
private const val AVAILABLE = 'L'
private const val FLOOR = '.'
private tailrec fun countSeated(room: Room, previous: Room, limit: Int, count: (Room, Position) -> Int): Int =
if (room == previous) room.values.count { it == TAKEN }
else countSeated(
room.mapValues { (position, state) ->
when {
state == AVAILABLE && count(room, position) == 0 -> TAKEN
state == TAKEN && count(room, position) >= limit -> AVAILABLE
else -> state
}
},
room,
limit,
count
)
private fun neighbours(seats: Room, pos: Position): Int =
Position.around.map { pos + it }.count { seats[it] == TAKEN }
private fun lineOfSight(room: Room, position: Position): Int =
lineOfSight(room, 0, Position.around.map { position to it })
private tailrec fun lineOfSight(room: Room, found: Int, queue: List<Pair<Position, Position>>): Int =
if (queue.isEmpty()) found
else {
val head = queue.first()
val step = head.second
val seat = head.first + step
lineOfSight(
room = room,
found = found + if (room[seat] == TAKEN) 1 else 0,
queue = (queue + (seat to step).takeIf { room[seat] == FLOOR }).drop(1).filterNotNull()
)
}
private data class Position(val x: Int, val y: Int) {
infix operator fun plus(other: Position) = Position(x + other.x, y + other.y)
companion object {
val around = listOf(
Position(-1, -1), Position(-1, 0), Position(-1, +1),
Position(0, -1), Position(0, +1),
Position(+1, -1), Position(+1, 0), Position(+1, +1),
)
}
}
private typealias Room = Map<Position, Char>
private fun String.toRoom(): Room =
foldIndexed(emptyMap()) { index, acc, char -> acc + (positionOf(index) to char) }
private fun String.positionOf(index: Int) = (indexOf(NEW_LINE) + 1).let { Position(index % it, index / it) } | 0 | Kotlin | 0 | 0 | 85a2ff73899dbb0e563029754e336cbac33cb69b | 2,450 | adventofcode2020 | MIT License |
2021/src/day03/day3.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day03
import java.io.File
import kotlin.collections.mutableMapOf
fun main() {
// testDay3Sample()
readInput("day3.txt")
}
fun testDay3Sample() {
val input =
listOf(
"00100",
"11110",
"10110",
"10111",
"10101",
"01111",
"00111",
"11100",
"10000",
"11001",
"00010",
"01010"
)
printStats(input)
}
fun readInput(arg: String) {
printStats(File("src/day03", arg).readLines())
}
fun printStats(input: List<String>) {
var (gamma, epsilon) = calulatePowerConsumption(input)
val powerConsumption = gamma * epsilon
val o2rating = getO2rating(input)
val co2rating = getCO2rating(input)
val lifeSupport = o2rating * co2rating
println("power $powerConsumption o2 $o2rating co2 $co2rating lifeSupport $lifeSupport")
}
fun calulatePowerConsumption(input: List<String>): Pair<Int, Int> {
// Map of index to number of "1"s in the input.
var onesFrequencyMap: MutableMap<Int, Int> = mutableMapOf()
var maxSize: Int = 0
input.forEach {
maxSize = Math.max(it.length, maxSize)
it.forEachIndexed { index, value ->
if ("1".single().equals(value)) {
onesFrequencyMap[index] = onesFrequencyMap.getOrDefault(index, 0) + 1
}
}
}
// Now loop through the entries in the map to calculate gamma and epsilon
var gammaString: String = ""
var epsilonString: String = ""
val commonSize = (input.size / 2)
for (index in 0..maxSize - 1) {
if (onesFrequencyMap.getOrDefault(index, 0) >= commonSize) {
gammaString += "1"
epsilonString += "0"
} else {
gammaString += "0"
epsilonString += "1"
}
}
println("gamma $gammaString epsilon $epsilonString")
return Pair(gammaString.toInt(2), epsilonString.toInt(2))
}
fun getO2rating(input: List<String>): Int {
return getFilteredListNumber(input, true)
}
fun getCO2rating(input: List<String>): Int {
return getFilteredListNumber(input, false)
}
fun getFilteredListNumber(input: List<String>, takeGreater: Boolean = false): Int {
var index: Int = 0
var currentList: List<String> = input
while (currentList.size > 1) {
val pairs = splitList(index, currentList)
currentList =
if (takeGreater.xor((pairs.first.size < pairs.second.size))) pairs.first
else pairs.second
index++
}
// at this point current list is 1
return currentList.single().toInt(2)
}
// Splits a list into a onesList and a zeroesList
fun splitList(index: Int, input: List<String>): Pair<List<String>, List<String>> {
var onesList: MutableList<String> = mutableListOf()
var zeroesList: MutableList<String> = mutableListOf()
input.forEach {
if ("1".single().equals(it.get(index))) {
onesList.add(it)
} else {
zeroesList.add(it)
}
}
return Pair(onesList, zeroesList)
}
| 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 3,208 | adventofcode | Apache License 2.0 |
src/Day09.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | import kotlin.math.abs
private data class Day09Instruction(
val direction: Char,
val amount: Int
) {
companion object {
fun fromString(input: String) =
Day09Instruction(input[0], input.substring(2).toInt())
}
}
fun main() {
fun Coordinate.moveUp() = Coordinate(x, y+1)
fun Coordinate.moveDown() = Coordinate(x, y-1)
fun Coordinate.moveLeft() = Coordinate(x-1, y)
fun Coordinate.moveRight() = Coordinate(x+1, y)
fun Coordinate.isTouching(other: Coordinate): Boolean {
val deltaX = abs(other.x - x)
val deltaY = abs(other.y - y)
return (deltaY < 2 && deltaX < 2)
}
fun Coordinate.follow(other: Coordinate) =
if (isTouching(other)) {
this
} else {
let {
when {
other.x > it.x -> it.moveRight()
other.x < it.x -> it.moveLeft()
else -> it
}
}
.let {
when {
other.y > it.y -> it.moveUp()
other.y < it.y -> it.moveDown()
else -> it
}
}
}
fun part1(input: List<String>): Int {
var head = Coordinate(0, 0)
var tail = Coordinate(0, 0)
val tailPositions = mutableSetOf(tail)
input
.map { Day09Instruction.fromString(it) }
.forEach {
(1..it.amount).forEach { _ ->
head = when (it.direction) {
'R' -> head.moveRight()
'L' -> head.moveLeft()
'U' -> head.moveUp()
'D' -> head.moveDown()
else -> throw RuntimeException("Invalid direction")
}
tail = tail.follow(head)
tailPositions.add(tail)
}
}
return tailPositions.size
}
fun part2(input: List<String>): Int {
var rope = buildList {
(0..9).forEach { _ -> add(Coordinate(0,0))}
}
return input
.map { Day09Instruction.fromString(it) }
.flatMap {instruction ->
List(instruction.amount) { instruction.direction }
}
.scan(rope) { r, d ->
buildList {
val h = when (d) {
'R' -> r.first().moveRight()
'L' -> r.first().moveLeft()
'U' -> r.first().moveUp()
'D' -> r.first().moveDown()
else -> throw RuntimeException("Invalid direction")
}
add(h)
r.drop(1).scan(h) { prev, current ->
val t = current.follow(prev)
add(t)
t
}
}
}
.map { it.last() }
.toSet()
.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 3,431 | advent-of-code-2022 | Apache License 2.0 |
src/day03/Day03.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day03
import println
import readInput
fun main() {
fun bitCounts(input: List<String>) = input
.asSequence()
.map { line -> line.map { it.toString().toInt() } }
.reduce { acc, it -> acc.zip(it) { a, b -> a + b } }
fun getRatingByCounting(input: List<String>, mostCommon: Boolean): Int = bitCounts(input)
.map { if (it > input.size / 2) 1 else 0 }
.map { if (mostCommon) it else 1 - it }
.joinToString("")
.toInt(2)
fun getRatingByFiltering(input: List<String>, mostCommon: Boolean): Int {
var lines = input
var bit = 0;
var match = ""
while (lines.size > 1) {
val next = if (bitCounts(lines)[bit] >= lines.size / 2.toDouble()) 1 else 0
match += if (mostCommon) next else 1 - next
lines = lines.filter { it.startsWith(match) }
bit++
}
return lines[0].toInt(2)
}
fun part1(input: List<String>): Int {
return getRatingByCounting(input, true) * getRatingByCounting(input, false)
}
fun part2(input: List<String>): Int {
return getRatingByFiltering(input, true) * getRatingByFiltering(input, false)
}
val testInput = readInput("day03/Day03_test")
check(part1(testInput) == 198)
check(part2(testInput) == 230)
val input = readInput("day03/Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 1,428 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/_2020/Day7.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2020
import aocRun
private val REGEX_MAIN = Regex("^(\\w+\\s+\\w+) bags contain (.*).$")
private val REGEX_CONTAINED = Regex("(\\d+) (\\w+\\s+\\w+) bags?")
private const val NO_BAGS = "no other bags"
private const val SHINY_GOLD = "shiny gold"
fun main() {
aocRun(puzzleInput) { input ->
val map = mutableMapOf<String, Set<String>>()
input.split("\n").forEach { rule ->
val matcher = REGEX_MAIN.matchEntire(rule)!!
val bag = matcher.groupValues[1]
val contained = matcher.groupValues[2]
map[bag] = if (contained == NO_BAGS)
emptySet()
else
REGEX_CONTAINED.findAll(contained).map { it.groupValues[2] }.toSet()
}
return@aocRun map.keys.count { hasShinyGoldBag(map, it) }
}
aocRun(puzzleInput) { input ->
val map = mutableMapOf<String, Set<Pair<Int, String>>>()
input.split("\n").forEach { rule ->
val matcher = REGEX_MAIN.matchEntire(rule)!!
val bag = matcher.groupValues[1]
val contained = matcher.groupValues[2]
map[bag] = if (contained == NO_BAGS)
emptySet()
else
REGEX_CONTAINED.findAll(contained).map { it.groupValues[1].toInt() to it.groupValues[2] }.toSet()
}
return@aocRun countContainedBags(map, SHINY_GOLD)
}
}
private fun hasShinyGoldBag(map: Map<String, Set<String>>, key: String): Boolean {
val contained = map.getValue(key)
if (contained.isEmpty())
return false
if (contained.contains(SHINY_GOLD))
return true
return contained.any { hasShinyGoldBag(map, it) }
}
private fun countContainedBags(map: Map<String, Set<Pair<Int, String>>>, key: String): Int {
val contained = map.getValue(key)
if (contained.isEmpty())
return 0
val recursiveSum = contained.sumOf { countContainedBags(map, it.second) * it.first }
val containedSum = contained.sumBy { it.first }
return recursiveSum + containedSum
}
private val puzzleInput = """
shiny lime bags contain 3 muted magenta bags, 3 clear cyan bags.
shiny violet bags contain 1 faded brown bag, 1 dull red bag.
muted maroon bags contain 4 pale lime bags.
pale magenta bags contain 2 striped coral bags, 1 shiny orange bag, 3 vibrant white bags, 4 posh cyan bags.
vibrant crimson bags contain 4 bright white bags, 3 dark brown bags, 4 plaid crimson bags.
mirrored red bags contain 2 bright orange bags, 3 dull brown bags, 4 dotted brown bags.
muted red bags contain 2 bright green bags.
faded chartreuse bags contain 5 bright cyan bags.
wavy red bags contain 4 drab white bags, 1 plaid silver bag.
pale purple bags contain 4 muted yellow bags, 2 mirrored chartreuse bags, 5 mirrored purple bags, 2 mirrored red bags.
dull blue bags contain 4 dark brown bags, 2 faded blue bags, 4 dim aqua bags.
mirrored tomato bags contain 1 posh turquoise bag, 2 bright aqua bags.
clear lavender bags contain 3 plaid bronze bags, 4 faded plum bags, 2 muted coral bags, 1 posh chartreuse bag.
light cyan bags contain 1 plaid tan bag, 2 muted cyan bags, 3 dim cyan bags, 1 pale gray bag.
plaid lavender bags contain 4 bright cyan bags, 1 dim aqua bag, 3 muted orange bags.
dotted bronze bags contain 5 drab lime bags, 3 striped plum bags, 3 faded blue bags, 5 faded purple bags.
clear indigo bags contain 3 dotted purple bags.
vibrant cyan bags contain 4 dim tomato bags, 1 dull green bag, 5 light silver bags, 2 striped gold bags.
pale yellow bags contain no other bags.
drab gray bags contain 4 shiny maroon bags.
clear turquoise bags contain 3 dotted blue bags, 3 faded cyan bags.
plaid bronze bags contain 3 light tomato bags, 2 faded chartreuse bags.
mirrored turquoise bags contain 2 plaid purple bags, 5 mirrored tomato bags, 2 drab tan bags.
wavy turquoise bags contain 2 plaid salmon bags.
shiny yellow bags contain 2 striped aqua bags, 5 drab gray bags, 4 pale aqua bags, 5 dim purple bags.
clear magenta bags contain 1 striped brown bag, 1 dull black bag, 5 light lime bags.
plaid indigo bags contain 5 wavy purple bags, 2 pale blue bags.
plaid brown bags contain 4 striped salmon bags.
dull gold bags contain 2 mirrored green bags, 1 shiny coral bag, 4 shiny red bags.
dark white bags contain 3 muted black bags, 1 vibrant yellow bag, 4 dotted chartreuse bags, 3 mirrored white bags.
drab blue bags contain 3 wavy tomato bags.
dull teal bags contain 5 drab fuchsia bags, 4 dim black bags.
drab aqua bags contain 3 dark red bags.
faded gold bags contain 1 pale bronze bag, 4 dim gold bags, 1 vibrant aqua bag, 2 bright aqua bags.
drab black bags contain 3 light cyan bags.
dim purple bags contain 5 mirrored bronze bags, 3 shiny bronze bags, 3 shiny turquoise bags, 4 clear maroon bags.
dim lime bags contain 4 vibrant yellow bags.
dotted white bags contain 5 faded lime bags.
muted lavender bags contain 3 dotted bronze bags, 2 faded chartreuse bags, 5 drab gold bags, 5 dark white bags.
drab white bags contain 1 clear lavender bag, 3 posh maroon bags.
bright tan bags contain 5 mirrored gray bags, 4 posh plum bags, 4 dull brown bags.
pale beige bags contain 4 muted indigo bags.
bright turquoise bags contain 5 wavy violet bags, 4 wavy indigo bags, 2 faded beige bags, 2 dim yellow bags.
muted violet bags contain 4 drab lime bags.
posh chartreuse bags contain 5 wavy silver bags, 4 light aqua bags.
faded green bags contain 5 muted magenta bags, 4 dark fuchsia bags.
dull orange bags contain 2 mirrored tomato bags, 4 wavy orange bags.
posh red bags contain 5 dim chartreuse bags, 1 shiny aqua bag, 1 wavy black bag.
clear crimson bags contain 5 dotted tan bags, 2 wavy crimson bags, 4 dim orange bags, 5 drab turquoise bags.
striped lavender bags contain 5 plaid teal bags, 4 dull crimson bags, 4 posh lavender bags.
faded lavender bags contain 2 vibrant coral bags.
posh lavender bags contain 2 drab silver bags, 1 drab cyan bag.
plaid olive bags contain 5 vibrant yellow bags, 1 striped bronze bag.
light indigo bags contain 3 shiny cyan bags, 3 vibrant yellow bags.
light orange bags contain 2 dark indigo bags.
dim teal bags contain 3 bright lavender bags, 4 wavy tomato bags, 2 shiny gray bags, 5 bright blue bags.
dull tomato bags contain 5 drab lime bags, 3 dark olive bags, 4 drab turquoise bags.
muted indigo bags contain 5 posh chartreuse bags, 1 mirrored green bag, 3 dark brown bags, 1 dark orange bag.
wavy fuchsia bags contain 3 mirrored magenta bags, 5 drab fuchsia bags, 5 dull green bags.
dim violet bags contain 2 posh crimson bags.
faded lime bags contain no other bags.
wavy salmon bags contain 5 posh red bags.
drab cyan bags contain 3 dull indigo bags, 1 vibrant indigo bag.
striped purple bags contain 1 faded blue bag, 3 faded fuchsia bags, 3 pale maroon bags.
dim aqua bags contain no other bags.
pale olive bags contain 1 muted indigo bag.
striped tan bags contain 4 light coral bags, 4 dull violet bags, 3 dim purple bags, 5 dull yellow bags.
dull black bags contain 1 dotted beige bag.
bright lime bags contain 2 light yellow bags.
faded red bags contain 2 drab teal bags, 2 pale coral bags, 5 dotted black bags.
vibrant green bags contain 4 drab bronze bags.
posh gold bags contain 2 pale cyan bags, 3 clear lavender bags, 2 plaid bronze bags.
muted magenta bags contain 5 shiny blue bags, 1 faded olive bag, 4 drab brown bags, 3 dull violet bags.
muted lime bags contain 5 light blue bags, 1 vibrant lavender bag.
muted tan bags contain 3 vibrant coral bags, 5 muted coral bags, 3 light bronze bags.
drab teal bags contain 3 dotted fuchsia bags, 4 drab aqua bags, 3 dim aqua bags.
muted purple bags contain 1 drab tan bag.
dim brown bags contain 4 dotted tan bags.
drab lime bags contain 1 mirrored green bag, 5 clear lime bags, 3 posh yellow bags, 5 pale yellow bags.
wavy aqua bags contain 1 faded silver bag.
striped magenta bags contain 2 mirrored aqua bags, 1 dotted gold bag.
dull maroon bags contain 2 drab maroon bags, 3 shiny lavender bags.
dotted yellow bags contain 2 dark indigo bags, 3 shiny gold bags, 2 muted coral bags, 5 pale maroon bags.
shiny plum bags contain 5 vibrant coral bags, 3 dotted gray bags, 1 pale lime bag, 4 plaid green bags.
faded violet bags contain 1 dark crimson bag, 5 pale gray bags, 1 pale olive bag.
faded olive bags contain 4 wavy indigo bags.
drab green bags contain 1 vibrant yellow bag, 1 posh tomato bag, 1 dull yellow bag, 5 shiny bronze bags.
shiny black bags contain 3 clear gray bags, 4 dim tomato bags.
dull coral bags contain 1 pale cyan bag, 1 light brown bag.
mirrored coral bags contain 1 dark tomato bag, 3 vibrant coral bags, 3 posh lime bags, 3 pale fuchsia bags.
faded white bags contain 1 light silver bag, 3 striped turquoise bags, 3 dark green bags, 3 posh orange bags.
wavy orange bags contain 2 dotted indigo bags, 1 vibrant indigo bag, 4 dull teal bags, 3 striped gold bags.
plaid beige bags contain 4 pale blue bags.
plaid green bags contain 1 mirrored bronze bag, 3 mirrored purple bags, 5 shiny coral bags, 5 posh yellow bags.
mirrored tan bags contain 1 faded blue bag.
plaid violet bags contain 2 faded blue bags.
shiny coral bags contain 3 vibrant bronze bags, 5 dull salmon bags.
dim beige bags contain 3 plaid magenta bags, 2 light gold bags, 1 shiny blue bag, 5 bright teal bags.
pale coral bags contain 1 faded orange bag, 3 dark turquoise bags.
mirrored crimson bags contain 2 dull silver bags.
dim tan bags contain 3 light tomato bags, 4 dotted chartreuse bags.
striped cyan bags contain 1 faded violet bag, 3 dotted lavender bags, 4 light lavender bags, 1 drab fuchsia bag.
dull turquoise bags contain 3 bright teal bags, 1 faded blue bag, 5 bright magenta bags.
bright magenta bags contain 2 wavy indigo bags.
wavy magenta bags contain 2 dim cyan bags, 2 dim violet bags, 4 dark salmon bags, 2 vibrant bronze bags.
wavy lavender bags contain 4 pale cyan bags, 4 vibrant yellow bags, 1 vibrant white bag.
pale green bags contain 3 dark indigo bags, 3 shiny gray bags.
dark aqua bags contain 3 faded turquoise bags, 3 vibrant indigo bags, 3 dull salmon bags, 1 dotted gray bag.
dim gray bags contain 1 faded silver bag, 3 muted red bags, 2 wavy orange bags, 1 posh beige bag.
clear black bags contain 4 vibrant plum bags, 3 bright brown bags, 2 dark gray bags, 1 clear teal bag.
drab indigo bags contain 2 dim aqua bags, 5 vibrant blue bags, 5 dull salmon bags, 5 drab violet bags.
mirrored orange bags contain 5 posh olive bags, 5 dotted tan bags, 5 mirrored salmon bags, 4 posh red bags.
plaid fuchsia bags contain 4 drab green bags, 3 mirrored tomato bags, 5 light white bags, 5 muted cyan bags.
shiny teal bags contain 5 bright white bags, 5 mirrored red bags.
light maroon bags contain 1 drab cyan bag.
vibrant fuchsia bags contain 5 drab crimson bags.
faded gray bags contain 3 mirrored aqua bags.
wavy chartreuse bags contain 4 muted orange bags, 2 clear blue bags, 1 muted tan bag, 2 clear lime bags.
dark yellow bags contain 5 wavy orange bags, 4 mirrored beige bags.
wavy green bags contain 5 vibrant tan bags.
dotted magenta bags contain 2 shiny red bags.
faded crimson bags contain 4 muted gray bags, 3 dim black bags.
dull cyan bags contain 3 posh tomato bags, 3 drab indigo bags, 2 vibrant blue bags.
posh aqua bags contain 2 posh yellow bags.
muted white bags contain 1 faded tomato bag.
vibrant tomato bags contain 5 vibrant white bags.
dim black bags contain 2 drab indigo bags.
mirrored lime bags contain 4 dull brown bags.
drab plum bags contain 5 plaid green bags, 5 striped lime bags, 1 dotted teal bag.
dark olive bags contain 2 wavy plum bags.
pale lime bags contain 4 dark orange bags, 5 dim black bags, 1 dull white bag.
striped fuchsia bags contain 4 bright orange bags, 3 pale maroon bags.
plaid maroon bags contain 1 dull coral bag.
clear white bags contain 5 plaid lavender bags, 1 faded turquoise bag, 1 mirrored tomato bag, 5 faded silver bags.
dark tan bags contain 4 striped gold bags.
muted beige bags contain 3 dark gold bags.
faded cyan bags contain 5 vibrant yellow bags, 2 shiny plum bags.
drab beige bags contain 4 dotted orange bags, 2 dark black bags, 2 bright olive bags, 4 dark gold bags.
drab turquoise bags contain 2 clear blue bags, 2 muted cyan bags, 4 faded turquoise bags.
striped green bags contain 4 striped plum bags, 5 dark gold bags.
bright coral bags contain 4 posh teal bags, 3 shiny crimson bags, 5 dim magenta bags.
plaid plum bags contain 5 wavy teal bags, 3 mirrored beige bags, 3 faded silver bags.
drab red bags contain 3 light magenta bags, 1 drab salmon bag, 4 shiny tan bags.
dotted coral bags contain 1 faded black bag.
wavy coral bags contain 2 posh white bags, 1 shiny gold bag, 1 striped aqua bag.
bright aqua bags contain 1 dotted olive bag, 1 striped gold bag.
bright purple bags contain 1 vibrant purple bag, 2 clear orange bags.
vibrant lime bags contain 1 dotted turquoise bag, 5 dotted magenta bags, 5 light black bags.
pale indigo bags contain 5 vibrant chartreuse bags, 5 clear white bags, 1 light lime bag, 3 dull silver bags.
dull bronze bags contain 4 dark indigo bags, 3 plaid bronze bags, 2 pale yellow bags.
wavy plum bags contain 5 bright chartreuse bags, 5 pale maroon bags, 1 clear lime bag.
dull purple bags contain 4 muted gray bags.
drab brown bags contain 3 drab lime bags, 3 dull silver bags, 2 dark gold bags, 3 drab beige bags.
dotted crimson bags contain 1 dotted black bag.
bright violet bags contain 5 dull olive bags, 2 striped turquoise bags, 3 vibrant aqua bags, 4 clear maroon bags.
dark fuchsia bags contain 2 wavy purple bags, 4 pale tan bags, 2 vibrant coral bags, 5 dark brown bags.
wavy maroon bags contain 2 striped fuchsia bags.
light white bags contain 2 dull green bags.
dotted indigo bags contain 2 clear lavender bags, 4 shiny coral bags.
shiny turquoise bags contain 1 posh crimson bag, 1 posh salmon bag, 4 vibrant bronze bags.
dull fuchsia bags contain 1 mirrored red bag, 3 posh gray bags, 4 plaid maroon bags, 4 clear gold bags.
light magenta bags contain 3 plaid tan bags.
faded beige bags contain 5 bright indigo bags, 1 pale yellow bag, 2 vibrant yellow bags.
mirrored gold bags contain 1 mirrored blue bag, 2 posh fuchsia bags, 5 dark red bags.
light salmon bags contain 5 muted black bags, 5 dull blue bags, 2 light aqua bags, 1 pale tomato bag.
wavy gray bags contain 3 light red bags.
bright gray bags contain 4 dotted blue bags.
pale white bags contain 3 drab aqua bags, 3 wavy maroon bags, 4 shiny blue bags, 4 dotted lime bags.
dim turquoise bags contain 3 striped crimson bags, 2 faded silver bags.
clear silver bags contain 4 plaid gray bags, 1 dark black bag.
bright brown bags contain 5 faded chartreuse bags.
muted olive bags contain 1 dotted red bag, 1 posh green bag.
striped silver bags contain 3 dotted tomato bags, 1 plaid cyan bag, 4 clear white bags, 5 mirrored indigo bags.
drab yellow bags contain 5 wavy silver bags, 5 dark orange bags, 3 dark brown bags, 2 bright magenta bags.
vibrant red bags contain 5 vibrant bronze bags, 2 posh tomato bags, 3 dull lime bags, 2 striped violet bags.
dotted maroon bags contain 2 vibrant silver bags.
faded teal bags contain 4 clear lavender bags.
dim crimson bags contain 1 faded chartreuse bag.
faded orange bags contain 3 bright magenta bags, 4 mirrored brown bags.
dotted lime bags contain 4 light brown bags, 1 bright white bag, 5 dim lime bags.
posh turquoise bags contain 4 striped indigo bags, 2 dim white bags.
dark beige bags contain 1 dark olive bag.
dotted black bags contain 2 posh turquoise bags, 3 wavy indigo bags, 4 dotted violet bags.
dotted fuchsia bags contain 5 dark black bags, 1 clear lime bag.
plaid magenta bags contain 3 posh maroon bags, 4 drab green bags.
muted coral bags contain 5 light brown bags, 2 posh chartreuse bags, 1 vibrant tan bag.
striped yellow bags contain 1 light brown bag.
posh violet bags contain 3 bright magenta bags.
dark brown bags contain 2 faded blue bags, 2 dim aqua bags, 5 posh yellow bags, 5 drab violet bags.
drab fuchsia bags contain 3 shiny aqua bags, 2 plaid lavender bags, 1 muted cyan bag.
striped maroon bags contain 4 clear lime bags, 5 striped gold bags, 3 clear plum bags, 3 dull tan bags.
muted yellow bags contain 1 shiny turquoise bag.
bright silver bags contain 5 striped red bags, 4 dark aqua bags.
light beige bags contain 1 shiny gold bag, 4 dark orange bags.
light coral bags contain 3 clear beige bags, 4 shiny maroon bags.
plaid cyan bags contain 4 pale yellow bags, 1 drab beige bag, 1 bright chartreuse bag, 1 clear coral bag.
shiny tomato bags contain 3 muted indigo bags, 2 faded indigo bags.
dark maroon bags contain 1 posh white bag, 2 wavy aqua bags, 5 muted brown bags.
plaid teal bags contain 1 dull lime bag, 3 faded blue bags, 4 drab cyan bags, 3 clear cyan bags.
vibrant magenta bags contain 2 wavy tan bags.
pale tomato bags contain 2 bright silver bags, 1 dull teal bag, 5 dull lime bags, 5 muted aqua bags.
dim orange bags contain 1 vibrant white bag, 5 bright tomato bags.
plaid crimson bags contain 2 wavy brown bags, 2 striped maroon bags, 4 dark magenta bags.
posh beige bags contain 1 faded blue bag.
dotted gray bags contain 3 drab silver bags, 4 faded silver bags, 2 light coral bags.
shiny blue bags contain 1 bright magenta bag.
pale gold bags contain 1 light coral bag, 5 vibrant aqua bags, 2 wavy plum bags, 5 dim lavender bags.
striped chartreuse bags contain 3 wavy bronze bags.
vibrant lavender bags contain 3 clear bronze bags, 4 dull yellow bags.
drab tomato bags contain 1 mirrored aqua bag, 3 drab yellow bags, 2 muted white bags.
vibrant brown bags contain 3 pale white bags.
dark salmon bags contain 3 dull salmon bags, 5 drab violet bags, 4 striped indigo bags.
dotted tomato bags contain 5 muted fuchsia bags, 3 pale aqua bags, 1 dim aqua bag, 3 dull yellow bags.
wavy gold bags contain 2 light aqua bags, 3 dull white bags.
pale salmon bags contain 2 dotted lime bags, 2 shiny gold bags.
bright cyan bags contain no other bags.
clear maroon bags contain 3 mirrored white bags, 5 faded blue bags, 3 drab yellow bags, 4 light aqua bags.
dull indigo bags contain 3 vibrant indigo bags, 4 pale yellow bags.
plaid black bags contain 2 faded orange bags, 2 drab aqua bags.
striped salmon bags contain 5 drab violet bags, 3 dark brown bags, 4 dull white bags, 4 clear lime bags.
wavy bronze bags contain 4 wavy silver bags, 4 light bronze bags, 2 shiny coral bags.
dull lime bags contain 1 dull green bag, 3 dark orange bags, 4 shiny maroon bags.
drab chartreuse bags contain 2 clear lime bags, 3 dim cyan bags, 3 faded cyan bags.
dotted lavender bags contain 5 dull indigo bags.
striped aqua bags contain 4 dotted lime bags, 4 dotted brown bags.
plaid gold bags contain 2 dim lime bags, 1 dull bronze bag, 5 faded fuchsia bags, 2 drab yellow bags.
faded coral bags contain 1 vibrant green bag, 1 drab yellow bag, 4 wavy teal bags.
faded bronze bags contain 2 dim lime bags, 4 wavy magenta bags.
striped turquoise bags contain 5 mirrored magenta bags.
plaid yellow bags contain 4 mirrored maroon bags, 1 dim silver bag, 3 striped gold bags.
vibrant coral bags contain 2 mirrored white bags, 1 dull lime bag.
posh black bags contain 3 clear beige bags, 2 drab gold bags, 3 mirrored indigo bags, 1 dim black bag.
wavy beige bags contain 1 vibrant purple bag, 4 light green bags, 3 light red bags.
pale blue bags contain no other bags.
light silver bags contain 1 posh chartreuse bag, 5 vibrant tan bags.
mirrored teal bags contain 1 dark tomato bag, 1 wavy teal bag, 3 vibrant maroon bags, 5 pale red bags.
pale gray bags contain 3 mirrored bronze bags, 3 faded crimson bags, 3 dotted red bags, 2 striped yellow bags.
vibrant chartreuse bags contain 4 mirrored yellow bags.
clear gold bags contain 1 bright magenta bag, 3 dotted olive bags, 2 posh yellow bags, 2 dull blue bags.
wavy tomato bags contain 3 shiny coral bags, 4 posh chartreuse bags, 2 light aqua bags, 3 dark orange bags.
posh yellow bags contain 5 vibrant bronze bags, 5 faded lime bags, 4 posh chartreuse bags, 2 bright cyan bags.
dark lime bags contain 3 drab tomato bags.
pale crimson bags contain 2 pale maroon bags, 5 clear lime bags.
mirrored beige bags contain 5 clear maroon bags, 2 wavy maroon bags, 2 drab indigo bags.
light lime bags contain 1 light bronze bag.
vibrant silver bags contain 4 pale tan bags.
dull plum bags contain 3 vibrant yellow bags, 1 striped plum bag, 2 dim aqua bags.
mirrored chartreuse bags contain 3 wavy black bags.
plaid white bags contain 5 dark aqua bags, 1 muted orange bag.
bright fuchsia bags contain 5 vibrant tan bags.
drab gold bags contain 1 faded blue bag.
bright tomato bags contain 1 dim white bag, 1 drab yellow bag.
dotted chartreuse bags contain 4 dim aqua bags.
faded fuchsia bags contain 2 light tomato bags, 1 posh yellow bag, 4 faded chartreuse bags, 1 pale blue bag.
pale silver bags contain 1 drab orange bag, 5 clear salmon bags, 2 plaid violet bags.
mirrored purple bags contain 4 clear lime bags.
mirrored green bags contain 4 dim aqua bags.
vibrant violet bags contain 3 dark orange bags.
plaid blue bags contain 4 striped crimson bags, 2 vibrant lavender bags, 4 faded plum bags, 5 dull salmon bags.
muted orange bags contain 1 bright indigo bag, 4 posh yellow bags, 4 bright cyan bags.
vibrant blue bags contain no other bags.
light gray bags contain 2 striped green bags, 3 clear blue bags, 3 shiny coral bags.
dark plum bags contain 2 faded crimson bags, 2 dark salmon bags, 2 shiny gray bags.
drab violet bags contain no other bags.
dim chartreuse bags contain 3 dotted brown bags, 5 faded plum bags, 4 wavy tomato bags.
wavy cyan bags contain 5 faded aqua bags, 1 striped blue bag, 5 posh olive bags.
clear teal bags contain 1 mirrored olive bag, 5 dim tomato bags.
light violet bags contain 2 posh gray bags, 5 dotted cyan bags.
dark tomato bags contain 5 plaid white bags, 1 wavy indigo bag.
wavy purple bags contain 3 drab green bags.
pale black bags contain 3 drab indigo bags.
drab orange bags contain 5 striped turquoise bags.
mirrored white bags contain 4 dim aqua bags.
light purple bags contain 2 wavy green bags, 5 bright brown bags, 5 muted crimson bags, 3 dotted purple bags.
shiny orange bags contain 2 muted indigo bags.
bright green bags contain 3 mirrored tomato bags, 3 dim bronze bags.
light black bags contain 4 dotted yellow bags, 3 dark turquoise bags, 3 vibrant blue bags, 4 clear maroon bags.
shiny fuchsia bags contain 1 clear cyan bag, 1 striped silver bag, 2 bright black bags.
striped bronze bags contain 1 dotted lime bag, 4 dark chartreuse bags, 3 shiny bronze bags.
light tomato bags contain 5 dull salmon bags.
drab crimson bags contain 3 clear coral bags, 5 drab bronze bags, 3 clear black bags, 2 pale maroon bags.
vibrant aqua bags contain 2 dark black bags, 2 mirrored green bags.
clear bronze bags contain 2 mirrored aqua bags, 4 dark green bags, 5 dotted red bags.
bright chartreuse bags contain 1 dim lime bag.
mirrored fuchsia bags contain 1 faded chartreuse bag, 3 pale olive bags, 4 pale cyan bags, 2 muted beige bags.
dim plum bags contain 5 dotted bronze bags, 2 drab yellow bags, 5 shiny blue bags, 5 dotted cyan bags.
dark indigo bags contain 4 dark brown bags, 2 dull cyan bags, 4 faded chartreuse bags.
pale fuchsia bags contain 1 dim purple bag, 5 dark gray bags, 2 dim brown bags, 3 wavy tomato bags.
dull green bags contain 2 dark brown bags, 4 drab indigo bags, 1 mirrored green bag, 2 drab lime bags.
dotted aqua bags contain 2 plaid lavender bags.
striped white bags contain 2 drab cyan bags.
dim maroon bags contain 5 dull indigo bags, 3 pale aqua bags.
shiny olive bags contain 2 wavy aqua bags, 4 mirrored crimson bags.
dotted blue bags contain 4 bright brown bags, 5 dotted black bags, 2 faded teal bags, 3 pale yellow bags.
plaid salmon bags contain 5 dull purple bags, 4 faded lime bags, 2 striped aqua bags.
dotted gold bags contain 4 bright black bags.
dark black bags contain 2 dull blue bags.
posh cyan bags contain 5 shiny yellow bags.
posh green bags contain 4 plaid beige bags.
dim fuchsia bags contain 1 dull salmon bag, 1 dull olive bag, 5 shiny yellow bags.
wavy brown bags contain 1 clear plum bag.
plaid red bags contain 1 dim indigo bag, 4 muted blue bags.
light chartreuse bags contain 1 dotted yellow bag, 4 clear gold bags, 1 bright magenta bag, 5 dark tan bags.
vibrant white bags contain 1 muted gray bag.
light red bags contain 1 dark bronze bag, 3 shiny lavender bags.
light bronze bags contain 1 wavy silver bag, 3 plaid lavender bags, 4 drab violet bags, 5 mirrored green bags.
dark magenta bags contain 5 pale aqua bags.
striped gray bags contain 1 posh cyan bag.
dark cyan bags contain 2 drab fuchsia bags, 1 clear cyan bag, 2 plaid gold bags.
plaid silver bags contain 3 bright beige bags.
shiny gray bags contain 2 dull blue bags, 2 faded chartreuse bags.
shiny cyan bags contain 1 striped salmon bag, 4 vibrant tan bags.
plaid gray bags contain 5 wavy aqua bags, 5 vibrant yellow bags, 1 mirrored indigo bag, 1 faded silver bag.
drab salmon bags contain 2 muted aqua bags.
posh gray bags contain 3 posh tan bags, 4 wavy indigo bags, 5 dark gray bags.
shiny brown bags contain 3 muted gray bags, 2 muted tomato bags.
drab maroon bags contain 1 bright chartreuse bag, 2 dark aqua bags, 3 dim black bags, 5 wavy silver bags.
light yellow bags contain 5 striped purple bags, 1 faded fuchsia bag, 2 plaid gold bags, 2 dotted olive bags.
clear salmon bags contain 3 faded chartreuse bags, 5 posh salmon bags, 5 mirrored red bags.
bright orange bags contain 2 posh tomato bags.
clear purple bags contain 3 dim olive bags, 2 mirrored violet bags, 1 muted tomato bag.
dull brown bags contain 2 faded lime bags, 5 drab violet bags, 1 mirrored green bag.
vibrant salmon bags contain 5 muted green bags, 4 faded bronze bags, 1 vibrant indigo bag.
dull silver bags contain 2 light green bags.
vibrant beige bags contain 2 dull cyan bags.
muted salmon bags contain 3 bright aqua bags, 2 pale maroon bags, 1 light aqua bag.
clear tomato bags contain 5 clear lavender bags, 4 dull tan bags, 2 dotted turquoise bags.
striped brown bags contain 3 drab lavender bags, 5 clear lavender bags.
dotted turquoise bags contain 1 light tan bag, 2 dull tomato bags.
posh orange bags contain 1 mirrored cyan bag, 3 shiny cyan bags, 5 bright beige bags, 4 striped lime bags.
dull olive bags contain 5 light silver bags, 3 wavy olive bags, 3 bright magenta bags, 4 mirrored bronze bags.
posh maroon bags contain 2 striped violet bags, 3 plaid lavender bags, 2 clear beige bags.
pale chartreuse bags contain 1 faded lime bag, 2 light aqua bags, 1 muted coral bag.
dim magenta bags contain 1 faded chartreuse bag.
striped tomato bags contain 5 plaid lavender bags, 1 posh beige bag, 1 clear lavender bag, 4 muted indigo bags.
shiny aqua bags contain 1 wavy gold bag, 1 plaid gold bag.
posh magenta bags contain 3 shiny beige bags, 3 clear gold bags.
muted black bags contain 5 dull yellow bags, 4 faded beige bags.
plaid tomato bags contain 3 dotted crimson bags, 3 shiny tan bags.
dim red bags contain 4 light beige bags, 5 shiny gold bags, 5 posh blue bags, 4 dotted indigo bags.
drab lavender bags contain 4 striped indigo bags, 3 vibrant tan bags, 3 plaid aqua bags, 3 plaid bronze bags.
vibrant orange bags contain 3 dotted lavender bags, 1 posh purple bag, 5 dull cyan bags.
light lavender bags contain 4 drab cyan bags, 5 posh maroon bags, 3 dotted red bags.
dark red bags contain 4 faded plum bags.
plaid chartreuse bags contain 1 posh blue bag.
clear tan bags contain 2 dull purple bags, 2 plaid purple bags.
muted bronze bags contain 2 plaid salmon bags, 2 muted crimson bags, 4 dotted olive bags.
pale lavender bags contain 1 vibrant plum bag, 5 vibrant yellow bags.
posh crimson bags contain 2 light brown bags.
dark blue bags contain 5 mirrored tomato bags, 1 drab coral bag, 3 wavy purple bags.
dim silver bags contain 5 drab yellow bags, 5 posh purple bags, 3 light tomato bags, 3 wavy blue bags.
faded maroon bags contain 3 dark salmon bags, 3 faded aqua bags, 1 clear olive bag, 2 clear brown bags.
dark bronze bags contain 3 dim white bags, 3 bright cyan bags, 4 clear olive bags, 2 faded crimson bags.
pale orange bags contain 1 light yellow bag, 5 bright olive bags, 2 pale olive bags.
bright maroon bags contain 3 bright white bags, 1 dotted orange bag.
dull yellow bags contain 5 light bronze bags, 4 faded beige bags, 2 dark orange bags, 2 dull cyan bags.
wavy violet bags contain 2 dim aqua bags, 5 posh chartreuse bags.
dull beige bags contain 1 shiny bronze bag, 1 striped crimson bag, 5 plaid indigo bags.
clear yellow bags contain 3 dim brown bags, 4 dotted lavender bags.
clear red bags contain 3 shiny indigo bags, 1 vibrant plum bag, 1 dim fuchsia bag, 5 striped teal bags.
dotted silver bags contain 5 wavy bronze bags, 4 vibrant cyan bags, 2 dull blue bags, 2 posh yellow bags.
shiny maroon bags contain 3 muted indigo bags, 5 light white bags, 3 posh yellow bags, 4 posh tomato bags.
dark lavender bags contain 1 vibrant tan bag, 5 plaid lime bags.
vibrant plum bags contain 1 faded teal bag, 5 shiny plum bags, 3 bright fuchsia bags, 1 shiny coral bag.
bright beige bags contain 2 mirrored green bags.
clear beige bags contain 1 posh chartreuse bag, 4 drab cyan bags, 3 light beige bags.
mirrored yellow bags contain 3 faded beige bags, 2 shiny cyan bags, 2 wavy silver bags, 2 dull yellow bags.
shiny lavender bags contain 4 clear cyan bags.
muted cyan bags contain 5 posh tomato bags, 2 drab gray bags, 1 dull indigo bag, 3 pale blue bags.
light teal bags contain 3 dull yellow bags, 2 striped fuchsia bags.
vibrant black bags contain 3 bright white bags.
light turquoise bags contain 4 muted indigo bags, 3 mirrored silver bags, 5 dark tomato bags.
light gold bags contain 5 mirrored magenta bags.
dull lavender bags contain 2 wavy chartreuse bags, 3 dull crimson bags, 3 pale tomato bags.
light olive bags contain 4 dark orange bags, 4 clear olive bags.
pale red bags contain 3 plaid lavender bags, 4 plaid beige bags, 1 plaid coral bag, 1 shiny chartreuse bag.
wavy lime bags contain 2 muted coral bags, 2 clear teal bags, 3 dull maroon bags, 4 dim lime bags.
pale bronze bags contain 4 vibrant cyan bags.
wavy tan bags contain 3 drab lavender bags, 2 dotted aqua bags, 2 bright white bags.
faded aqua bags contain 4 wavy black bags.
mirrored maroon bags contain 2 bright white bags, 4 dotted maroon bags, 5 light coral bags, 5 striped turquoise bags.
striped teal bags contain 4 bright chartreuse bags, 3 striped indigo bags, 5 dark lavender bags, 4 posh white bags.
striped coral bags contain 2 striped lime bags, 2 wavy purple bags, 1 striped plum bag.
mirrored brown bags contain 1 faded lime bag, 5 drab indigo bags, 4 bright white bags.
faded tomato bags contain 1 dim indigo bag, 5 shiny plum bags, 1 drab yellow bag, 4 drab indigo bags.
shiny tan bags contain 3 dark turquoise bags, 3 muted aqua bags.
posh tomato bags contain no other bags.
clear chartreuse bags contain 4 shiny indigo bags, 2 dim cyan bags.
bright olive bags contain 2 faded blue bags.
dull tan bags contain 4 striped red bags.
muted aqua bags contain 3 dark black bags, 4 faded crimson bags, 2 plaid white bags, 3 bright black bags.
shiny red bags contain 1 dull blue bag, 2 bright white bags.
bright white bags contain 2 faded blue bags.
dotted salmon bags contain 1 dotted indigo bag.
faded turquoise bags contain 5 dark orange bags.
posh plum bags contain 5 faded white bags.
wavy olive bags contain 5 light aqua bags, 1 pale lavender bag, 5 pale green bags.
light crimson bags contain 1 muted indigo bag, 2 plaid beige bags.
mirrored gray bags contain 1 posh lavender bag, 5 wavy indigo bags, 4 dotted crimson bags.
striped crimson bags contain 2 striped salmon bags, 5 mirrored magenta bags, 4 drab fuchsia bags.
posh olive bags contain 4 posh fuchsia bags, 1 drab brown bag, 4 dotted red bags.
clear brown bags contain 1 striped plum bag.
dark coral bags contain 1 shiny gold bag, 2 faded turquoise bags.
mirrored violet bags contain 1 dotted gold bag, 3 striped salmon bags, 3 faded crimson bags.
mirrored black bags contain 5 dull cyan bags, 3 wavy silver bags, 1 posh fuchsia bag.
bright blue bags contain 3 shiny coral bags.
light blue bags contain 1 striped indigo bag, 4 dark aqua bags, 3 mirrored tomato bags, 2 vibrant blue bags.
dark gray bags contain 2 posh chartreuse bags, 2 mirrored tan bags.
wavy silver bags contain no other bags.
dark crimson bags contain 5 mirrored blue bags, 4 drab green bags, 5 plaid purple bags, 4 clear beige bags.
wavy indigo bags contain 4 faded lime bags, 4 mirrored green bags, 2 posh tomato bags.
shiny purple bags contain 1 pale gold bag, 1 dull tomato bag.
dotted olive bags contain 1 drab cyan bag, 4 shiny coral bags.
faded plum bags contain 5 dotted cyan bags.
striped orange bags contain 2 dotted purple bags, 2 dotted indigo bags.
dim tomato bags contain 5 mirrored green bags.
shiny gold bags contain 1 dull white bag, 4 dark orange bags.
posh coral bags contain 2 pale olive bags, 5 clear gold bags, 5 posh turquoise bags, 5 wavy olive bags.
muted crimson bags contain 3 dim black bags, 1 vibrant bronze bag, 3 light black bags.
mirrored magenta bags contain 5 wavy silver bags, 5 shiny red bags, 5 pale black bags.
dull white bags contain 5 bright indigo bags, 3 posh tomato bags, 2 clear lime bags, 5 drab lime bags.
pale tan bags contain 5 wavy purple bags, 5 muted orange bags, 5 dark red bags.
muted tomato bags contain 1 dim maroon bag, 2 dull yellow bags, 3 vibrant bronze bags, 5 dull blue bags.
pale cyan bags contain 2 wavy violet bags, 1 clear maroon bag, 2 bright orange bags.
posh white bags contain 4 dim aqua bags, 5 posh chartreuse bags, 4 drab gold bags.
wavy crimson bags contain 2 posh maroon bags, 5 clear cyan bags, 1 shiny maroon bag, 2 plaid bronze bags.
drab purple bags contain 1 shiny gold bag, 5 dotted bronze bags, 4 drab gray bags.
dark green bags contain 3 bright chartreuse bags, 3 pale green bags, 5 dotted crimson bags, 2 clear plum bags.
dim cyan bags contain 2 shiny gold bags, 3 light silver bags, 2 vibrant blue bags.
pale maroon bags contain 5 mirrored brown bags, 3 vibrant indigo bags.
vibrant turquoise bags contain 3 muted cyan bags, 3 dull white bags.
dim olive bags contain 5 drab salmon bags.
bright salmon bags contain 3 striped turquoise bags, 2 dark salmon bags.
faded black bags contain 2 striped plum bags, 3 muted indigo bags.
clear aqua bags contain 2 vibrant bronze bags, 1 vibrant indigo bag, 4 mirrored tomato bags.
muted turquoise bags contain 3 muted cyan bags, 2 light brown bags, 4 light violet bags, 1 posh salmon bag.
shiny green bags contain 2 posh tomato bags.
mirrored indigo bags contain 3 clear lavender bags, 3 muted magenta bags, 3 posh yellow bags.
dim white bags contain 1 clear gold bag.
dark teal bags contain 4 light teal bags, 3 mirrored aqua bags, 5 faded teal bags.
wavy yellow bags contain 2 dull chartreuse bags, 5 dull yellow bags, 3 vibrant gold bags.
light fuchsia bags contain 5 plaid white bags, 2 mirrored magenta bags, 5 striped turquoise bags, 5 light bronze bags.
dotted plum bags contain 1 muted orange bag.
dark purple bags contain 3 dark brown bags.
vibrant yellow bags contain 4 posh chartreuse bags, 1 vibrant bronze bag.
bright gold bags contain 4 dotted tomato bags.
faded brown bags contain 1 clear cyan bag, 4 faded purple bags.
dotted orange bags contain 5 vibrant tan bags.
light green bags contain 3 muted orange bags, 4 muted gray bags, 3 faded silver bags, 3 shiny blue bags.
dark silver bags contain 5 dark tan bags, 4 light silver bags.
vibrant teal bags contain 3 shiny bronze bags, 5 mirrored green bags, 3 plaid aqua bags, 1 bright olive bag.
mirrored plum bags contain 1 dark crimson bag, 2 striped gray bags, 3 posh white bags.
striped red bags contain 1 dotted black bag, 1 mirrored magenta bag, 3 shiny blue bags.
shiny beige bags contain 5 striped salmon bags, 2 bright cyan bags, 4 striped crimson bags.
clear orange bags contain 1 faded chartreuse bag.
striped beige bags contain 2 plaid green bags, 1 bright turquoise bag, 1 drab chartreuse bag.
muted fuchsia bags contain 4 dotted violet bags, 1 vibrant silver bag, 1 shiny cyan bag, 1 vibrant yellow bag.
dim lavender bags contain 4 muted cyan bags, 1 striped violet bag.
dull red bags contain 5 posh bronze bags, 3 clear turquoise bags, 1 bright green bag, 1 vibrant white bag.
mirrored blue bags contain 5 faded olive bags, 5 light aqua bags.
bright crimson bags contain 1 posh olive bag, 5 faded white bags.
drab silver bags contain 1 muted orange bag, 3 dull green bags, 3 dim aqua bags, 2 striped fuchsia bags.
clear fuchsia bags contain 4 drab gold bags.
vibrant olive bags contain 2 light brown bags, 1 vibrant red bag.
dim salmon bags contain 3 dark red bags, 5 dark lavender bags, 2 dotted turquoise bags, 2 light magenta bags.
dull crimson bags contain 5 vibrant silver bags.
wavy blue bags contain 5 faded turquoise bags, 4 clear beige bags, 4 light green bags, 5 dark gray bags.
mirrored aqua bags contain 4 plaid bronze bags, 2 light coral bags, 4 faded orange bags, 5 posh tomato bags.
dim blue bags contain 1 bright silver bag, 4 bright cyan bags.
muted green bags contain 4 dotted tomato bags.
pale violet bags contain 3 plaid fuchsia bags, 3 light coral bags, 4 dark gold bags.
vibrant purple bags contain 3 vibrant white bags, 1 posh beige bag.
light tan bags contain 4 pale maroon bags, 4 muted fuchsia bags, 3 mirrored aqua bags.
dotted green bags contain 4 faded green bags, 2 striped black bags, 4 dull brown bags, 3 faded aqua bags.
bright bronze bags contain 2 drab bronze bags, 2 pale beige bags.
dull salmon bags contain 1 faded blue bag, 2 wavy silver bags, 3 posh chartreuse bags.
pale teal bags contain 2 dotted beige bags.
vibrant indigo bags contain 3 pale yellow bags, 4 vibrant bronze bags, 4 bright cyan bags.
shiny silver bags contain 2 faded brown bags, 2 dotted lime bags, 5 faded chartreuse bags.
bright red bags contain 1 posh turquoise bag, 4 clear aqua bags.
posh teal bags contain 2 pale beige bags.
clear lime bags contain 4 vibrant blue bags, 2 wavy silver bags, 5 pale yellow bags.
faded purple bags contain 4 faded black bags.
plaid aqua bags contain 4 bright cyan bags, 2 pale black bags, 3 dull salmon bags.
dark violet bags contain 4 muted green bags, 2 dotted bronze bags.
dull aqua bags contain 5 posh aqua bags, 2 clear plum bags, 2 dim maroon bags.
shiny chartreuse bags contain 4 dim turquoise bags, 2 posh fuchsia bags, 3 dark blue bags, 4 shiny aqua bags.
pale plum bags contain 4 drab black bags, 4 vibrant purple bags, 1 muted turquoise bag.
shiny indigo bags contain 2 wavy magenta bags.
pale brown bags contain 3 posh purple bags, 5 light aqua bags, 3 striped maroon bags.
posh tan bags contain 4 striped salmon bags, 4 dark brown bags.
plaid lime bags contain 3 drab green bags.
clear olive bags contain 4 dark black bags, 4 drab indigo bags, 3 clear lime bags.
striped olive bags contain 3 bright plum bags, 5 dotted gray bags.
plaid turquoise bags contain 4 mirrored magenta bags, 3 clear lime bags, 5 dark turquoise bags, 4 dotted olive bags.
dotted violet bags contain 4 striped fuchsia bags, 4 wavy tomato bags, 3 dim white bags, 2 clear gold bags.
muted silver bags contain 5 plaid tan bags, 2 dim olive bags, 4 dull cyan bags, 5 posh violet bags.
striped blue bags contain 1 striped chartreuse bag.
muted plum bags contain 2 posh tomato bags, 4 faded lime bags, 5 dull bronze bags, 5 wavy lime bags.
faded yellow bags contain 2 dotted tomato bags, 3 muted yellow bags, 1 dim bronze bag.
dull chartreuse bags contain 2 striped red bags.
dotted tan bags contain 4 light aqua bags.
bright indigo bags contain 2 posh tomato bags, 5 vibrant indigo bags, 2 posh chartreuse bags, 1 wavy silver bag.
bright plum bags contain 3 light green bags, 4 wavy gray bags, 3 mirrored red bags.
wavy teal bags contain 4 vibrant blue bags, 4 posh turquoise bags.
striped indigo bags contain 4 shiny gold bags, 3 dim aqua bags, 5 pale black bags.
posh brown bags contain 4 muted crimson bags.
dotted teal bags contain 4 bright beige bags, 3 posh olive bags, 2 dull coral bags.
dim yellow bags contain 2 shiny gray bags, 3 faded fuchsia bags, 3 wavy tomato bags, 2 light brown bags.
faded magenta bags contain 5 pale silver bags.
dull magenta bags contain 5 dull fuchsia bags, 1 drab green bag, 1 wavy red bag, 1 wavy fuchsia bag.
faded salmon bags contain 2 faded gray bags.
dim bronze bags contain 4 dark gold bags, 3 bright orange bags, 2 striped indigo bags.
faded tan bags contain 2 striped salmon bags, 5 muted violet bags, 4 dotted violet bags, 4 light green bags.
posh salmon bags contain 1 dull green bag, 2 bright cyan bags, 1 mirrored bronze bag.
light brown bags contain 3 posh chartreuse bags, 5 mirrored bronze bags.
posh silver bags contain 1 dim yellow bag, 1 clear tan bag.
muted brown bags contain 5 dotted maroon bags, 4 shiny yellow bags, 5 dark orange bags.
drab coral bags contain 4 faded chartreuse bags, 1 vibrant bronze bag, 5 shiny bronze bags, 3 vibrant tan bags.
vibrant maroon bags contain 2 striped yellow bags, 2 muted indigo bags, 3 muted aqua bags.
dim gold bags contain 2 bright violet bags.
plaid tan bags contain 5 muted gray bags, 5 muted coral bags, 2 wavy green bags.
dim coral bags contain 1 clear bronze bag, 2 dark gold bags, 3 drab teal bags.
vibrant gold bags contain 3 dark chartreuse bags, 1 posh purple bag, 1 striped white bag, 2 dotted chartreuse bags.
mirrored olive bags contain 4 striped fuchsia bags, 2 wavy indigo bags, 3 drab gold bags.
pale aqua bags contain 5 faded chartreuse bags, 3 faded crimson bags, 5 dotted orange bags, 3 light brown bags.
mirrored cyan bags contain 4 dull blue bags, 4 striped gold bags, 2 plaid lavender bags, 4 light silver bags.
bright yellow bags contain 4 posh yellow bags, 5 mirrored tan bags, 2 posh tomato bags, 4 light indigo bags.
clear cyan bags contain 1 dark gray bag, 4 vibrant indigo bags.
bright teal bags contain 3 mirrored tan bags.
muted blue bags contain 2 clear white bags, 4 vibrant red bags, 2 faded orange bags, 2 clear plum bags.
dark turquoise bags contain 1 drab violet bag, 5 drab gold bags, 1 mirrored green bag.
vibrant bronze bags contain 3 dim aqua bags, 3 light aqua bags, 3 wavy silver bags, 2 posh tomato bags.
posh fuchsia bags contain 3 dark brown bags, 5 striped indigo bags, 1 muted indigo bag, 4 mirrored bronze bags.
posh blue bags contain 4 clear black bags.
mirrored salmon bags contain 1 dotted gray bag, 3 clear gold bags, 5 dark indigo bags, 2 striped gold bags.
dark gold bags contain 2 vibrant blue bags, 3 muted indigo bags.
dark chartreuse bags contain 4 shiny tan bags, 1 wavy lavender bag, 3 vibrant olive bags, 3 light green bags.
drab olive bags contain 4 faded salmon bags, 4 drab white bags.
posh purple bags contain 3 wavy gold bags.
plaid coral bags contain 3 pale bronze bags, 5 mirrored green bags, 2 muted tan bags, 2 wavy silver bags.
shiny magenta bags contain 4 striped green bags, 5 mirrored brown bags.
dull gray bags contain 5 vibrant indigo bags, 3 clear fuchsia bags, 4 dotted teal bags, 4 dim bronze bags.
clear blue bags contain 4 shiny cyan bags, 1 striped fuchsia bag.
shiny white bags contain 4 faded tan bags, 2 shiny gold bags, 1 shiny bronze bag, 1 dim coral bag.
bright black bags contain 5 shiny gray bags, 3 dull bronze bags, 4 striped gold bags.
faded silver bags contain 3 clear gold bags, 4 dotted cyan bags, 1 light white bag, 4 dull green bags.
clear plum bags contain 2 drab silver bags.
dark orange bags contain 4 dim aqua bags, 4 drab violet bags.
shiny salmon bags contain 5 faded violet bags, 3 muted fuchsia bags.
plaid orange bags contain 5 light beige bags, 1 dull salmon bag.
posh bronze bags contain 4 faded blue bags, 5 bright orange bags, 3 dark gold bags.
striped plum bags contain 2 vibrant bronze bags.
vibrant gray bags contain 1 clear magenta bag.
plaid purple bags contain 1 light aqua bag, 5 vibrant tan bags, 4 pale tan bags, 4 wavy bronze bags.
faded blue bags contain no other bags.
pale turquoise bags contain 1 vibrant gray bag, 3 plaid purple bags, 5 drab coral bags, 5 plaid indigo bags.
vibrant tan bags contain 4 pale yellow bags.
striped gold bags contain 1 dull salmon bag.
faded indigo bags contain 4 faded chartreuse bags, 2 wavy silver bags, 1 shiny green bag.
light plum bags contain 2 faded chartreuse bags, 1 plaid lime bag, 1 posh violet bag, 5 faded plum bags.
dim indigo bags contain 2 dim black bags, 1 wavy plum bag, 4 dark blue bags.
mirrored bronze bags contain 4 dark gold bags, 4 posh tomato bags, 2 plaid aqua bags.
posh indigo bags contain 2 dim maroon bags, 1 dotted gray bag, 4 dark brown bags, 3 wavy indigo bags.
mirrored silver bags contain 3 dull aqua bags, 5 mirrored purple bags.
drab magenta bags contain 5 pale beige bags, 4 dotted indigo bags.
drab bronze bags contain 1 dotted brown bag, 5 clear beige bags.
mirrored lavender bags contain 4 posh purple bags, 2 mirrored cyan bags, 3 drab gold bags.
dotted purple bags contain 2 striped teal bags, 5 clear plum bags, 2 striped lavender bags, 2 dull violet bags.
light aqua bags contain 2 faded blue bags, 4 drab violet bags, 5 dim aqua bags.
dim green bags contain 5 dark bronze bags, 3 light crimson bags, 2 bright yellow bags.
dotted cyan bags contain 3 light aqua bags.
muted gold bags contain 5 shiny maroon bags.
shiny crimson bags contain 5 pale aqua bags, 4 dull salmon bags, 4 dark turquoise bags.
dotted beige bags contain 2 drab cyan bags, 5 mirrored bronze bags, 4 vibrant bronze bags, 5 shiny blue bags.
muted chartreuse bags contain 3 plaid beige bags.
striped lime bags contain 2 muted orange bags.
dull violet bags contain 2 dark gold bags, 4 posh maroon bags, 2 vibrant teal bags, 4 drab teal bags.
shiny bronze bags contain 5 light tomato bags, 1 dull blue bag, 4 dark black bags, 1 posh chartreuse bag.
clear green bags contain 1 light green bag, 5 dim plum bags.
wavy black bags contain 3 clear fuchsia bags, 2 striped violet bags, 1 vibrant indigo bag.
posh lime bags contain 5 pale cyan bags, 3 clear fuchsia bags, 1 posh white bag, 4 dark turquoise bags.
striped violet bags contain 5 bright white bags, 5 dull blue bags, 3 light tomato bags, 3 mirrored green bags.
dotted brown bags contain 5 posh tomato bags.
dotted red bags contain 4 dim tomato bags, 1 drab beige bag.
wavy white bags contain 5 plaid crimson bags, 2 light magenta bags.
muted teal bags contain 5 dim crimson bags, 1 dim cyan bag.
bright lavender bags contain 2 dark lavender bags, 2 mirrored cyan bags, 1 dim yellow bag, 5 vibrant teal bags.
clear coral bags contain 2 drab beige bags, 1 drab yellow bag, 1 dotted tan bag.
clear gray bags contain 3 plaid lime bags, 1 dull beige bag, 5 light beige bags.
drab tan bags contain 3 dull salmon bags, 3 wavy tomato bags, 2 muted orange bags, 5 clear cyan bags.
muted gray bags contain 5 dull cyan bags, 4 clear olive bags.
striped black bags contain 4 dull plum bags, 3 faded gray bags, 3 faded cyan bags.
clear violet bags contain 4 posh bronze bags, 1 pale gold bag.
""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 46,713 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/year2022/day09/Solution.kt | LewsTherinTelescope | 573,240,975 | false | {"Kotlin": 33565} | package year2022.day09
import utils.runIt
import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() = runIt(
testInput = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent(),
part1 = ::part1,
testAnswerPart1 = 13,
testInputPart2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent(),
part2 = ::part2,
testAnswerPart2 = 36,
)
fun part1(input: String): Int = input.lines()
.map(Move::from)
.let(Rope(2)::moveTrackingTail)
.size
fun part2(input: String): Int = input.lines()
.map(Move::from)
.let(Rope(10)::moveTrackingTail)
.size
data class Move(
val direction: Char,
val amount: Int,
) {
companion object {
fun from(stringForm: String) = Move(
direction = stringForm[0],
amount = stringForm.substringAfter(" ").toInt(),
)
}
}
data class Rope(val length: Int) {
fun moveTrackingTail(moves: List<Move>): Set<Point> = hashSetOf<Point>().apply {
val knots = Array(length) { IntArray(2) }
val lastKnot = length - 1
moves.forEach { (direction, amount) ->
repeat(amount) {
when (direction) {
'R' -> knots[0].x++
'L' -> knots[0].x--
'U' -> knots[0].y++
'D' -> knots[0].y--
}
(1 until length).forEach { i ->
val prev = i - 1
if (chessDistance(knots[prev], knots[i]) > 1) {
knots[i].x += (knots[prev].x compareTo knots[i].x).sign
knots[i].y += (knots[prev].y compareTo knots[i].y).sign
}
}
add(knots[lastKnot].toPoint())
}
}
}
}
data class Point(val x: Int, val y: Int)
fun IntArray.toPoint() = Point(x, y)
inline var IntArray.x
get() = get(0)
set(value) { set(0, value) }
inline var IntArray.y
get() = get(1)
set(value) { set(1, value) }
fun chessDistance(first: IntArray, second: IntArray) =
maxOf((second.x - first.x).absoluteValue, (second.y - first.y).absoluteValue)
| 0 | Kotlin | 0 | 0 | ee18157a24765cb129f9fe3f2644994f61bb1365 | 1,843 | advent-of-code-kotlin | Do What The F*ck You Want To Public License |
kotlin/2018/src/main/kotlin/2018/Lib02.kt | nathanjent | 48,783,324 | false | {"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966} | package aoc.kt.y2018;
/**
* Day 2.
*/
/** Part 1 */
fun processBoxChecksum1(input: String): String {
val (count2s, count3s) = input.lines()
.filter { !it.isEmpty() }
.map {
val charCounts = mutableMapOf<Char, Int>()
it.forEach { c ->
val count = charCounts.getOrDefault(c, 0)
charCounts.put(c, count + 1)
}
Pair(if (charCounts.containsValue(2)) 1 else 0,
if (charCounts.containsValue(3)) 1 else 0)
}
.fold(Pair(0, 0), {
(count2s, count3s), (two, three) ->
Pair(count2s + two, count3s + three)
})
return (count2s * count3s).toString()
}
/** Part 2 */
fun processBoxChecksum2(input: String): String {
val lines = input.lines()
.filter { !it.isEmpty() }
val matchCounts = mutableMapOf<String, Pair<Int, Int>>()
for (l1 in lines) {
for (l2 in lines) {
if (l1 == l2) continue
// use combined lines as key
val key = "$l1:$l2"
l1.zip(l2).forEachIndexed({
index, (c1, c2) ->
val (count, pIndex) =
matchCounts.getOrDefault(key, Pair(0, -1))
if (c1 == c2) {
// count matching characters
matchCounts.put(key, Pair(count + 1, pIndex))
} else {
// index of the non-matching character
matchCounts.put(key, Pair(count, index))
}
})
}
}
val maxEntry = matchCounts
.maxBy { (_, p) -> p.first }
val (_, index) = maxEntry?.component2()?:Pair(0, -1)
val key = maxEntry?.component1()?:""
val word = key.substringBefore(':')
val first = word.substring(0 until index)
val last = word.substring(index+1..word.length-1)
return "$first$last"
}
| 0 | Rust | 0 | 0 | 7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf | 1,912 | adventofcode | MIT License |
src/Day12/Day12.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | import java.util.*
fun main() {
fun preprocess(input: List<String>): Map<String, List<String>> {
val res = mutableMapOf<String, MutableList<String>>()
for (e in input) {
val split = e.split('-')
val l1 = res.getOrDefault(split[0], mutableListOf())
l1.add(split[1])
res[split[0]] = l1
val l2 = res.getOrDefault(split[1], mutableListOf())
l2.add(split[0])
res[split[1]] = l2
}
return res
}
fun String.isUppercase(): Boolean = this.uppercase() == this
fun calc(input: Map<String, List<String>>, selector: (List<String>, String) -> Boolean): Int {
var res = 0
val queue = LinkedList<List<String>>()
queue.add(listOf("start"))
while (queue.isNotEmpty()) {
val cur = queue.pop()
val next = input[cur.last()]
if (next != null) {
for (e in next) {
if (e == "end") {
res++
} else if (selector(cur, e)) {
val newCur = cur.toMutableList()
newCur.add(e)
queue.add(newCur)
}
}
}
}
return res
}
fun part1(input: Map<String, List<String>>): Int {
return calc(input) { l, e -> e.isUppercase() || !l.contains(e) }
}
fun part2(input: Map<String, List<String>>): Int {
return calc(input) { l, e ->
val filtered = l.filter { !it.isUppercase() }
val hasDouble = filtered.toSet().size != filtered.size
val count = filtered.count { it == e }
e != "start" && (e.isUppercase() || count == 0 || (!hasDouble && count < 2))
}
}
val testInput = preprocess(readInput(12, true))
val input = preprocess(readInput(12))
check(part1(testInput) == 226)
println(part1(input))
check(part2(testInput) == 3509)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 2,036 | advent-of-code-2021 | Apache License 2.0 |
src/problems/day3/part1/part1.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day3.part1
import java.io.File
//private const val testFile = "input/day3/test.txt"
private const val part_numbers = "input/day3/part_numbers.txt"
fun main() {
val partNumberSum = File(part_numbers).bufferedReader().useLines { sumPartNumbers(it) }
println("Part Number Sum: $partNumberSum")
}
private fun sumPartNumbers(lines: Sequence<String>): Int {
val possiblePNs: MutableList<PossiblePN> = mutableListOf()
val symbols: MutableMap<Int, Set<Int>> = mutableMapOf()
lines.forEachIndexed {row, line ->
val res = parseLine(line, row)
possiblePNs.addAll(res.possiblePNs)
symbols[row] = res.symbols
}
return possiblePNs.filter { it.adjacentToSymbol(symbols) }.sumOf { it.value }
}
private fun parseLine(line: String, row: Int) = LineResult(
accumulateNumbers(line, row),
recordSymbols(line),
)
private fun accumulateNumbers(line: String, row: Int): List<PossiblePN> {
val accumulator = PossiblePNAccumulator(row)
line.forEach { accumulator.nextChar(it) }
return accumulator.end()
}
private fun recordSymbols(line: String): Set<Int> {
val symbols = mutableSetOf<Int>()
line.forEachIndexed { index, c -> if (c.isSymbol()) symbols.add(index)}
return symbols
}
private fun Char.isSymbol() = (this !in '0'..'9') and (this != '.')
private data class PossiblePN(val value: Int, val row: Int, val startCol: Int, val endCol: Int) {
fun adjacentToSymbol(symbols: Map<Int, Set<Int>>): Boolean {
return aboveRowContainsSymbol(symbols) or
rowContainsSymbol(symbols) or
belowRowContainsSymbols(symbols)
}
private fun aboveRowContainsSymbol(symbols: Map<Int, Set<Int>>) = checkRowSegment(symbols, row - 1)
private fun rowContainsSymbol(symbols: Map<Int, Set<Int>>): Boolean {
val targetRow = symbols[row] ?: return false
return targetRow.contains(startCol - 1) or targetRow.contains(endCol + 1)
}
private fun belowRowContainsSymbols(symbols: Map<Int, Set<Int>>) = checkRowSegment(symbols, row + 1)
private fun checkRowSegment(symbols: Map<Int, Set<Int>>, row: Int): Boolean {
val targetRow = symbols[row] ?: return false
for (col in startCol - 1..endCol + 1) {
if (targetRow.contains(col)) return true
}
return false
}
}
private data class LineResult(val possiblePNs: List<PossiblePN>, val symbols: Set<Int>)
private class PossiblePNAccumulator(private val row: Int) {
private val possiblePNs = mutableListOf<PossiblePN>()
private val currentNumber = StringBuilder()
private var currentCol = 0
private var currentStartCol = 0
private var currentEndCol = 0
private var currentState = State.OUT_NUMBER
private enum class State {
IN_NUMBER, OUT_NUMBER
}
fun nextChar(character: Char) {
when {
(character in '0'..'9') and (currentState == State.OUT_NUMBER) -> {
currentState = State.IN_NUMBER
currentNumber.append(character)
currentStartCol = currentCol
currentEndCol = currentCol
}
(character in '0'..'9') and (currentState == State.IN_NUMBER) -> {
currentNumber.append(character)
currentEndCol = currentCol
}
(character !in '0'..'9') and (currentState == State.IN_NUMBER) -> {
currentState = State.OUT_NUMBER
recordPossiblePN()
currentNumber.clear()
}
}
currentCol++
}
private fun recordPossiblePN() {
possiblePNs.add(
PossiblePN(
value = currentNumber.toString().toInt(),
row = row,
startCol = currentStartCol,
endCol = currentEndCol,
)
)
}
fun end(): List<PossiblePN> {
if (currentState == State.IN_NUMBER) {
recordPossiblePN()
}
return possiblePNs
}
} | 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 4,034 | aoc2023 | MIT License |
src/Day08.kt | zhiqiyu | 573,221,845 | false | {"Kotlin": 20644} | import kotlin.math.max
class Grid(input: List<String>) {
var m: Int
var n: Int
private val grid: List<List<Int>>
var visible: MutableList<MutableList<Boolean>>
init {
m = input.size
n = input.get(0).length
grid = input.map { it.toList().map(Char::digitToInt) }
visible = MutableList(m) { MutableList(n) {false}}
}
fun getVisibleTrees() {
for (i in 0..m-1) {
var curHighest = -1
for (j in 0..n-1) {
curHighest = compare(i, j, curHighest)
}
curHighest = -1
for (j in n-1 downTo 0) {
curHighest = compare(i, j, curHighest)
}
}
for (j in 0..n-1) {
var curHighest = -1
for (i in 0..m-1) {
curHighest = compare(i, j, curHighest)
}
curHighest = -1
for (i in m-1 downTo 0) {
curHighest = compare(i, j, curHighest)
}
}
}
private fun compare(i: Int, j: Int, curHighest: Int): Int {
var local = curHighest
if (grid.get(i).get(j) > local) {
local = grid.get(i).get(j)
visible.get(i).set(j, true)
}
return local
}
fun getScenicScore(i: Int, j: Int): Int {
if (i == 0 || j == 0 || i == m-1 || j == n-1) return 0
var result = 1
var count = 0
var height = grid.get(i).get(j)
for (p in i-1 downTo 0) {
count += 1
if (grid.get(p).get(j) >= height) {
break
}
}
result *= count
count = 0
for (p in i+1..m-1) {
count += 1
if (grid.get(p).get(j) >= height) {
break
}
}
result *= count
count = 0
for (q in j-1 downTo 0) {
count += 1
if (grid.get(i).get(q) >= height) {
break
}
}
result *= count
count = 0
for (q in j+1..n-1) {
count += 1
if (grid.get(i).get(q) >= height) {
break
}
}
result *= count
return result
}
fun getMaxScenicScore(): Int {
var maxScore = 0
for (i in 0..m-1) {
for (j in 0..n-1) {
maxScore = max(maxScore, getScenicScore(i, j))
}
}
return maxScore
}
fun countVisible(): Int {
return visible.map { it -> it.map { v -> if (v) 1 else 0}.sum()}.sum()
}
fun print() {
println(grid)
}
}
fun main() {
fun part1(input: List<String>): Int {
var grid = Grid(input)
grid.getVisibleTrees()
return grid.countVisible()
}
fun part2(input: List<String>): Int {
var grid = Grid(input)
return grid.getMaxScenicScore()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
print(part2(testInput))
check(part2(testInput) == 8)
val input = readInput("Day08")
println("----------")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d3aa03b2ba2a8def927b94c2b7731663041ffd1d | 3,386 | aoc-2022 | Apache License 2.0 |
src/Day20.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import kotlin.math.absoluteValue
object Day20 {
fun mix(input: List<IndexedValue<Long>>): MutableList<IndexedValue<Long>> {
val sorted = input.toMutableList()
input.sortedBy { it.index }.forEach { (index, value) ->
if (value == 0L) return@forEach
val curr = sorted.find { it.index == index }!!
val idx = sorted.indexOfFirst { it.index == index }
sorted.removeAt(idx)
val nexIdx = ((idx.toLong() + value) % (sorted.size)).let {
if (it <= 0) {
sorted.size - it.absoluteValue
} else it
}
sorted.add(nexIdx.absoluteValue.toInt(), curr)
// sorted.map { it.value }.log("n $n")
}
return sorted
}
fun part1(input: List<Long>) {
val mixed = input.withIndex().toMutableList().let { mix(it) }
val zIdx = mixed.indexOfFirst { it.value == 0L }
val normalized = mixed.subList(zIdx, mixed.size) + mixed.subList(0, zIdx)
listOf(1000, 2000, 3000).map { normalized[(it % normalized.size)] }.sumOf { it.value }
.log("part1")
}
fun part2(input: List<Long>) {
val mixed = input.map { it * 811589153 }.withIndex().toMutableList().let {
(0..9).fold(it) {acc, i ->
mix(acc).also { it.map { it.value }.log("i: $i")}
}
}
//861096091333 low
val zIdx = mixed.indexOfFirst { it.value == 0L }
val normalized = mixed.subList(zIdx, mixed.size) + mixed.subList(0, zIdx)
listOf(1000, 2000, 3000).map { normalized[(it % normalized.size)] }.log().sumOf { it.value }
.log("part1")
}
@JvmStatic
fun main(args: Array<String>) {
val input = downloadAndReadInput("Day20", "\n").filter { it.isNotBlank() }
.map { it.toLong() }
part1(input)
part2(input)
}
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 1,938 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/2022/Day08_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | import kotlin.math.max
private typealias Mat = List<List<Int>>
fun Mat.transpose(): Mat {
val res = List<MutableList<Int>>(size) { mutableListOf() }
for (j in indices)
for (i in indices)
res[j].add(this[i][j])
return res
}
fun Mat.hflip(): Mat = map {it.asReversed()}
////////////////////////////////// part1 ///////////////////////////////
fun Mat.visibleFromLeft(): Mat {
val res = List<MutableList<Int>>(size) { mutableListOf() }
for (i in indices) {
var mx = -1
for (j in indices) {
if (this[i][j] <= mx) res[i].add(0)
else {
mx = this[i][j]
res[i].add(1)
}
}
}
return res
}
private fun part1(m: Mat): Int {
val sides = listOf(
m.visibleFromLeft(),
m.hflip().visibleFromLeft().hflip(),
m.transpose().visibleFromLeft().transpose(),
m.transpose().hflip().visibleFromLeft().hflip().transpose(),
)
// count (i, j) indices where at least one element is > 0
var cnt = 0
for (i in m.indices)
for (j in m[i].indices)
for (mat in sides)
if (mat[i][j] > 0) {
cnt += 1
break
}
return cnt
}
////////////////////////////////// part2 ///////////////////////////////
fun Mat.scoreFromLeft(): Mat {
val res = List<MutableList<Int>>(size) { mutableListOf() }
for (i in indices) {
var highIdx = -1
for (j in indices) {
if (highIdx < 0 || this[i][j] > this[i][highIdx]) {
res[i].add(j)
highIdx = j
}
else res[i].add(j - highIdx)
if (this[i][j] == this[i][highIdx]) highIdx = j
}
}
return res
}
private fun part2(m: Mat): Int {
val sides = listOf(
m.scoreFromLeft(),
m.hflip().scoreFromLeft().hflip(),
m.transpose().scoreFromLeft().transpose(),
m.transpose().hflip().scoreFromLeft().hflip().transpose(),
)
// get (i,j) with the highest score multiplied from all sides
var best = 0
for (i in m.indices)
for (j in m[i].indices) {
val scores = sides.map {it[i][j]}
val score = scores.reduce {acc, x -> acc * x}
best = max(best, score)
}
return best
}
fun main() {
val input = readInput(8).trim()
val m: List<List<Int>> = input.lines()
.map {
it.toList().map { it.digitToInt() }
}
println(part1(m))
println(part2(m))
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 2,569 | adventofcode | Apache License 2.0 |
src/main/kotlin/dec19/Main.kt | dladukedev | 318,188,745 | false | null | package dec19
sealed class Rule {
data class Terminator(val character: String): Rule()
data class Step(val paths: List<List<Int>>): Rule()
}
fun parseRule(input: String): Pair<Int, Rule> {
val (ruleId, rule) = input.split(": ")
return if(rule.contains("\"")) {
ruleId.toInt() to Rule.Terminator(rule[1].toString())
} else {
val paths = rule.split(" | ")
.map { path -> path.split(" ").map { value -> value.toInt() } }
ruleId.toInt() to Rule.Step(paths)
}
}
fun parseRules(input: String): HashMap<Int, Rule> {
return input
.lines()
.map {
parseRule(it)
}.toMap() as HashMap
}
fun getValidResults(rules: HashMap<Int, Rule>, ruleId: Int = 0): List<String> {
return when(val currentRule = rules[ruleId]) {
is Rule.Step -> {
return currentRule.paths.map {
it.map{ pathRuleId ->
getValidResults(rules, pathRuleId)
}.joinToString("")
}
}
is Rule.Terminator -> {
listOf(currentRule.character)
}
else -> throw Exception("Failure")
}
}
fun buildRegex(rules: HashMap<Int, Rule>, ruleId: Int = 0): String {
return when(val currentRule = rules[ruleId]) {
is Rule.Step -> {
when {
currentRule.paths.count() == 1 -> {
currentRule.paths.first().joinToString("") { buildRegex(rules, it) }
}
currentRule.paths.count() > 1 -> {
"(${currentRule.paths.joinToString("|") { it.joinToString("") { rule -> buildRegex(rules, rule) } }})"
}
else -> {
""
}
}
}
is Rule.Terminator -> {
currentRule.character
}
else -> throw Exception("Failure")
}
}
fun buildRegex2(rules: HashMap<Int, Rule>, ruleId: Int = 0): String {
if(ruleId == 8) {
val regex42 = buildRegex2(rules, 42)
return "($regex42+)"
}
if(ruleId == 11) {
val regex42 = buildRegex2(rules, 42)
val regex31 = buildRegex2(rules, 31)
val regex = (0..100).map {
(0..it).joinToString("") { regex42 } + (0..it).joinToString("") { regex31 }
}.joinToString("|") { "($it)" }
return "($regex)"
}
return when(val currentRule = rules[ruleId]) {
is Rule.Step -> {
when {
currentRule.paths.count() == 1 -> {
currentRule.paths.first().joinToString("") { buildRegex2(rules, it) }
}
currentRule.paths.count() > 1 -> {
"(${currentRule.paths.joinToString("|") { it.joinToString("") { rule -> buildRegex2(rules, rule) } }})"
}
else -> {
""
}
}
}
is Rule.Terminator -> {
currentRule.character
}
else -> throw Exception("Failure")
}
}
fun main() {
val parsed = parseRules(rulesInput)
println("------------ PART 1 ------------")
val regex = Regex(buildRegex(parsed))
val result = input.lines().filter {
it.matches(regex)
}.count()
println("result: $result")
println("------------ PART 2 ------------")
parsed.replace(8, parseRule("8: 42 | 42 8").second)
parsed.replace(11, parseRule("11: 42 31 | 42 11 31").second)
val regex2 = Regex(buildRegex2(parsed))
val result2 = input.lines().filter {
it.matches(regex2)
}.count()
println("result: $result2")
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 3,641 | advent-of-code-2020 | MIT License |
src/Day17.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | data class RockPos(val x: Int, val y: Int) {
fun move(jet: Int) = this.copy(x = x + jet)
fun fallDown(): RockPos = this.copy(y = y - 1)
}
fun lineRock(xStart: Int, y: Int) = (xStart..xStart + 3).map { x -> RockPos(x, y) }
fun plusRock(xStart: Int, y: Int) = listOf(
RockPos(xStart, y + 1),
RockPos(xStart + 1, y + 1),
RockPos(xStart + 2, y + 1),
RockPos(xStart + 1, y),
RockPos(xStart + 1, y + 2)
)
fun elRock(xStart: Int, y: Int) = listOf(
RockPos(xStart, y),
RockPos(xStart + 1, y),
RockPos(xStart + 2, y),
RockPos(xStart + 2, y + 1),
RockPos(xStart + 2, y + 2)
)
fun pipeRock(xStart: Int, y: Int) = (0..3).map { RockPos(xStart, y + it) }
fun sqRock(xStart: Int, y: Int) =
listOf(RockPos(xStart, y), RockPos(xStart + 1, y), RockPos(xStart, y + 1), RockPos(xStart + 1, y + 1))
fun makeRock(n: Int, y: Int): List<RockPos> = when (n) {
0 -> lineRock(2, y)
1 -> plusRock(2, y)
2 -> elRock(2, y)
3 -> pipeRock(2, y)
4 -> sqRock(2, y)
else -> error("unknown rock type: $n")
}
fun List<RockPos>.canMove(jet: Int, cave: Set<RockPos>): Boolean {
val inBound = if (jet == -1) {
this.minOf { it.x } > 0
} else {
this.maxOf { it.x } < 6
}
return inBound && this.none { RockPos(it.x + jet, it.y) in cave }
}
fun List<RockPos>.fall() = this.map { it.fallDown() }
fun Set<RockPos>.highestPoint() = this.maxOfOrNull { it.y } ?: 0
fun Set<RockPos>.hasPattern(y: Int): Boolean {
// ..#.##.
// ..#.##.
val hasFirstRow = (0..1).all { RockPos(it, y) !in this }
&& (RockPos(2, y) in this)
&& (RockPos(3, y) !in this)
&& (4..5).all { RockPos(it, y) in this }
&& (RockPos(6, y) !in this)
val hasSecondRow = (0..1).all { RockPos(it, y + 1) !in this }
&& (RockPos(2, y + 1) in this)
&& (RockPos(3, y + 1) !in this)
&& (4..5).all { RockPos(it, y + 1) in this }
&& (RockPos(6, y + 1) !in this)
return hasFirstRow && hasSecondRow
}
fun RockPos.canFall(cave: Set<RockPos>) = !cave.contains(this.copy(y = this.y - 1)) && this.y > 1
fun main() {
fun part1(input: String): Int {
val jetPattern = input.trim().map { if (it == '<') -1 else 1 }
val cave = mutableSetOf<RockPos>()
var time = 0
(0 until 2022).map { rockNum ->
val yStart = cave.highestPoint() + 4
var rock = makeRock(rockNum % 5, yStart)
var isAtRest = false
while (!isAtRest) {
rock = rock.map { piece ->
val jet = jetPattern[time % jetPattern.size]
if (rock.canMove(jet, cave)) {
piece.move(jet)
} else {
// no-op
piece
}
}
isAtRest = !rock.all { it.canFall(cave) }
if (!isAtRest) {
rock = rock.fall()
}
time++
}
rock.map { cave += it }
}
return cave.highestPoint()
}
// TODO: not correct
fun part2(input: String): Long {
val jetPattern = input.trim().map { if (it == '<') -1 else 1 }
val cave = mutableSetOf<RockPos>()
var time = 0
val heightHistory = mutableListOf(0)
(0 until 2022).map { rockNum ->
val yStart = cave.highestPoint()
var rock = makeRock(rockNum % 5, yStart)
var isAtRest = false
while (!isAtRest) {
rock = rock.map { piece ->
val jet = jetPattern[time % jetPattern.size]
if (rock.canMove(jet, cave)) {
piece.move(jet)
} else {
piece
}
}
isAtRest = !rock.all { it.canFall(cave) }
if (!isAtRest) {
rock = rock.fall()
}
time++
}
rock.map { cave += it }
heightHistory += cave.highestPoint()
}
// find a loop in the heights over iterations. Use a heuristic to guess
val heightDiffs = heightHistory.zipWithNext().map { (a, b) -> b - a}
// arbitrary starting points
val loopStart = 200
val markerLength = 10
val marker = heightDiffs.subList(loopStart, loopStart + markerLength)
var loopHeight = -1
var loopLength = -1
val heightBeforeLoop = heightDiffs[loopStart-1]
for (i in loopStart+markerLength until heightDiffs.size) {
// we found a match
if (marker == heightDiffs.subList(i, i + markerLength)) {
loopLength = i - loopStart
loopHeight = heightHistory[i - 1] + heightBeforeLoop
break
}
}
val targetRocks = 1_000_000_000_000
val fullLoops = (targetRocks - loopStart) / loopLength
val offset = ((targetRocks - loopStart) % loopLength).toInt()
val extraY = heightHistory[loopStart + offset] - heightBeforeLoop
return heightBeforeLoop + loopHeight * fullLoops + extraY
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsText("Day17_test")
check(part1(testInput) == 3068)
val input = readInputAsText("Day17")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 5,510 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | arksap2002 | 576,679,233 | false | {"Kotlin": 31030} | import java.util.*
import kotlin.math.min
fun isCorrect(from: Char, to: Char): Boolean = to - from <= 1
fun main() {
fun part1(input: List<String>): Int {
val board = mutableListOf<MutableList<Int>>()
val used = mutableListOf<MutableList<Boolean>>()
var current = Pair(0, 0)
var finish = Pair(0, 0)
for (i in input.indices) {
val tmpBoard = mutableListOf<Int>()
val tmpUsed = mutableListOf<Boolean>()
for (j in 0 until input[0].length) {
if (input[i][j] == 'S') {
current = Pair(i, j)
}
if (input[i][j] == 'E') finish = Pair(i, j)
tmpBoard.add(Int.MAX_VALUE)
tmpUsed.add(false)
}
board.add(tmpBoard)
used.add(tmpUsed)
}
board[current.first][current.second] = 0
used[current.first][current.second] = true
val queue: Queue<Pair<Int, Int>> = LinkedList()
queue.add(current)
while (!queue.isEmpty()) {
current = queue.remove()!!
val x = current.first
val y = current.second
val xes = listOf(0, 0, -1, 1)
val yes = listOf(-1, 1, 0, 0)
for (i in xes.indices) {
val newX = x + xes[i]
val newY = y + yes[i]
if (newX < 0 || newX >= input.size || newY < 0 || newY >= input[0].length) continue
if (isCorrect(input[x][y], input[newX][newY])
|| (input[x][y] == 'S' && isCorrect('a', input[newX][newY]))
|| (input[newX][newY] == 'E' && isCorrect(input[x][y], 'z'))
) {
board[newX][newY] = min(board[newX][newY], board[x][y] + 1)
if (!used[newX][newY]) {
queue.add(Pair(newX, newY))
used[newX][newY] = true
}
}
}
}
return board[finish.first][finish.second]
}
fun part2(input: List<String>): Int {
var result = part1(input)
val starts = mutableListOf<Pair<Int, Int>>()
val newInput = mutableListOf<String>()
var current = Pair(0, 0)
for (i in input.indices) {
newInput.add(input[i])
for (j in 0 until input[0].length) {
if (input[i][j] == 'a') starts.add(Pair(i, j))
if (input[i][j] == 'S') current = Pair(i, j)
}
}
for (pair in starts) {
var s = ""
for (i in 0 until newInput[current.first].length) {
s += if (newInput[current.first][i] == 'S') {
'a'
} else {
newInput[current.first][i]
}
}
newInput[current.first] = s
current = pair
s = ""
for (i in 0 until newInput[current.first].length) {
s += if (i == current.second) {
'S'
} else {
newInput[current.first][i]
}
}
newInput[current.first] = s
result = min(result, part1(newInput))
}
return result
}
val input = readInput("Day12")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a24a20be5bda37003ef52c84deb8246cdcdb3d07 | 3,389 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D11.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
import io.github.pshegger.aoc.common.Coordinate
class Y2020D11 : BaseSolver() {
override val year = 2020
override val day = 11
override fun part1(): Int = calculateOccupiedSeats(true, 4)
override fun part2(): Int = calculateOccupiedSeats(false, 5)
private fun calculateOccupiedSeats(adjacentMode: Boolean, emptyThreshold: Int): Int {
var prev = parseInput()
val vision = prev.calculateVision(adjacentMode)
var settled = false
while (!settled) {
val n = prev.step(vision, emptyThreshold)
if (n == prev) {
settled = true
}
prev = n
}
return prev.sumOf { row -> row.count { it == '#' } }
}
private fun List<String>.calculateVision(adjacentMode: Boolean): Map<Coordinate, List<Coordinate>> =
flatMapIndexed { y, row ->
row.mapIndexed { x, _ ->
val c = Coordinate(x, y)
Pair(c, calculateVisionAt(c, adjacentMode))
}
}.toMap()
private fun List<String>.calculateVisionAt(c: Coordinate, adjacentMode: Boolean): List<Coordinate> =
(-1..1).flatMap { dy ->
(-1..1).mapNotNull { dx ->
when {
dx == 0 && dy == 0 -> null
adjacentMode && isSeat(Coordinate(c.x + dx, c.y + dy)) -> Coordinate(c.x + dx, c.y + dy)
!adjacentMode -> {
var seatFound = false
var seat: Coordinate? = null
var i = 1
while (!seatFound) {
val dc = Coordinate(c.x + dx * i, c.y + dy * i)
if (!isInBounds(dc)) {
seatFound = true
} else if (isSeat(dc)) {
seatFound = true
seat = dc
}
i++
}
seat
}
else -> null
}
}
}
private fun List<String>.isInBounds(c: Coordinate) =
c.y in indices && c.x in this[c.y].indices
private fun List<String>.isSeat(c: Coordinate) =
isInBounds(c) && this[c.y][c.x] in listOf('L', '#')
private fun List<String>.step(
vision: Map<Coordinate, List<Coordinate>>,
emptyThreshold: Int
): List<String> =
mapIndexed { y, row ->
row.mapIndexed { x, c ->
val occupiedAdjacents = (vision[Coordinate(x, y)] ?: error("No precomputed vision found for ($x, $y)"))
.count { (ax, ay) -> this[ay][ax] == '#' }
when {
c == 'L' && occupiedAdjacents == 0 -> '#'
c == '#' && occupiedAdjacents >= emptyThreshold -> 'L'
else -> c
}
}.joinToString("")
}
private fun parseInput() = readInput { readLines() }
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,150 | advent-of-code | MIT License |
app/src/main/kotlin/com/bloidonia/advent2020/Day_18.kt | timyates | 317,965,519 | false | null | package com.bloidonia.advent2020
import com.bloidonia.linesFromResource
class Day_18 {
enum class Op {
MUL, DIV, ADD, SUB, OPEN, CLOSE, NUMBER
}
data class Token(val op: Op, val arg: Long? = null)
fun tokenize(input: String) =
"(\\(|\\d+|\\+|-|\\*|/|\\))".toRegex().findAll(input).let {
var depth = 0L
it.map {
when (it.groupValues[0].trim()) {
"*" -> Token(Op.MUL)
"/" -> Token(Op.DIV)
"+" -> Token(Op.ADD)
"-" -> Token(Op.SUB)
"(" -> Token(Op.OPEN, ++depth)
")" -> Token(Op.CLOSE, depth--)
else -> Token(Op.NUMBER, it.groupValues[0].trim().toLong())
}
}
}
fun process(input: List<Token>, plusPrecidence: Boolean = false): Long {
var processing = input
while (processing.find { it.op == Op.OPEN } != null) {
val highest = processing.maxOfOrNull { if (it.op == Op.OPEN) it.arg!! else 0 }!!
val start = processing.indexOfFirst { it.op == Op.OPEN && it.arg == highest }
val end = processing.indexOfFirst { it.op == Op.CLOSE && it.arg == highest }
processing = processing.take(start)
.plusElement(Token(Op.NUMBER, process(processing.subList(start + 1, end), plusPrecidence)))
.plus(processing.drop(end + 1))
}
if (plusPrecidence) {
while (processing.find { it.op == Op.ADD } != null) {
val plusIndex = processing.indexOfFirst { it.op == Op.ADD }
processing = processing.take(plusIndex - 1)
.plusElement(Token(Op.NUMBER, processing[plusIndex - 1].arg!! + processing[plusIndex + 1].arg!!))
.plus(processing.drop(plusIndex + 2))
}
}
val start = processing.first().arg!!.toLong()
return processing.drop(1).chunked(2).fold(start) { acc, ops ->
if (ops[0].op == Op.MUL) acc * ops[1].arg!!
else if (ops[0].op == Op.DIV) acc / ops[1].arg!!
else if (ops[0].op == Op.ADD) acc + ops[1].arg!!
else acc - ops[1].arg!!
}
}
}
fun main() {
val day18 = Day_18()
val part1 = linesFromResource("/18.txt").map {
day18.process(day18.tokenize(it).toList(), false).toLong()
}.sum()
println(part1)
val part2 = linesFromResource("/18.txt").map {
day18.process(day18.tokenize(it).toList(), true).toLong()
}.sum()
println(part2)
} | 0 | Kotlin | 0 | 0 | cab3c65ac33ac61aab63a1081c31a16ac54e4fcd | 2,598 | advent-of-code-2020-kotlin | Apache License 2.0 |
src/day01/Day01.kt | martinhrvn | 724,678,473 | false | {"Kotlin": 27307, "Jupyter Notebook": 1336} | package day01
import println
import readInput
class CalibrationReader(val input: List<String>) {
val digitMapping =
mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9)
fun part1() = input.sumOf(::getCalibrationNumber)
fun part2() = input.sumOf(::getCalibrationIncludingWords)
private fun getCalibrationNumber(line: String): Int {
val first = line.first { it.isDigit() }
val last = line.last { it.isDigit() }
return "$first$last".toInt()
}
private fun getCalibrationIncludingWords(line: String): Int {
val first: Int =
line.indices.firstNotNullOf { i ->
if (line[i].isDigit()) {
line[i].digitToInt()
} else {
digitMapping.firstNotNullOfOrNull { (k, v) ->
if (line.startsWith(k, startIndex = i)) {
v
} else null
}
}
}
val last: Int =
line.indices.reversed().firstNotNullOf { i ->
if (line[i].isDigit()) {
line[i].digitToInt()
} else {
digitMapping.firstNotNullOfOrNull { (k, v) ->
if (line.startsWith(k, startIndex = i)) {
v
} else null
}
}
}
return first * 10 + last
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(CalibrationReader(testInput).part1() == 142)
val testInput_part2 = readInput("day01/Day01_2_test")
check(CalibrationReader(testInput_part2).part2() == 281)
val input = readInput("day01/Day01")
val calibrationReader = CalibrationReader(input)
calibrationReader.part1().println()
calibrationReader.part2().println()
}
| 0 | Kotlin | 0 | 0 | 59119fba430700e7e2f8379a7f8ecd3d6a975ab8 | 1,904 | advent-of-code-2023-kotlin | Apache License 2.0 |
src/Day01.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | fun main() {
fun part1(input: List<String>): Int {
return input.fold(mutableListOf(0)) { temp, el ->
if (el.isBlank()) {
temp.add(0)
} else {
temp[temp.size - 1] += el.toInt()
}
temp
}.max()
}
fun part2(input: List<String>): Int {
return input.fold(mutableListOf(0)) { temp, el ->
if (el.isBlank()) {
temp.add(0)
} else {
temp[temp.size - 1] += el.toInt()
}
temp
}.sorted().takeLast(3).sum()
}
fun beauty(input: List<String>): List<Int> =
input.joinToString(separator="\n").trim().split("\n\n").map { it.lines().sumOf(String::toInt) }.sortedDescending()
fun part1Beauty(input: List<String>): Int =
beauty(input).first()
fun part2Beauty(input: List<String>): Int =
beauty(input).take(3).sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
println(part1Beauty(input))
println(part2Beauty(input))
}
| 0 | Kotlin | 0 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 1,286 | aoc2022 | Apache License 2.0 |
src/Day02.kt | zhiqiyu | 573,221,845 | false | {"Kotlin": 20644} | import kotlin.math.max
import kotlin.math.abs
class Game(
var abc: Array<String> = arrayOf("A", "B", "C"), // rock, paper, scissor
var xyz: Array<String> = arrayOf("X", "Y", "Z") // lose, draw, win
) {
var pointMap: MutableMap<String, Int>
init {
pointMap = mutableMapOf<String, Int>()
for (i in abc.indices) {
for (j in xyz.indices) {
when (i - j) {
-2 -> pointMap.put(abc.get(i).plus(xyz.get(j)), 0)
-1 -> pointMap.put(abc.get(i).plus(xyz.get(j)), 6)
0 -> pointMap.put(abc.get(i).plus(xyz.get(j)), 3)
1 -> pointMap.put(abc.get(i).plus(xyz.get(j)), 0)
2 -> pointMap.put(abc.get(i).plus(xyz.get(j)), 6)
}
}
}
}
fun round(opponent: String, me: String): Int {
return xyz.indexOf(me) + 1 + pointMap.getValue(opponent.plus(me))
}
fun round2(opponent: String, result: String): Int {
var i = abc.indexOf(opponent)
var j = xyz.indexOf(result)
when (j) {
0 -> return (i-1).mod(3) + 1
1 -> return i + 1 + 3
2 -> return (i+1).mod(3) + 1 + 6
}
return 0
}
}
fun main() {
var game = Game()
fun part1(input: List<String>): Int {
var points = 0
for (line in input) {
var plays = line.split(" ")
points += game.round(plays.get(0), plays.get(1))
}
return points
}
fun part2(input: List<String>): Int {
var points = 0
for (line in input) {
val plays = line.split(" ")
points += game.round2(plays.get(0), plays.get(1))
}
return points
}
// 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("----------")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d3aa03b2ba2a8def927b94c2b7731663041ffd1d | 2,144 | aoc-2022 | Apache License 2.0 |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day12/Jupiter.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day12
import com.github.jrhenderson1988.adventofcode2019.lcm
import kotlin.math.abs
class Jupiter(val moons: List<Moon>) {
fun calculateTotalEnergyAfterSteps(steps: Int) =
(0 until steps).fold(moons) { ms, _ -> applyVelocity(applyGravity(ms)) }.sumBy {
val potential = abs(it.x) + abs(it.y) + abs(it.z)
val kinetic = abs(it.vx) + abs(it.vy) + abs(it.vz)
potential * kinetic
}
fun numberOfStepsUntilStateRepeated(): Long {
val x = stepsUntilFirstRepetition({ it.x }, { it.vx })
val y = stepsUntilFirstRepetition({ it.y }, { it.vy })
val z = stepsUntilFirstRepetition({ it.z }, { it.vz })
return lcm(lcm(x.toLong(), y.toLong()), z.toLong())
}
private fun stepsUntilFirstRepetition(position: (moon: Moon) -> Int, velocity: (moon: Moon) -> Int): Int {
var m = moons
val initialPositions = m.mapIndexed { i, moon -> i to Pair(position(moon), velocity(moon)) }.toMap()
var step = 0
while (true) {
step++
m = applyVelocity(applyGravity(m))
val stateMatches = m.foldIndexed(true) { i, prev, moon ->
prev && Pair(position(moon), velocity(moon)) == initialPositions[i]
}
if (stateMatches) {
return step
}
}
}
companion object {
fun parse(input: String) = Jupiter(input.trim().lines().map { Moon.parse(it) })
fun applyVelocity(moons: List<Moon>) =
moons.map { moon ->
Moon(
moon.x + moon.vx,
moon.y + moon.vy,
moon.z + moon.vz,
moon.vx,
moon.vy,
moon.vz
)
}
fun applyGravity(moons: List<Moon>) =
moons.map { moon ->
val others = moons.filter { it != moon }
Moon(
moon.x,
moon.y,
moon.z,
moon.vx + others.sumBy { other -> compareVelocity(moon.x, other.x) },
moon.vy + others.sumBy { other -> compareVelocity(moon.y, other.y) },
moon.vz + others.sumBy { other -> compareVelocity(moon.z, other.z) }
)
}
private fun compareVelocity(a: Int, b: Int) = when {
a > b -> -1
a < b -> 1
else -> 0
}
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 2,545 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day14.kt | SimonMarquis | 434,880,335 | false | {"Kotlin": 38178} | class Day14(raw: String) {
private val input: Pair<String, Set<Rule>> = raw.split("\n\n").let { (polymer, rules) ->
polymer to rules.lines().map { rule ->
rule.split(" -> ").let { (i, o) -> Rule(i, o) }
}.toSet()
}
fun part1(): Long = input.process(10)
fun part2(): Long = input.process(40)
private fun Pair<String, Set<Rule>>.process(step: Int) = let { (polymer, rules) ->
val initial = polymer.windowed(2, partialWindows = true).groupingBy { it }.eachCount().mapValues { it.value.toLong() }
(1..step).fold(initial) { acc, _ ->
acc.step(rules)
}.split().values.let {
it.maxOrNull()!! - it.minOrNull()!!
}
}
data class Rule(val input: String, val output: String)
private fun Map<String, Long>.step(rules: Set<Rule>): Map<String, Long> = buildMap {
this@step.entries.forEach { (k, v) ->
when (val rule = rules.singleOrNull { k == it.input }) {
null -> put(k, this[k] ?: v)
else -> {
put(k, (this[k] ?: this@step[k] ?: 0) - v)
val left = rule.input.take(1) + rule.output
put(left, (this[left] ?: this@step[left] ?: 0) + v)
val right = rule.output + rule.input.takeLast(1)
put(right, (this[right] ?: this@step[right] ?: 0) + v)
}
}
}
}
private fun Map<String, Long>.split(): Map<Char, Long> = buildMap {
this@split.entries.forEach { (k, v) ->
k.first().let { put(it, (this[it] ?: 0L) + v) }
}
}
} | 0 | Kotlin | 0 | 0 | 8fd1d7aa27f92ba352e057721af8bbb58b8a40ea | 1,645 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-11.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.time.measureTime
fun main() {
val input = readInputLines(2023, "11-input")
val test1 = readInputLines(2023, "11-test1")
measureTime {
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1, 10).println()
part2(test1, 100).println()
part2(input, 1000000).println()
}.also { it.println() }
}
private fun part1(input: List<String>) = solve(input, 2)
private fun part2(input: List<String>, times: Int) = solve(input, times)
private fun solve(input: List<String>, times: Int): Long {
val galaxies = input.flatMapIndexed { y: Int, line: String ->
line.mapIndexedNotNull { x, c -> c.takeIf { it == '#' }?.let { Coord2D(x, y) } }
}
val emptyRows = input.indices.filter { row -> input[row].all { it == '.' } }
val emptyCols = (0..<input.first().length).filter { input.all { line -> line[it] == '.' } }
val expanded = galaxies.map { (x, y) ->
Coord2D(x + emptyCols.count { it < x } * (times - 1), y + emptyRows.count { it < y } * (times - 1))
}
return expanded.indices.sumOf { i ->
(i + 1..expanded.lastIndex).sumOf { j ->
expanded[i].distanceTo(expanded[j]).toLong()
}
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,493 | advent-of-code | MIT License |
src/test/kotlin/chapter6/solutions/ex10/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter6.solutions.ex10
import chapter3.Cons
import chapter3.List
import chapter3.foldRight
import chapter6.RNG
import chapter6.rng1
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
//tag::init[]
data class State<S, out A>(val run: (S) -> Pair<A, S>) {
companion object {
fun <S, A> unit(a: A): State<S, A> =
State { s: S -> a to s }
//tag::ignore[]
fun <S, A, B, C> map2(
ra: State<S, A>,
rb: State<S, B>,
f: (A, B) -> C
): State<S, C> =
ra.flatMap { a ->
rb.map { b ->
f(a, b)
}
}
fun <S, A> sequence(fs: List<State<S, A>>): State<S, List<A>> =
foldRight(fs, unit(List.empty<A>()),
{ f, acc ->
map2(f, acc) { h, t -> Cons(h, t) }
}
)
//end::ignore[]
}
fun <B> map(f: (A) -> B): State<S, B> =
flatMap { a -> unit<S, B>(f(a)) }
fun <B> flatMap(f: (A) -> State<S, B>): State<S, B> =
State { s: S ->
val (a: A, s2: S) = this.run(s)
f(a).run(s2)
}
}
//end::init[]
class Solution10 : WordSpec({
"unit" should {
"compose a new state of pure a" {
State.unit<RNG, Int>(1).run(rng1) shouldBe (1 to rng1)
}
}
"map" should {
"transform a state" {
State.unit<RNG, Int>(1).map { it.toString() }
.run(rng1) shouldBe ("1" to rng1)
}
}
"flatMap" should {
"transform a state" {
State.unit<RNG, Int>(1)
.flatMap { i ->
State.unit<RNG, String>(i.toString())
}.run(rng1) shouldBe ("1" to rng1)
}
}
"map2" should {
"combine the results of two actions" {
val combined: State<RNG, String> =
State.map2(
State.unit(1.0),
State.unit(1)
) { d: Double, i: Int ->
">>> $d double; $i int"
}
combined.run(rng1).first shouldBe ">>> 1.0 double; 1 int"
}
}
"sequence" should {
"combine the results of many actions" {
val combined: State<RNG, List<Int>> =
State.sequence(
List.of(
State.unit(1),
State.unit(2),
State.unit(3),
State.unit(4)
)
)
combined.run(rng1).first shouldBe List.of(1, 2, 3, 4)
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 2,680 | fp-kotlin | MIT License |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day24/Day24.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day24
import nl.sanderp.aoc.common.measureDuration
import nl.sanderp.aoc.common.prettyPrint
import nl.sanderp.aoc.common.readResource
fun main() {
val input = readResource("Day24.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Long> { partOne(input) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
}
private sealed class Instruction
private data class Input(val a: Int) : Instruction()
private data class Add(val a: Int, val b: Int) : Instruction()
private data class AddLiteral(val a: Int, val b: Int) : Instruction()
private data class Multiply(val a: Int, val b: Int) : Instruction()
private data class MultiplyLiteral(val a: Int, val b: Int) : Instruction()
private data class DivideBy(val a: Int, val b: Int) : Instruction()
private data class DivideByLiteral(val a: Int, val b: Int) : Instruction()
private data class Mod(val a: Int, val b: Int) : Instruction()
private data class ModLiteral(val a: Int, val b: Int) : Instruction()
private data class Equals(val a: Int, val b: Int) : Instruction()
private data class EqualsLiteral(val a: Int, val b: Int) : Instruction()
private fun parse(line: String): Instruction {
val parts = line.split(' ')
val a = parts[1][0] - 'w'
if (parts[0] == "inp") {
return Input(a)
}
val b = parts[2]
return when (parts[0]) {
"add" -> if (b[0].isLetter()) Add(a, b[0] - 'w') else AddLiteral(a, b.toInt())
"mul" -> if (b[0].isLetter()) Multiply(a, b[0] - 'w') else MultiplyLiteral(a, b.toInt())
"div" -> if (b[0].isLetter()) DivideBy(a, b[0] - 'w') else DivideByLiteral(a, b.toInt())
"mod" -> if (b[0].isLetter()) Mod(a, b[0] - 'w') else ModLiteral(a, b.toInt())
"eql" -> if (b[0].isLetter()) Equals(a, b[0] - 'w') else EqualsLiteral(a, b.toInt())
else -> throw IllegalArgumentException("Cannot parse line: $line")
}
}
private fun run(instructions: List<Instruction>, w: Int, z: Int): Map<IntArray, Int> {
val memory = arrayOf(w, 0, 0, z)
for ((n, i) in instructions.withIndex()) {
when (i) {
is Input -> {
val rest = instructions.drop(n + 1)
return (1..9)
.flatMap { digit ->
run(rest, digit, memory[3]).mapKeys { IntArray(1) { digit } + it.key }.toList()
}
.toMap()
}
is Add -> memory[i.a] = memory[i.a] + memory[i.b]
is AddLiteral -> memory[i.a] = memory[i.a] + i.b
is Multiply -> memory[i.a] = memory[i.a] * memory[i.b]
is MultiplyLiteral -> memory[i.a] = memory[i.a] * i.b
is DivideBy -> memory[i.a] = memory[i.a] / memory[i.b]
is DivideByLiteral -> memory[i.a] = memory[i.a] / i.b
is Mod -> memory[i.a] = memory[i.a] % memory[i.b]
is ModLiteral -> memory[i.a] = memory[i.a] % i.b
is Equals -> if (memory[i.a] == memory[i.b]) memory[i.a] = 1 else memory[i.a] = 0
is EqualsLiteral -> if (memory[i.a] == i.b) memory[i.a] = 1 else memory[i.a] = 0
}
}
return mapOf(IntArray(0) to memory[3])
}
private fun partOne(instructions: List<Instruction>): Long {
val states = run(instructions, 0, 0)
.mapKeys { it.key.joinToString("").toLong() }
return states.filterValues { it == 0 }.maxOf { it.key }
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 3,424 | advent-of-code | MIT License |
src/Day04.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | fun main() {
fun List<Int>.includes(other: List<Int>) = this[0] <= other[0] && this[1] >= other[1]
fun intersects(a: List<Int>, b: List<Int>) = a[1] >= b[0] && b[1] >= a[0]
fun countPairs(input: List<String>, predicate: (List<Int>, List<Int>) -> Boolean): Int {
return input.count { line ->
val (a, b) = line.split(",")
.map { it.split("-").map(String::toInt) }
predicate(a, b)
}
}
fun part1(input: List<String>): Int = countPairs(input) { a, b ->
a.includes(b) || b.includes(a)
}
fun part2(input: List<String>) = countPairs(input, ::intersects)
val testInput = readInputLines("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInputLines("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 853 | Advent-of-Code-2022 | Apache License 2.0 |
day3/src/main/kotlin/Main.kt | joshuabrandes | 726,066,005 | false | {"Kotlin": 47373} | import java.io.File
fun main(args: Array<String>) {
println("------ Advent of Code 2023 - Day 3 -----")
val engineSchematic = if (args.isEmpty()) getPuzzleInput() else args.toList()
val validNumbers = getValidNumbers(engineSchematic)
println("Task 1: Sum of all valid numbers: ${validNumbers.sumOf { it.first }}")
println("Task 2: Sum of all gear ratios: ${getSumOfAllGearRatios(engineSchematic)}")
println("----------------------------------------")
}
fun getValidNumbers(engineSchematic: List<String>): MutableList<Pair<Int, Pair<Int, Int>>> {
val numbersWithPositions = mutableListOf<Pair<Int, Pair<Int, Int>>>()
// 1. Find all numbers and their positions
for (y in engineSchematic.indices) {
var x = 0
while (x < engineSchematic[y].length) {
if (engineSchematic[y][x].isDigit()) {
val result = completeNumberAndGetLastIndex(engineSchematic, x, y)
val number = result.first
numbersWithPositions.add(number to (x to y))
// Skip to the end of the number
x = result.second
}
x++
}
}
// 2. Find valid numbers (numbers with at least 1 symbol around)
val validNumbers = mutableListOf<Pair<Int, Pair<Int, Int>>>()
for ((number, position) in numbersWithPositions) {
val (x, y) = position
if (isValidNumber(engineSchematic, x, y))
validNumbers.add(number to position)
}
return validNumbers
}
fun getSumOfAllGearRatios(schematic: List<String>): Int {
val gearPositions = mutableListOf<Pair<Int, Int>>()
// 1. Find all potential gear positions
for (y in schematic.indices) {
for (x in schematic[y].indices) {
if (schematic[y][x] == '*') {
gearPositions.add(x to y)
}
}
}
// 2. Find all actual gears
val gears = mutableListOf<Gear>()
for ((x, y) in gearPositions) {
val adjacentGears = findAdjacentNumbers(schematic, x, y)
if (adjacentGears.size == 2)
gears.add(Gear(adjacentGears[0], adjacentGears[1]))
}
// 3. Calculate the sum of all gear ratios
return gears.sumOf { it.ratio }
}
fun findAdjacentNumbers(schematic: List<String>, x: Int, y: Int): List<Int> {
val adjacentNumbers = mutableListOf<Int>()
val xLeft = if (x - 1 >= 0) x - 1 else x
val xRight = if (x + 1 < schematic[y].length) x + 1 else x
// find potential left number
if (schematic[y][xLeft].isDigit()) {
adjacentNumbers.add(getFullNumber(schematic, xLeft, y))
}
// find potential right number
if (schematic[y][xRight].isDigit()) {
adjacentNumbers.add(getFullNumber(schematic, xRight, y))
}
// find potential top numbers
val topNumbers = findNumbersInRow(schematic, xLeft, xRight, y + 1)
adjacentNumbers.addAll(topNumbers)
// find potential bottom numbers
val bottomNumbers = findNumbersInRow(schematic, xLeft, xRight, y - 1)
adjacentNumbers.addAll(bottomNumbers)
return adjacentNumbers
}
fun findNumbersInRow(schematic: List<String>, xLeft: Int, xRight: Int, y: Int): List<Int> {
val numbers = mutableListOf<Int>()
// check if the row exists
if (y !in schematic.indices) {
return numbers
}
// check if potential middle number exists
if ((xRight - xLeft > 1) && schematic[y][xLeft + 1].isDigit()) {
numbers.add(getMiddleNumber(schematic, y, xLeft, xRight))
} else {
// check if potential left number exists
if (schematic[y][xLeft].isDigit()) {
numbers.add(getFullNumber(schematic, xLeft, y))
}
// check if potential right number exists
if (schematic[y][xRight].isDigit()) {
numbers.add(getFullNumber(schematic, xRight, y))
}
}
return numbers
}
private fun getMiddleNumber(schematic: List<String>, y: Int, xLeft: Int, xRight: Int, ) : Int {
var middleNumber = schematic[y][xLeft + 1].toString()
var dX = xRight
while (dX < schematic[y].length) {
if (schematic[y][dX].isDigit()) {
middleNumber += schematic[y][dX]
dX++
} else break
}
dX = xLeft
while (dX >= 0) {
if (schematic[y][dX].isDigit()) {
middleNumber = schematic[y][dX] + middleNumber
dX--
} else break
}
return middleNumber.toInt()
}
fun getFullNumber(schematic: List<String>, x: Int, y: Int): Int {
var number = schematic[y][x].toString()
var dX = x
while (dX + 1 < schematic[y].length) {
if (schematic[y][dX + 1].isDigit()) {
number += schematic[y][dX + 1]
dX++
} else break
}
dX = x
while (dX - 1 >= 0) {
if (schematic[y][dX - 1].isDigit()) {
number = schematic[y][dX - 1] + number
dX--
} else break
}
return number.toInt()
}
fun completeNumberAndGetLastIndex(schematic: List<String>, x: Int, y: Int): Pair<Int, Int> {
var x1 = x
var number = schematic[y][x].toString()
while (x1 + 1 < schematic[y].length) {
if (schematic[y][x1 + 1].isDigit()) {
number += schematic[y][x1 + 1]
x1++
} else break
}
return number.toInt() to x1
}
fun isValidNumber(schematic: List<String>, x: Int, y: Int): Boolean {
val xFirst = x - 1
val xLast = getNumberLastPosition(schematic[y], x) + 1
// Check if there is a symbol before the number
if ((xFirst >= 0) && isValidSymbol(schematic[y][xFirst])) {
return true
}
// Check if there is a symbol after the number
if ((xLast < schematic[y].length) && isValidSymbol(schematic[y][xLast])) {
return true
}
// Check if there is a symbol above the number
if ((y > 0) && areaContainsSymbol(schematic[y - 1], xFirst, xLast)) {
return true
}
// Check if there is a symbol below the number
if ((y + 1 < schematic.size) && areaContainsSymbol(schematic[y + 1], xFirst, xLast)) {
return true
}
return false
}
fun getNumberLastPosition(line: String, x: Int): Int {
var lastPosition = x
while (lastPosition + 1 < line.length) {
if (line[lastPosition + 1].isDigit()) {
lastPosition++
} else break
}
return lastPosition
}
fun areaContainsSymbol(line: String, xFirst: Int, xLast: Int): Boolean {
for (x in xFirst..xLast) {
if ((x in line.indices) && isValidSymbol(line[x])) {
return true
}
}
return false
}
fun isValidSymbol(symbol: Char): Boolean {
return symbol != '.'
}
data class Gear(val number1: Int, val number2: Int) {
val ratio = number1 * number2
}
fun getPuzzleInput(): List<String> {
val fileUrl = ClassLoader.getSystemResource("day3-input.txt")
return File(fileUrl.toURI()).readLines()
} | 0 | Kotlin | 0 | 1 | de51fd9222f5438efe9a2c45e5edcb88fd9f2232 | 6,905 | aoc-2023-kotlin | The Unlicense |
src/main/kotlin/dev/bogwalk/batch0/Problem8.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch0
/**
* Problem 8: Largest Product in a Series
*
* https://projecteuler.net/problem=8
*
* Goal: Find the largest product of K adjacent digits in an N-digit number.
*
* Constraints: 1 <= K <= 13, K <= N <= 1000
*
* e.g.: N = 10 with input = "3675356291", K = 5
* products LTR = {1890, 3150, 3150, 900, 1620, 540}
* largest = 3150 -> {6*7*5*3*5} or {7*5*3*5*6}
*/
class LargestProductInSeries {
/**
* SPEED (WORSE) 5.8e+05ns for N = 1000, K = 4
* SPEED (WORSE) 8.6e+05ns for N = 1000, K = 13
*/
fun largestSeriesProductRecursive(number: String, n: Int, k: Int): Long {
return when {
n == 1 -> number.toLong()
k == 1 -> number.maxOf { it.digitToInt() }.toLong()
n == k -> stringProduct(number)
else -> {
maxOf(
// first substring with k-adjacent digits
stringProduct(number.take(k)),
// original string minus the first digit
largestSeriesProductRecursive(number.drop(1), n - 1, k)
)
}
}
}
/**
* SPEED (BETTER) 2.5e+05ns for N = 1000, K = 4
* SPEED (BETTER) 2.3e+05ns for N = 1000, K = 13
*/
fun largestSeriesProduct(number: String, n: Int, k: Int): Long {
return when {
n == 1 -> number.toLong()
k == 1 -> number.maxOf { it.digitToInt() }.toLong()
n == k -> stringProduct(number)
else -> {
var largest = 0L
for (i in 0..n - k) {
largest = maxOf(largest, stringProduct(number.substring(i, i + k)))
}
largest
}
}
}
/**
* The constraints of this solution ensure that [series] will not exceed 13 characters, so
* the max product of 13 '9's would be less than Long.MAX_VALUE.
*/
fun stringProduct(series: String): Long {
return series.fold(1L) { acc, ch ->
if (ch == '0') {
return 0L // prevents further folding
} else {
acc * ch.digitToInt()
}
}
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,208 | project-euler-kotlin | MIT License |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day07/part1/day07_1.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day07.part1
import eu.janvdb.aoc2023.day07.TypeOfHand
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input07-test.txt"
const val FILENAME = "input07.txt"
fun main() {
val pairs = readLines(2023, FILENAME).map { CardBidPair.parse(it) }
val score = pairs
.sortedBy { it.hand }
.asSequence()
.mapIndexed { index, it -> (index + 1L) * it.bid }
.sum()
println(score)
}
data class CardBidPair(val hand: Hand, val bid: Int) {
companion object {
fun parse(input: String): CardBidPair {
val split = input.trim().split(" ")
return CardBidPair(Hand.parse(split[0]), split[1].toInt())
}
}
}
enum class Card(val symbol: Char) {
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
TEN('T'),
JACK('J'),
QUEEN('Q'),
KING('K'),
ACE('A');
companion object {
fun findBySymbol(symbol: Char) =
entries.find { it.symbol == symbol } ?: throw IllegalArgumentException("Unknown symbol: $symbol")
}
}
data class Hand(val cards: List<Card>) : Comparable<Hand> {
val type = calculateType()
private fun calculateType(): TypeOfHand {
val occurrences = cards.groupingBy { it }.eachCount().map { it.value }.sortedDescending()
if (occurrences[0] == 5) return TypeOfHand.FIVE_OF_A_KIND
if (occurrences[0] == 4) return TypeOfHand.FOUR_OF_A_KIND
if (occurrences[0] == 3 && occurrences[1] == 2) return TypeOfHand.FULL_HOUSE
if (occurrences[0] == 3) return TypeOfHand.THREE_OF_A_KIND
if (occurrences[0] == 2 && occurrences[1] == 2) return TypeOfHand.TWO_PAIRS
if (occurrences[0] == 2) return TypeOfHand.ONE_PAIR
return TypeOfHand.HIGH_CARD
}
override fun compareTo(other: Hand): Int {
if (type != other.type) return type.compareTo(other.type)
for (i in cards.indices) {
val thisCard = cards[i]
val otherCard = other.cards[i]
if (thisCard != otherCard) return thisCard.compareTo(otherCard)
}
return 0
}
companion object {
fun parse(input: String): Hand {
val cards = input.toCharArray().map { Card.findBySymbol(it) }
return Hand(cards)
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,090 | advent-of-code | Apache License 2.0 |
src/Day05.kt | RichardLiba | 572,867,612 | false | {"Kotlin": 16347} | fun main() {
data class Move(val count: Int, val from: Int, val to: Int)
fun readWorld(input: List<String>): Pair<MutableMap<Int, List<Char>>, MutableList<Move>> {
val world: MutableMap<Int, List<Char>> = mutableMapOf()
var worldWidth: Int = -1
val moves: MutableList<Move> = mutableListOf()
input.forEachIndexed { line, it ->
if (it.startsWith("move")) {
// parse moves
val move = it.split(" ").mapNotNull { it.toIntOrNull() }
moves.add(Move(move[0], move[1], move[2]))
} else if (it.isEmpty() || it.startsWith(" ")) {
} else {
if (worldWidth == -1) {
worldWidth = (it.length + 1) / 4
repeat(worldWidth) {
world[it] = listOf()
}
}
// parse world map
it.forEachIndexed { index, c ->
if (c == '[' || c == ']' || c.isWhitespace()) {
// do nothing
} else {
val mappedIndex = if (index == 1) 0 else index / 4
when (index) {
1, 5, 9, 13, 17, 21, 25, 29, 33 -> world[mappedIndex] = world[mappedIndex]!!.plus(c)
else -> {
println("Char $c at index $index at line $line")
throw IllegalStateException()
}
}
}
}
}
}
println(world)
return Pair(world, moves)
}
fun part1(input: List<String>): String {
val parsedInput = readWorld(input)
val world = parsedInput.first
val moves = parsedInput.second
moves.forEach { (count, from, to) ->
// println("move $count from $from to $to")
repeat(count) {
world[to - 1] = listOf(world[from - 1]!![0]).plus(world[to - 1]!!)
world[from - 1] = world[from - 1]!!.drop(1)
}
}
println(world)
return world.values.joinToString { "${it[0]}" }.replace(", ", "")
}
fun part2(input: List<String>): String {
val parsedInput = readWorld(input)
val world = parsedInput.first
val moves = parsedInput.second
moves.forEach { (count, from, to) ->
// println("move $count from $from to $to")
world[to - 1] = world[from - 1]!!.take(count).plus(world[to - 1]!!)
world[from - 1] = world[from - 1]!!.drop(count)
}
println(world)
return world.values.joinToString { "${it[0]}" }.replace(", ", "")
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6a0b6b91b5fb25b8ae9309b8e819320ac70616ed | 2,858 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day13.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | fun main() {
fun part1(input: String): Int {
return input
.split("\n\n")
.flatMap { it.lines() }
.map { it.toPacket() }
.chunked(2)
.map { Pair(it.first().list!!, it[1].list!!) }
.map { it.isRightOrder() }
.mapIndexedNotNull { index, isRightOrder ->
if (isRightOrder != false) index + 1 else null
}
.sum()
}
fun part2(input: String): Int {
val strPackets = input
.split("\n\n")
.flatMap { it.lines() }
val strPacketsWithDividers = strPackets + "[[2]]" + "[[6]]"
val orderedPackets = strPacketsWithDividers
.map { it.toPacket().list!! }
.sortedWith { left, right ->
val isRightOrder = Pair(left, right).isRightOrder()
if (isRightOrder != false) -1 else 1
}
val firstDivider = "[[2]]".toPacket().list!!
val firstDividerIndex = orderedPackets.indexOf(firstDivider) + 1
val secondDivider = "[[6]]".toPacket().list!!
val secondDividerIndex = orderedPackets.indexOf(secondDivider) + 1
return firstDividerIndex * secondDividerIndex
}
val testInput = readInputAsString("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInputAsString("Day13")
println(part1(input))
println(part2(input))
}
data class Packet(val number: Int?, val list: List<Packet>?) {
constructor(number: Int) : this(number, null)
constructor(list: List<Packet>) : this(null, list)
}
fun Pair<List<Packet>, List<Packet>>.isRightOrder(): Boolean? {
if (first.isEmpty() && second.isEmpty()) return null
if (first.isEmpty()) return true
if (second.isEmpty()) return false
for (i in first.indices) {
if (second.lastIndex < i) return false // iterating the first list and the second is already over
// handling numbers
val firstNumber = first[i].number
val secondNumber = second[i].number
if (firstNumber != null && secondNumber != null) {
if (firstNumber != secondNumber) return firstNumber < secondNumber
else continue
}
// handling lists
val firstList = first[i].list
val secondList = second[i].list
if (firstList != null && secondList != null) {
val isRightNestedOrder = Pair(firstList, secondList).isRightOrder()
if (isRightNestedOrder != null) return isRightNestedOrder
else continue
}
// handling different types
if (firstNumber != null) {
val isRightNestedOrder = Pair(listOf(Packet(firstNumber)), secondList!!).isRightOrder()
if (isRightNestedOrder != null) return isRightNestedOrder
else continue
}
val isRightNestedOrder = Pair(firstList!!, listOf(Packet(secondNumber!!))).isRightOrder()
if (isRightNestedOrder != null) return isRightNestedOrder
else continue
}
return null
}
fun String.toPacket(): Packet {
val data = mutableListOf<Packet>()
var strToEval = removeSurrounding("[", "]") // this method always takes a list
while (strToEval.isNotEmpty()) {
if (strToEval.first().isDigit()) {
val strInt = strToEval.takeWhile { it.isDigit() }
data.add(Packet(strInt.toInt()))
strToEval = strToEval.removePrefix(strInt).removePrefix(",")
} else {
var depth = -1
var indexEndOfList = -1
for ((index, c) in strToEval.withIndex()) {
if (c == ']' && depth == 0) {
indexEndOfList = index
break
}
if (c == '[') depth++
if (c == ']') depth--
}
val strList = strToEval.substring(0, indexEndOfList + 1)
data.add(strList.toPacket())
strToEval = strToEval.removePrefix(strList).removePrefix(",")
}
}
return Packet(data)
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 4,089 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinAbsoluteSumDiff.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
/**
* 1818. Minimum Absolute Sum Difference
* @see <a href="https://leetcode.com/problems/minimum-absolute-sum-difference/">Source</a>
*/
fun interface MinAbsoluteSumDiff {
operator fun invoke(nums1: IntArray, nums2: IntArray): Int
}
class MinAbsoluteSumDiffSimple : MinAbsoluteSumDiff {
override operator fun invoke(nums1: IntArray, nums2: IntArray): Int {
var res: Long = 0
var maxIdx = -1
var maxDiff = Int.MIN_VALUE
for (i in nums1.indices) {
val diff = abs(nums1[i] - nums2[i])
res = (res + diff) % MOD
if (diff > maxDiff) {
maxDiff = diff
maxIdx = i
}
}
var ded = maxDiff
for (num in nums1) {
ded = min(ded, abs(num - nums2[maxIdx]))
}
res -= (maxDiff - ded).toLong()
return res.toInt()
}
}
class MinAbsoluteSumDiffBinarySearch : MinAbsoluteSumDiff {
override operator fun invoke(nums1: IntArray, nums2: IntArray): Int {
var total = 0
var best = 0
val n = nums1.size
val diff = mutableListOf<Int>()
for (i in 0 until n) {
diff.add(abs(nums1[i] - nums2[i]))
}
nums1.sort()
for (i in 0 until n) {
val j = lowerBound(nums1, nums2[i])
val delta = diff[i] - min(
if (0 <= j - 1) abs(nums1[j - 1] - nums2[i]) else MOD,
if (j < n) abs(nums1[j] - nums2[i]) else MOD,
)
best = max(best, delta)
}
for (x in diff) {
total = (total + x) % MOD
}
return total - best
}
private fun lowerBound(a: IntArray, target: Int): Int {
val n = a.size
var i = 0
var j = n
while (i < j) {
val k = (i + j) / 2
if (a[k] < target) {
i = k + 1
} else {
j = k
}
}
return i
}
}
class MinAbsoluteSumDiffBinarySearch2 : MinAbsoluteSumDiff {
override operator fun invoke(nums1: IntArray, nums2: IntArray): Int {
val len: Int = nums1.size
var sum: Long = 0
val diffArray = IntArray(len)
for (i in 0 until len) {
val diff = abs(nums1[i] - nums2[i])
diffArray[i] = diff
sum += diff.toLong()
}
if (sum == 0L) return 0
val sortedNums1: IntArray = nums1.copyOf(len).sorted().toIntArray()
var minSum = sum
for (i in 0 until len) {
var left = 0
var right = len - 1
while (left <= right) {
val mid = left + (right - left) / 2
val diff = abs(sortedNums1[mid] - nums2[i])
val newSum = sum - diffArray[i] + diff
if (newSum < minSum) minSum = newSum
if (nums2[i] < sortedNums1[mid]) right = mid - 1 else left = mid + 1
}
}
return (minSum % MOD).toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,757 | kotlab | Apache License 2.0 |
src/Day09.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val moves = parseInput(input)
val head = Knot()
var tail = Knot()
val positions = mutableSetOf(tail)
moves.forEach { move ->
head.move(move)
tail = head.nextPosition(tail).also { positions += it }
}
return positions.size
}
private fun part2(input: List<String>): Int {
val moves = parseInput(input)
val knots = MutableList(10) { Knot() }
val positions = mutableSetOf(knots.last())
moves.forEach { move ->
knots.first().move(move)
(0 until knots.lastIndex).forEach {
knots[it + 1] = knots[it].nextPosition(knots[it + 1])
}
positions += knots.last()
}
return positions.size
}
private fun parseInput(input: List<String>): List<Pair<Int, Int>> {
return input.flatMap {
val (direction, amount) = it.split(" ")
val move = when (direction) {
"U" -> 0 to 1
"D" -> 0 to -1
"L" -> -1 to 0
else -> 1 to 0
}
(0 until amount.toInt()).map { move }
}
}
private data class Knot(var x: Int = 0, var y: Int = 0) {
private fun isTouching(other: Knot): Boolean = abs(x - other.x) <= 1 && abs(y - other.y) <= 1
fun move(move: Pair<Int, Int>) {
x += move.first
y += move.second
}
fun nextPosition(other: Knot): Knot = when {
isTouching(other) -> other
else -> {
val xOffset = (x - other.x).sign
val yOffset = (y - other.y).sign
other.copy(x = other.x + xOffset, y = other.y + yOffset)
}
}
} | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 1,958 | aoc-22 | Apache License 2.0 |
src/Day05.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | import java.util.*
class Cargo(val moves: Array<Array<Int>>) {
private var stacks = mutableMapOf<Int, Stack<String>>()
fun putCrate(at: Int, label: String) {
if (!stacks.containsKey(at)) {
stacks[at] = Stack<String>()
}
stacks[at]!!.push(label)
}
fun moveCrate(amount: Int, from: Int, to: Int) {
val fromStack = stacks[from]!!
val toStack = stacks[to]!!
for (i in 1..amount) {
val topCrate = fromStack.pop()
toStack.push(topCrate)
}
}
fun moveCrateInTheSameOrder(amount: Int, from: Int, to: Int) {
val fromStack = stacks[from]!!
val toStack = stacks[to]!!
val tmpStack = Stack<String>();
for (i in 1..amount) {
val topCrate = fromStack.pop()
tmpStack.push(topCrate)
}
for (i in 1..amount) {
val topCrate = tmpStack.pop()
toStack.push(topCrate)
}
}
fun topCrates(): List<String> {
val keys = stacks.keys.sorted().toIntArray()
return keys.map { stacks[it]!!.peek() }
}
}
fun main() {
fun parseInput(input: List<String>): Cargo {
var stackLines = arrayOf<Array<String>>()
var moves = arrayOf<Array<Int>>()
for (line in input) {
if (line.isEmpty()) {
continue
}
if (line.substring(0, 4) == "move") {
val splits = line.split(" ")
moves += arrayOf(splits[1].toInt(), splits[3].toInt(), splits[5].toInt())
continue
}
if (line.contains("[")) {
val length = line.length
var stackLine = arrayOf<String>()
for (i in 1 until length step 4) {
stackLine += line[i].toString()
}
stackLines += stackLine
continue
}
}
val cargo = Cargo(moves)
for (stackLine in stackLines.reversed()) {
for (i in stackLine.indices) {
val label = stackLine[i]
if (label == " ") {
continue
}
cargo.putCrate(i + 1, label)
}
}
return cargo
}
fun part1(input: List<String>): String {
val cargo = parseInput(input)
for (move in cargo.moves) {
cargo.moveCrate(move[0], move[1], move[2])
}
return cargo.topCrates().joinToString("")
}
fun part2(input: List<String>): String {
val cargo = parseInput(input)
for (move in cargo.moves) {
cargo.moveCrateInTheSameOrder(move[0], move[1], move[2])
}
return cargo.topCrates().joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day05_sample")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readTestInput("Day05")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 3,127 | advent-of-code-2022 | Apache License 2.0 |
src/day03/Day03.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day03
import readInput
import kotlin.math.ceil
fun main() {
fun charPriority(char: Char): Int {
return when (char.code) {
in 97..122 -> {
char.code - 96 // a - z
}
in 65..90 -> {
char.code - 38 // A - Z
}
else -> 0
}
}
fun groupPriority(input: List<Set<Char>>): Int {
val first = input[0]
val withoutFirst = input.subList(1, input.size)
val shared = withoutFirst.fold(first) { acc, set ->
acc.intersect(set)
}
return charPriority(shared.first())
}
fun rowPriority(input: String): Int {
val halfSize = ceil(input.length.toFloat() / 2).toInt()
return groupPriority(input.chunked(halfSize).map { it.toSet() })
}
fun part1(input: List<String>): Int {
return input.sumOf {
rowPriority(it)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { chunk ->
groupPriority(chunk.map { it.toSet() })
}
}
val testInput = readInput("Day03_test")
val input = readInput("Day03")
println("Part 1 [Test] : ${part1(testInput)}")
check(part1(testInput) == 157)
println("Part 1 [Real] : ${part1(input)}")
println("Part 2 [Test] : ${part2(testInput)}")
check(part2(testInput) == 70)
println("Part 2 [Real] : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 1,449 | advent-of-code-2022 | Apache License 2.0 |
src/Day17.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
val input = readInput("Day17")
val (n,m) = input.size to input[0].length
val dirs = listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0) // east south west north
fun solve(minSteps: Int, maxSteps: Int): Int {
val loss = Array(n) {
Array(m) {
IntArray(4) { -1 }
}
}
val queue = ArrayDeque<Triple<Int,Int,Int>>()
fun addQ(i: Int, j: Int, d1: Int, h: Int) {
val d = d1 % 4
if (i in input.indices && j in input[i].indices) {
val l = loss[i][j][d]
if (l < 0 || l > h) {
loss[i][j][d] = h
queue.add(Triple(i,j,d))
}
}
}
addQ(0,0,0,0)
addQ(0,0,1,0)
while (queue.isNotEmpty()) {
val (i,j,d) = queue.removeFirst()
var h = loss[i][j][d]
for (k in 1 until minSteps) {
val (i1,j1) = i + k*dirs[d].first to j + k*dirs[d].second
if (i1 !in input.indices || j1 !in input[i1].indices) break
h += (input[i1][j1] - '0')
}
for (k in minSteps .. maxSteps) {
val (i1,j1) = i + k*dirs[d].first to j + k*dirs[d].second
if (i1 !in input.indices || j1 !in input[i1].indices) break
h += (input[i1][j1] - '0')
addQ(i1, j1, d + 1, h)
addQ(i1, j1, d + 3, h)
}
}
return loss[n-1][m-1].filter { it >= 0}.min()
}
println(solve(1, 3))
println(solve(4, 10))
} | 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,598 | advent-of-code-kotlin | Apache License 2.0 |
src/Day02.kt | rounakdatta | 540,743,612 | false | {"Kotlin": 19962} | sealed class SubmarineInstruction {
// TODO: understand what default constructor of sealed classes mean
data class Forward(val numberOfUnits: Int) : SubmarineInstruction()
data class Down(val numberOfUnits: Int) : SubmarineInstruction()
data class Up(val numberOfUnits: Int) : SubmarineInstruction()
companion object ParsedInstruction {
fun parseInstruction(rawInstruction: String): SubmarineInstruction {
rawInstruction.split(" ")
.let { Pair(it[0], it[1].toInt()) }
.let {
return when (it.first) {
"forward" -> Forward(it.second)
"down" -> Down(it.second)
"up" -> Up(it.second)
else -> throw IllegalArgumentException()
}
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it -> SubmarineInstruction.parseInstruction(it) }
// Pair - first is horizontalPosition, second is depthPosition
.fold(Pair(0, 0)) { positionPair, instruction ->
when (instruction) {
is SubmarineInstruction.Forward -> Pair(
positionPair.first + instruction.numberOfUnits,
positionPair.second
)
// reverse operation, cuz "sub"marine
is SubmarineInstruction.Down -> Pair(
positionPair.first,
positionPair.second + instruction.numberOfUnits
)
is SubmarineInstruction.Up -> Pair(
positionPair.first,
positionPair.second - instruction.numberOfUnits
)
}
}
// of course there's a better way to multiply the two elements of a pair ;)
.toList()
.fold(1) { productSoFar, n ->
productSoFar * n
}
}
fun part2(input: List<String>): Int {
return -input
.map { it -> SubmarineInstruction.parseInstruction((it)) }
// Triple - first is horizontalPosition, second is depthPosition, third is aim
.fold(Triple(0, 0, 0)) { submarineTriple, instruction ->
when (instruction) {
is SubmarineInstruction.Down -> Triple(
submarineTriple.first,
submarineTriple.second,
submarineTriple.third - instruction.numberOfUnits
)
is SubmarineInstruction.Up -> Triple(
submarineTriple.first,
submarineTriple.second,
submarineTriple.third + instruction.numberOfUnits
)
is SubmarineInstruction.Forward -> Triple(
submarineTriple.first + instruction.numberOfUnits,
submarineTriple.second + submarineTriple.third * instruction.numberOfUnits,
submarineTriple.third
)
}
}
.let {
it.first * it.second
}
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 130d340aa4c6824b7192d533df68fc7e15e7e910 | 3,412 | aoc-2021 | Apache License 2.0 |
year2018/src/main/kotlin/net/olegg/aoc/year2018/day18/Day18.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2018.day18
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_8
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2018.DayOf2018
/**
* See [Year 2018, Day 18](https://adventofcode.com/2018/day/18)
*/
object Day18 : DayOf2018(18) {
override fun first(): Any? {
return solve(10)
}
override fun second(): Any? {
return solve(1000000000)
}
private fun solve(minutes: Int): Int {
val map = matrix
val cache = mutableMapOf(map.joinToString(separator = "") { it.joinToString(separator = "") } to 0)
val after = (1..minutes).fold(map) { acc, round ->
val curr = acc.mapIndexed { y, row ->
row.mapIndexed { x, c ->
val pos = Vector2D(x, y)
val adjacent = NEXT_8
.map { pos + it.step }
.mapNotNull { acc[it] }
when (c) {
'.' -> if (adjacent.count { it == '|' } >= 3) '|' else '.'
'|' -> if (adjacent.count { it == '#' } >= 3) '#' else '|'
'#' -> if (adjacent.contains('#') and adjacent.contains('|')) '#' else '.'
else -> c
}
}
}
val footprint = curr.joinToString(separator = "") { it.joinToString(separator = "") }
cache[footprint]?.let { head ->
val cycle = round - head
val tail = (minutes - head) % cycle
val target = head + tail
val final = cache
.filterValues { it == target }
.keys
.first()
return final.count { it == '#' } * final.count { it == '|' }
}
cache[footprint] = round
return@fold curr
}
return after.sumOf { row -> row.count { it == '#' } } * after.sumOf { row -> row.count { it == '|' } }
}
}
fun main() = SomeDay.mainify(Day18)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,836 | adventofcode | MIT License |
src/Day05.kt | zdenekobornik | 572,882,216 | false | null |
fun main() {
fun getStacksFromSupplies(suppliesString: String): Array<ArrayDeque<Char>> {
val supplies = suppliesString.lines()
.map { it.chunked(4).map { it.filterNot { it == '[' || it == ']' }.trim() } }.dropLast(1)
val columns = supplies.first().size
val stacks = Array<ArrayDeque<Char>>(columns) { ArrayDeque() }
for (row in supplies) {
for (column in row.indices) {
if (row[column].isBlank()) {
continue
}
stacks[column].add(row[column].first())
}
}
return stacks
}
fun part1(input: String): String {
val (suppliesRaw, movesRaw) = input.split("\n\n")
val moves = movesRaw.lines()
val stacks = getStacksFromSupplies(suppliesRaw)
for (move in moves) {
val (num, srcStack, destStack) = move.split(' ').map { it.trim().toIntOrNull() }.filterNotNull()
repeat(num) {
stacks[destStack - 1].addFirst(stacks[srcStack - 1].removeFirst())
}
}
return stacks.map { it.first() }.joinToString(separator = "")
}
fun part2(input: String): String {
val (suppliesRaw, movesRaw) = input.split("\n\n")
val moves = movesRaw.lines()
val stacks = getStacksFromSupplies(suppliesRaw)
for (move in moves) {
val (num, srcStack, destStack) = move.split(' ').map { it.trim().toIntOrNull() }.filterNotNull()
for (step in 0 until num) {
stacks[destStack - 1].add(step, stacks[srcStack - 1].removeFirst())
}
}
return stacks.map { it.first() }.joinToString(separator = "")
}
// test if implementation meets criteria from the description, like:
val testInput = readInputRaw("Day05_test")
checkResult(part1(testInput), "CMZ")
checkResult(part2(testInput), "MCD")
val input = readInputRaw("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f73e4a32802fa43b90c9d687d3c3247bf089e0e5 | 2,033 | advent-of-code-2022 | Apache License 2.0 |
src/year2023/day10/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day10
import year2023.solveIt
fun main() {
val day = "10"
val expectedTest1 = 8L
val expectedTest2 = 1L
data class Position(val x:Int, val y:Int)
val moveMap = mapOf(
"|01" to (0 to 1),"|0-1" to (0 to -1),
"-10" to (1 to 0),"--10" to (-1 to 0),
"J10" to (0 to -1),"J01" to (-1 to 0),
"710" to (0 to 1),"70-1" to (-1 to 0),
"L-10" to (0 to -1),"L01" to (1 to 0),
"F-10" to (0 to 1),"F0-1" to (1 to 0),
)
fun navigate(input: List<String>, previous: Position, current: Position): Position? {
val dx = current.x - previous.x
val dy = current.y - previous.y
val c = input[current.y][current.x]
val move = "$c$dx$dy"
return moveMap[move]?.let { Position(current.x + it.first, current.y + it.second) }
?.takeIf { it.x in input[0].indices && it.y in input.indices }
}
fun getLoop(input: List<String>): Set<Position> {
val start = input.flatMapIndexed { line, s -> s.mapIndexed { col, c -> c to Position(col, line) }.filter { it.first == 'S' } }.first().second
val possibleConnections =
listOf(
Position(start.x - 1, start.y),
Position(start.x + 1, start.y),
Position(start.x, start.y - 1),
Position(start.x, start.y + 1)
).filter { it.x in input[0].indices && it.y in input.indices }
val firstNotNullOf = possibleConnections.firstNotNullOf { n ->
var loop = setOf(start, n)
var count = 1
var previous = start
var current = n
while (true) {
val next = navigate(input, previous, current) ?: break
loop = loop + next
previous = current
current = next
count++
}
if (current == start) {
println("cycle $count $current")
loop
} else {
println("deadend $count $current")
null
}
}
return firstNotNullOf
}
fun part1(input: List<String>): Long {
val loop = getLoop(input)
return loop.size/2L
}
fun part2(input: List<String>): Long {
val loop = getLoop(input)
val a = setOf('|','L','J')
var count = 0L
for (y in input.indices){
var inside = false;
for (x in input[y].indices) {
val curr = input[y][x]
if (loop.contains(Position(x, y))){
if (a.contains(curr)) {
inside = !inside;
}
}
else if (inside){
count++
}
}
}
return count
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,923 | adventOfCode | Apache License 2.0 |
src/main/kotlin/Day05.kt | alex859 | 573,174,372 | false | {"Kotlin": 80552} | fun main() {
val testInput = readInput("Day05_test.txt")
check(testInput.moveCrates() == "CMZ")
check(testInput.moveCratesFancy() == "MCD")
val input = readInput("Day05.txt")
println(input.moveCrates())
println(input.moveCratesFancy())
}
internal fun String.moveCrates(): String {
val stacks = readStacks()
val instructions = readInstructions()
return stacks.apply(instructions).top()
}
internal fun String.moveCratesFancy(): String {
val stacks = readStacks()
val instructions = readInstructions()
return stacks.applyFancy(instructions).top()
}
internal fun Map<Int, List<String>>.top() =
toSortedMap().values.joinToString(separator = "") { it.first() }
internal fun Map<Int, List<String>>.apply(instruction: Instruction): Map<Int, List<String>> {
val mutable = this.toMutableMap()
val from = this[instruction.from] ?: error("unable to find stack ${instruction.from}")
val to = this[instruction.to] ?: error("unable to find stack ${instruction.from}")
val (updatedFrom, updatedTo) = moveElements(instruction.count, source = from, destination = to)
mutable += instruction.from to updatedFrom
mutable += instruction.to to updatedTo
return mutable
}
internal fun Map<Int, List<String>>.applyFancy(instruction: Instruction): Map<Int, List<String>> {
val mutable = this.toMutableMap()
val from = this[instruction.from] ?: error("unable to find stack ${instruction.from}")
val to = this[instruction.to] ?: error("unable to find stack ${instruction.from}")
val (updatedFrom, updatedTo) = moveElementsFancy(instruction.count, source = from, destination = to)
mutable += instruction.from to updatedFrom
mutable += instruction.to to updatedTo
return mutable
}
private fun moveElements(count: Int, source: List<String>, destination: List<String>): Pair<List<String>, List<String>> {
val mutableSource = source.toMutableList()
val mutableDestination = destination.toMutableList()
repeat(count) {
val element = mutableSource.removeAt(0)
mutableDestination.add(0, element)
}
return mutableSource.toList() to (mutableDestination.toList())
}
private fun moveElementsFancy(count: Int, source: List<String>, destination: List<String>): Pair<List<String>, List<String>> {
val cratesToMove = source.take(count)
return source.drop(count) to (cratesToMove + destination)
}
internal fun Map<Int, List<String>>.apply(instructions: List<Instruction>): Map<Int, List<String>> {
return instructions.fold(this) { current, instructions -> current.apply(instructions) }
}
internal fun Map<Int, List<String>>.applyFancy(instructions: List<Instruction>): Map<Int, List<String>> {
return instructions.fold(this) { current, instructions -> current.applyFancy(instructions) }
}
internal fun String.readInstructions(): List<Instruction> {
val (_, instructions) = split("\n\n")
return instructions.lines().map { it.readInstruction() }
}
internal fun String.readInstruction(): Instruction {
val regex = "move (\\d+?) from (\\d+?) to (\\d+?)".toRegex()
val (count, from, to) = regex.find(this)?.destructured ?: error("unable to read instruction $this")
return Instruction(from = from.toInt(), to = to.toInt(), count = count.toInt())
}
internal fun String.readRow(): List<String?> {
return this.chunked(4).map {
if (it.contains("[")) {
it.replace("[", "").replace("]", "").trim()
} else {
null
}
}
}
internal fun String.readStacks(): Map<Int, List<String>> {
val (stacks, _) = split("\n\n")
val lines = stacks.lines()
val result = mutableMapOf<Int, MutableList<String>>()
lines.exceptLast().forEach {
it.readRow().mapIndexed { i, element ->
val current = result.computeIfAbsent(i + 1) { mutableListOf() }
if (element != null) {
current += element
}
}
}
return result
}
private fun List<String>.exceptLast() = subList(0, size - 1)
data class Instruction(
val from: Int,
val to: Int,
val count: Int
) | 0 | Kotlin | 0 | 0 | fbbd1543b5c5d57885e620ede296b9103477f61d | 4,126 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day7/Solution.kt | krazyglitch | 573,086,664 | false | {"Kotlin": 31494} | package day7
import util.Utils
import java.time.Duration
import java.time.LocalDateTime
class Solution {
enum class FileType {
FOLDER, FILE
}
class File(input: String, val parent: File?) {
val fileType: FileType
val fileName: String
val fileSize: Int
val children = HashMap<String, File>()
init {
if (folderRegex.matches(input)) {
fileType = FileType.FOLDER
val match = folderRegex.find(input)
fileName = match?.groupValues!![1]
fileSize = 0
} else {
fileType = FileType.FILE
val match = fileRegex.find(input)
fileName = match?.groupValues!![2]
fileSize = match.groupValues[1].toInt()
}
}
fun getSize(): Int {
return when (fileType) {
FileType.FOLDER -> children.values.sumOf { c -> c.getSize() }
FileType.FILE -> fileSize
}
}
fun flatten(): List<File> {
val flatList = ArrayList<File>()
flatList.add(this)
children.values.filter { c -> c.fileType == FileType.FOLDER }.forEach { f ->
flatList.addAll(f.flatten())
}
return flatList
}
}
companion object {
val fileRegex = Regex("^(\\d+) ([\\w.]+)$")
val folderRegex = Regex("^dir (\\\\|\\w+)$")
}
private fun parseCommands(root: File, data: List<String>) {
var listing = false
val changeDirRegex = Regex("^\\$ cd (..|\\w+)$")
var pwd = root
var level = 0
var count = 0
data.forEach { cmd ->
val isCommand = cmd[0] == '$'
if (isCommand) listing = false
count++
if (listing) {
val newFile = File(cmd, pwd)
pwd.children[newFile.fileName] = newFile
} else if (isCommand) {
if (changeDirRegex.matches(cmd)) {
val match = changeDirRegex.find(cmd)
if (match != null) {
if (match.groupValues[1] == "..") {
pwd = pwd.parent!!
level--
} else {
pwd = pwd.children[match.groupValues[1]]!!
level++
}
}
} else {
listing = true
}
}
}
}
fun part1(data: List<String>): Int {
val root = File("dir \\", null)
parseCommands(root, data.subList(1, data.size))
return root.flatten().map { f -> f.getSize() }.filter { fs -> fs <= 100000 }.sum()
}
fun part2(data: List<String>): Int {
val root = File("dir \\", null)
parseCommands(root, data.subList(1, data.size))
val fullSize = 70000000
val requiredSize = 30000000
val unusedSize = fullSize - root.getSize()
val missingSize = requiredSize - unusedSize
return root.flatten().map { f -> f.getSize() }.sorted().first { fs -> fs >= missingSize }
}
}
fun main() {
val runner = Solution()
val input = Utils.readLines(runner, "input.txt", runner.javaClass.packageName)
println("Solving first part of day 7")
var start = LocalDateTime.now()
println("The sum directories below 100k is: ${input?.let { runner.part1(it) }}")
var end = LocalDateTime.now()
println("Solved first part of day 7")
var milliseconds = Duration.between(start, end).toMillis()
println("Took $milliseconds ms to solve first part of day 7")
println()
println("Solving second part of day 7")
start = LocalDateTime.now()
println("The smallest directory that can be deleted is: ${input?.let { runner.part2(it) }}")
end = LocalDateTime.now()
println("Solved second part of day 7")
milliseconds = Duration.between(start, end).toMillis()
println("Took $milliseconds ms to solve second part of day 7")
} | 0 | Kotlin | 0 | 0 | db6b25f7668532f24d2737bc680feffc71342491 | 4,124 | advent-of-code2022 | MIT License |
src/main/kotlin/year2022/Day19.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
class Day19 {
data class Blueprint(
val id: Int,
val oreRobotOreCost: Int,
val clayRobotOreCost: Int,
val obsidianRobotOreCost: Int,
val obsidianRobotClayCost: Int,
val geodeRobotOreCost: Int,
val geodeRobotObsidianCost: Int
) {
val maxOreCost = maxOf(oreRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost, clayRobotOreCost)
}
data class State(
val blueprint: Blueprint,
val stepsLeft: Int,
val ore: Int,
val clay: Int,
val obsidian: Int,
val geode: Int,
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int
) {
val isConsistent
get() = stepsLeft > 0 && ore >= 0 && clay >= 0 && obsidian >= 0
fun canBuyOreRobot() = ore >= blueprint.oreRobotOreCost
fun canBuyClayRobot() = ore >= blueprint.clayRobotOreCost
fun canBuyObsidianRobot() =
ore >= blueprint.obsidianRobotOreCost && clay >= blueprint.obsidianRobotClayCost
fun canBuyGeodeRobot() =
ore >= blueprint.geodeRobotOreCost && obsidian >= blueprint.geodeRobotObsidianCost
fun sameNumberOfRobots(other: State) = oreRobots == other.oreRobots
&& clayRobots == other.clayRobots
&& obsidianRobots == other.obsidianRobots
&& geodeRobots == other.geodeRobots
fun buyGeodeRobot() = copy(
ore = ore - blueprint.geodeRobotOreCost,
obsidian = obsidian - blueprint.geodeRobotObsidianCost,
geodeRobots = geodeRobots + 1
)
fun buyOreRobot() = copy(
ore = ore - blueprint.oreRobotOreCost,
oreRobots = oreRobots + 1,
)
fun buyClayRobot() = copy(
ore = ore - blueprint.clayRobotOreCost,
clayRobots = clayRobots + 1,
)
fun buyObsidianRobot() = copy(
ore = ore - blueprint.obsidianRobotOreCost,
clay = clay - blueprint.obsidianRobotClayCost,
obsidianRobots = obsidianRobots + 1,
)
fun increaseStep(prevState: State) = copy(
stepsLeft = stepsLeft - 1,
ore = ore + prevState.oreRobots,
clay = clay + prevState.clayRobots,
obsidian = obsidian + prevState.obsidianRobots,
geode = geode + prevState.geodeRobots
)
}
private val regex =
"""Blueprint (\d*): Each ore robot costs (\d*) ore. Each clay robot costs (\d*) ore. Each obsidian robot costs (\d*) ore and (\d*) clay. Each geode robot costs (\d*) ore and (\d*) obsidian.""".toRegex()
private fun solution(input: List<String>, steps: Int) = input.map(regex::find)
.map { result -> result!!.groupValues.drop(1).map(String::toInt) }
.map { list -> Blueprint(list[0], list[1], list[2], list[3], list[4], list[5], list[6]) }
.map { blueprint -> solution(null, State(blueprint, steps, 0, 0, 0, 0, 1, 0, 0, 0)) }
private fun solution(prevState: State?, state: State): Int {
if (state.stepsLeft == 0) {
return state.geode
}
return buildList {
if (state.canBuyGeodeRobot()) {
add(state.buyGeodeRobot())
} else {
add(state)
if (!(prevState?.canBuyOreRobot() == true && prevState.sameNumberOfRobots(state))
&& state.oreRobots < state.blueprint.maxOreCost
) {
add(state.buyOreRobot())
}
if (!(prevState?.canBuyClayRobot() == true && prevState.sameNumberOfRobots(state))
&& state.clayRobots < state.blueprint.obsidianRobotClayCost
) {
add(state.buyClayRobot())
}
if (!(prevState?.canBuyObsidianRobot() == true && prevState.sameNumberOfRobots(state))
&& state.obsidianRobots < state.blueprint.geodeRobotObsidianCost
) {
add(state.buyObsidianRobot())
}
}
}.filter { it.isConsistent }
.map { it.increaseStep(state) }
.maxOf { solution(state, it) }
}
fun part1(input: String) = solution(input.lines(), 24).reduceIndexed { idx, acc, value -> acc + (idx + 1) * value }
fun part2(input: String) = solution(input.lines().take(3), 32).reduce(Int::times)
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 4,502 | aoc-2022 | Apache License 2.0 |
src/day12/Day12.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day12
import readInput
import java.util.LinkedList
import java.util.Queue
fun main() {
data class RowCol(
val row: Int,
val col: Int
)
var destP: RowCol? = null
val sourceDestinations = mutableListOf<RowCol>()
fun List<String>.initMatrix(matrix: Array<CharArray>, part1: Boolean) {
val rowSize = size
val colSize = this[0].length
for (row in 0 until rowSize) {
for (col in 0 until colSize) {
matrix[row][col] = this[row][col]
if (matrix[row][col] == 'S') sourceDestinations.add(RowCol(row, col))
if (matrix[row][col] == 'a' && !part1) sourceDestinations.add(RowCol(row, col))
if (matrix[row][col] == 'E') destP = RowCol(row, col)
}
}
}
fun findShortestPath(srcDest: RowCol, grid: Array<CharArray>): Int {
val rowInbound = grid.indices
val colInbound = 0 until grid[0].size
val queue: Queue<Pair<RowCol, Int>> = LinkedList()
queue.add(Pair(srcDest, 0))
val visited = hashSetOf<RowCol>()
visited.add(srcDest)
while (queue.isNotEmpty()) {
val (nodeP, distance) = queue.remove()
if (nodeP == destP) return distance
var currentElevation = grid[nodeP.row][nodeP.col]
if (currentElevation == 'S') currentElevation = 'a'
fun visitNeighbour(currentPosition:RowCol){
if (currentPosition.row !in rowInbound || currentPosition.col !in colInbound) return
var nextElevation = grid[currentPosition.row][currentPosition.col]
if (nextElevation == 'E') nextElevation = 'z'
if (
currentElevation + 1 == nextElevation ||
currentElevation >= nextElevation
) {
if (!visited.contains(currentPosition)) {
visited.add(currentPosition)
queue.add(Pair(currentPosition, distance + 1))
}
}
}
visitNeighbour(RowCol(nodeP.row - 1, nodeP.col))
visitNeighbour(RowCol(nodeP.row + 1, nodeP.col))
visitNeighbour(RowCol(nodeP.row, nodeP.col - 1))
visitNeighbour(RowCol(nodeP.row, nodeP.col + 1))
}
return -1
}
fun part1(input: List<String>): Int {
val rowSize = input.size
val colSize = input[0].length
sourceDestinations.clear()
val grid = Array(rowSize) { CharArray(colSize) }
input.initMatrix(grid, true)
return findShortestPath(sourceDestinations[0], grid)
}
fun part2(input: List<String>): Int {
val rowSize = input.size
val colSize = input[0].length
sourceDestinations.clear()
val grid = Array(rowSize) { CharArray(colSize) }
input.initMatrix(grid, false)
var shortPath = Int.MAX_VALUE
sourceDestinations.forEach {
val result = findShortestPath(it, grid)
if (result < shortPath && result != -1) shortPath = result
}
return shortPath
}
val input = readInput("/day12/Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 3,276 | aoc-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/com/github/akowal/aoc/Day05.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
class Day05 {
fun solvePart1(): String {
val (stacks, moves) = loadData()
moves.forEach { m ->
val from = stacks[m.from]
val to = stacks[m.to]
repeat(m.qty) {
to.add(from.removeLast())
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
fun solvePart2(): String {
val (stacks, moves) = loadData()
moves.forEach { m ->
val from = stacks[m.from]
val to = stacks[m.to]
val buf = mutableListOf<Char>()
repeat(m.qty) {
buf += from.removeLast()
}
buf.reversed().forEach {
to.add(it)
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
private fun loadData(): Data {
val stackStr = mutableListOf<String>()
val moveStr = mutableListOf<String>()
inputFile("day05").readLines().let { lines ->
stackStr += lines.takeWhile { it.isNotEmpty() }.toList()
stackStr.removeLast()
moveStr += lines.drop(stackStr.size + 2)
}
val numOfStacks = stackStr.last().split(' ').size
val stacks = Array(numOfStacks) { ArrayDeque<Char>() }
repeat(numOfStacks) { i ->
val x = i * 4 + 1
var y = stackStr.lastIndex
while (y >= 0 && x < stackStr[y].length && stackStr[y][x] != ' ') {
stacks[i].add(stackStr[y][x])
y--
}
}
val moves = moveStr.map {
val arr = it.split(' ')
Move(
qty = arr[1].toInt(),
from = arr[3].toInt() - 1,
to = arr[5].toInt() - 1,
)
}
return Data(stacks, moves)
}
private data class Data(
val stacks: Array<ArrayDeque<Char>>,
val moves: List<Move>,
)
private data class Move(
val qty: Int,
val from: Int,
val to: Int,
)
}
fun main() {
val solution = Day05()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 2,206 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/g2001_2100/s2002_maximum_product_of_the_length_of_two_palindromic_subsequences/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2002_maximum_product_of_the_length_of_two_palindromic_subsequences
// #Medium #String #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask
// #2023_06_23_Time_389_ms_(100.00%)_Space_43.3_MB_(100.00%)
class Solution {
fun maxProduct(s: String): Int {
if (s.length == 2) {
return 1
}
val list: MutableList<State> = ArrayList()
val chars = s.toCharArray()
val visited: MutableSet<State> = HashSet()
for (i in chars.indices) {
val mask = 1 shl i
recur(chars, State(i, i, 0, mask), list, visited)
recur(chars, State(i, i + 1, 0, mask), list, visited)
}
list.sortWith { a: State, b: State -> b.cnt - a.cnt }
var res = 1
val explored: MutableSet<Int> = HashSet()
for (i in 0 until list.size - 1) {
if (explored.contains(i)) {
continue
}
val cur = list[i]
if (cur.cnt == 1) {
break
}
for (j in i + 1 until list.size) {
val cand = list[j]
if (cur.mask and cand.mask < 1) {
if (explored.add(j)) {
res = res.coerceAtLeast(cur.cnt * cand.cnt)
}
break
}
}
}
return res
}
private fun recur(chars: CharArray, s: State, list: MutableList<State>, visited: MutableSet<State>) {
if (s.i < 0 || s.j >= chars.size) {
return
}
if (!visited.add(s)) {
return
}
if (chars[s.i] == chars[s.j]) {
val m = s.mask or (1 shl s.i) or (1 shl s.j)
val nextCnt = s.cnt + if (s.i < s.j) 2 else 1
list.add(State(s.i, s.j, nextCnt, m))
recur(chars, State(s.i - 1, s.j + 1, nextCnt, m), list, visited)
}
recur(chars, State(s.i - 1, s.j, s.cnt, s.mask), list, visited)
recur(chars, State(s.i, s.j + 1, s.cnt, s.mask), list, visited)
}
private class State(var i: Int, var j: Int, var cnt: Int, var mask: Int) {
override fun equals(other: Any?): Boolean {
if (other == null || other.javaClass != this.javaClass) {
return false
}
val s = other as State
return i == s.i && j == s.j && mask == s.mask
}
override fun hashCode(): Int {
return (i * 31 + j) * 31 + mask
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,529 | LeetCode-in-Kotlin | MIT License |
src/day21/Day21.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day21
import readInput
import java.util.*
enum class Operator {
PLUS,
MINUS,
DIVIDE,
MUL
}
data class Node(
val name: String,
var value: Long? = null,
var operator: Operator? = null,
var left: Node? = null,
var right: Node? = null
) {
override fun toString(): String {
return "name -> $name value -> $value"
}
}
class MonkeyExpressionTree {
private var root: Node? = null
private fun operator(op: String): Operator {
return when (op) {
"+" -> Operator.PLUS
"-" -> Operator.MINUS
"*" -> Operator.MUL
"/" -> Operator.DIVIDE
else -> throw IllegalStateException()
}
}
private fun buildTree(inputMap: Map<String, String>) {
root = Node(name = "root")
val stack = Stack<Node>()
stack.push(root)
while (stack.isNotEmpty()) {
val current = stack.pop()
val value = inputMap[current.name]!!
when {
value.toIntOrNull() != null -> current.value = value.toLong()
else -> {
val (operand1, operator, operand2) = value.split(" ").map { it.trim() }
current.left = Node(name = operand1)
current.right = Node(name = operand2)
current.operator = operator(operator)
stack.push(current.left)
stack.push(current.right)
}
}
}
}
fun evaluateMonkeyTree(): Long {
fun eval(node: Node): Long {
if (node.value != null) return node.value!!
return when (node.operator) {
Operator.MUL -> eval(node.left!!) * eval(node.right!!)
Operator.DIVIDE -> eval(node.left!!) / eval(node.right!!)
Operator.PLUS -> eval(node.left!!) + eval(node.right!!)
Operator.MINUS -> eval(node.left!!) - eval(node.right!!)
else -> throw UnsupportedOperationException()
}
}
return eval(root!!)
}
fun whatHumanNeedToYell():String {
fun eval(node: Node): String {
if (node.value != null) {
if (node.name == "humn") return "X"
return node.value.toString()
}
return when (node.operator) {
Operator.MUL -> "(".plus(eval(node.left!!).plus("*").plus(eval(node.right!!))).plus(")")
Operator.DIVIDE -> "(".plus(eval(node.left!!).plus("/").plus(eval(node.right!!))).plus(")")
Operator.PLUS -> "(".plus(eval(node.left!!).plus("+").plus(eval(node.right!!))).plus(")")
Operator.MINUS -> "(".plus(eval(node.left!!).plus("-").plus(eval(node.right!!))).plus(")")
else -> throw UnsupportedOperationException()
}
}
return (eval(root!!.left!!).plus("=").plus(eval(root!!.right!!)))
}
fun buildParseTree(input: List<String>) {
val inputMap: Map<String, String> = input.map {
it.split(":").map { it.trim() }
}.associate { it.first() to it.last() }
buildTree(inputMap)
}
}
fun main() {
fun solve1(input: List<String>): Long {
return with(MonkeyExpressionTree()) {
buildParseTree(input)
evaluateMonkeyTree()
}
}
fun solve2(input: List<String>):String {
val equation = with(MonkeyExpressionTree()) {
buildParseTree(input)
whatHumanNeedToYell()
}
// I cheated for part 2, I get the equation and put it in https://www.mathpapa.com/equation-solver/
// TODO -> Solve it programatically
return equation
}
val input = readInput("/day21/Day21")
println(solve1(input))
println(solve2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 3,848 | aoc-2022-kotlin | Apache License 2.0 |
src/Day09.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} | import java.lang.Exception
import kotlin.math.abs
data class Position(val x: Int, val y: Int) {
fun follow(other: Position): Position {
return if (!near(other)) {
moveTowards(other)
} else {
this
}
}
fun near(other: Position): Boolean {
return other.x - x in -1..1 && other.y - y in -1..1
}
fun moveTowards(other: Position): Position {
var newX = x
var newY = y
val xDirection = other.x - x
val yDirection = other.y - y
val shouldMoveX = xDirection < -1 || 1 < xDirection
val shouldMoveY = yDirection < -1 || 1 < yDirection
if (abs(xDirection) > 0 && abs(yDirection) > 0 && (shouldMoveX || shouldMoveY)) {
newX += xDirection / abs(xDirection)
newY += yDirection / abs(yDirection)
} else {
if (shouldMoveX) {
newX += xDirection / abs(xDirection)
}
if (shouldMoveY) {
newY += yDirection / abs(yDirection)
}
}
return Position(newX, newY)
}
fun up(): Position = copy(y = y + 1)
fun down(): Position = copy(y = y - 1)
fun right(): Position = copy(x = x + 1)
fun left(): Position = copy(x = x - 1)
}
data class Snake(val knots: List<Position>) {
fun move(direction: String): Snake {
return knots
.runningFold(null as? Position) { knot, next ->
if (knot == null) {
when (direction) {
"U" -> next.up()
"D" -> next.down()
"R" -> next.right()
"L" -> next.left()
else -> throw Exception()
}
} else {
next.follow(knot)
}
}
.filterNotNull()
.let { Snake(it) }
}
}
fun main() {
fun part1(input: List<String>): Int {
var head = Position(0, 0)
return input
.flatMap {
val (move, times) = it.split(" ")
List(times.toInt()) { move }
}
.runningFold(Position(0, 0)) { tail, move ->
head = when (move) {
"U" -> head.copy(y = head.y + 1)
"D" -> head.copy(y = head.y - 1)
"R" -> head.copy(x = head.x + 1)
"L" -> head.copy(x = head.x - 1)
else -> throw Exception()
}
if (!tail.near(head)) {
tail.moveTowards(head)
} else {
tail
}
}
.toSet()
.let { it.size }
}
fun part2(input: List<String>): Int {
return input
.flatMap {
val (move, times) = it.split(" ")
List(times.toInt()) { move }
}
.runningFold(Snake(List(10) { Position(0, 0)})) { snake, direction ->
snake.move(direction)
}
.map { it.knots.last() }
.toSet()
.let { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
println(part1(testInput))
check(part1(testInput) == 13)
val testInput2 = readInput("Day09_test_2")
println(part2(testInput2))
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 3,572 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day11/Day11.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day11
import execute
import readAllText
import splitBy
import wtf
data class Monkey(
val id: Int,
val items: MutableList<Long>,
val divisor: Long,
val op: (Long) -> Long,
val nextMonkeyOp: (Long) -> Int,
)
private fun parseMonkey(lines: List<String>): Monkey {
val id = lines[0].substringAfter("Monkey ").substringBefore(":").toInt()
val items = lines[1].substringAfter("Starting items: ").split(", ").map { it.toLong() }.toMutableList()
val op = lines[2].substringAfter("Operation: new = ").let {
when {
it == "old * old" -> { old: Long -> old * old }
it.startsWith("old + ") -> { old: Long -> old + it.substringAfter("old + ").toLong() }
it.startsWith("old * ") -> { old: Long -> old * it.substringAfter("old * ").toLong() }
else -> wtf(it)
}
}
val testDivisor = lines[3].substringAfter("Test: divisible by ").toLong()
val idOnTrue = lines[4].substringAfter("If true: throw to monkey ").toInt()
val idOnFalse = lines[5].substringAfter("If false: throw to monkey ").toInt()
val nextMonkeyOp = { worry: Long -> if (worry % testDivisor == 0L) idOnTrue else idOnFalse }
return Monkey(id, items, testDivisor, op, nextMonkeyOp)
}
fun part1(input: String) = solve(input, 20, 3)
fun part2(input: String) = solve(input, 10000, 1)
private fun solve(input: String, times: Int, worryDivisor: Long) = input.lineSequence()
.splitBy(String::isBlank).filter { it.any(String::isNotBlank) }
.map { parseMonkey(it) }
.associateBy { it.id }
.let { monkeys ->
val common = monkeys.values.map { it.divisor }.reduce { a, b -> a.times(b) }
val counters = monkeys.keys.associateWith { 0L }.toMutableMap()
repeat(times) {
monkeys.toList().sortedBy { it.first }
.forEach { (_, monkey) ->
monkey.items.forEach { item ->
val worry = monkey.op(item) % common / worryDivisor
val newMonkeyId = monkey.nextMonkeyOp(worry)
monkeys[newMonkeyId]!!.items += worry
counters[monkey.id] = counters[monkey.id]!! + 1
}
monkey.items.clear()
}
}
counters.values.sorted().takeLast(2).reduce(Long::times)
}
fun main() {
val input = readAllText("local/day11_input.txt")
val test = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent()
execute(::part1, test, 10605)
execute(::part1, input, 111210)
execute(::part2, test, 2713310158)
execute(::part2, input, 15447387620)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 3,443 | advent-of-code-2022 | MIT License |
src/main/kotlin/y2023/day02/Day02.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2023.day02
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class Game(
val id: Int,
var red: Int = 0,
var blue: Int = 0,
var green: Int = 0
)
fun input(): List<Game> {
return AoCGenerics.getInputLines("/y2023/day02/input.txt").map { line ->
val game = Game(
id = line.split(":")[0].split(" ")[1].toInt()
)
val gameRecords = line.split(":")[1].trim()
// Split the sets and then the draws. Doesn't hurt to mix sets as we only search for the highest of each color
val draws = gameRecords.split(";").map { it.trim().split(",") }.flatten()
draws.forEach { draw ->
val drawCount = draw.trim().split(" ")[0].trim().toInt()
val drawColor = draw.trim().split(" ")[1].trim()
when (drawColor) {
"blue" -> game.blue = maxOf(game.blue, drawCount)
"red" -> game.red = maxOf(game.red, drawCount)
"green" -> game.green = maxOf(game.green, drawCount)
}
}
game
}
}
fun Game.valid() = this.blue <= 14 && this.green <= 13 && this.red <= 12
fun part1() = input().sumOf {
if (it.valid()) it.id else 0
}
fun part2() =
input().sumOf {
it.green * it.red * it.blue
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,358 | AdventOfCode | MIT License |
kotlin/src/main/kotlin/LongestSubstringFromChanHo.kt | funfunStudy | 93,757,087 | false | null | import kotlin.math.max
fun main(args: Array<String>) {
val problems = listOf("abcabcbb", "bbbbb", "pwwkew", "", "dvdf", "asjrgapa")
val expected = listOf(3, 1, 3, 0, 3, 6)
problems.mapIndexed { index, s -> Pair(solution(s), expected.get(index)) }
.forEach { (result, expected) ->
println("result = $result, expected = $expected")
assert(result == expected)
}
}
fun solution(str: String): Int {
return maxLength(substring(str))
}
fun substring(str: String): List<String> {
return if (str.isEmpty())
listOf()
else {
str.fold(mutableListOf<String>()) { acc, ch ->
if (acc.size == 0) {
acc.add("$ch")
} else {
val tmp = acc[acc.size - 1]
if (tmp.contains("$ch")) {
acc.add("${tmp.drop(tmp.lastIndexOf(ch) + 1)}$ch")
} else {
acc[acc.size - 1] = "$tmp$ch"
}
}
acc
}
}
}
fun maxLength(strs: List<String>): Int {
return strs.map {
it.length
}.takeIf {
it.size >= 2
}?.reduce { acc, i ->
max(acc, i)
}?: run {
if (strs.isEmpty()) 0
else strs[0].length
}
}
| 0 | Kotlin | 3 | 14 | a207e4db320e8126169154aa1a7a96a58c71785f | 1,290 | algorithm | MIT License |
code/other/FastSubsetSum.kt | hakiobo | 397,069,173 | false | null | private fun fastSubsetSum(nums: IntArray, goal: Int, x: Int): Int {
val n = nums.size
val maxPref = IntArray((x shl 1) - 1) { -1 }
val cur = IntArray(x)
var part = 0
var b = 0
while (b < n && part + nums[b] <= goal) {
part += nums[b]
b++
}
if(b == n) return part
maxPref[part - goal + x - 1] = b
for (t in b until n) {
if (maxPref[x - 1] >= 0) return goal
val s = nums[t]
for (mu in (x - 2) downTo 0) {
maxPref[mu + s] = max(maxPref[mu + s], maxPref[mu])
}
for (mu in ((x - 1) shl 1) downTo x) {
for (j in maxPref[mu] - 1 downTo cur[mu - x]) {
val mup = mu - nums[j]
maxPref[mup] = max(maxPref[mup], j)
}
cur[mu - x] = max(cur[mu - x], maxPref[mu])
}
}
for (i in x - 1 downTo 0) {
if (maxPref[i] >= 0) {
return i + (goal - x + 1)
}
}
return 0
}
// this version allows you to construct the solution, but has worse space complexity
private fun fastSubsetSum(nums: IntArray, goal: Int, x: Int): BooleanArray {
val n = nums.size
val maxPref = IntArray((x shl 1) - 1) { -1 }
val cur = IntArray(x)
var part = 0
var b = 0
val used = BooleanArray(n)
while (b < n && part + nums[b] <= goal) {
part += nums[b]
used[b] = true
b++
}
if (b == n) return used
maxPref[part - goal + x - 1] = b
val prev = Array((x shl 1) - 1) { IntArray(b + 1) { -1 } }
prev[part - goal + x - 1][b] = n
for (t in b until n) {
if (maxPref[x - 1] >= 0) break
val s = nums[t]
for (mu in (x - 2) downTo 0) {
if (maxPref[mu] > maxPref[mu + s]) {
prev[mu + s][maxPref[mu]] = t
maxPref[mu + s] = maxPref[mu]
}
}
for (mu in ((x - 1) shl 1) downTo x) {
for (j in maxPref[mu] - 1 downTo cur[mu - x]) {
val mup = mu - nums[j]
if (maxPref[mup] < j) {
prev[mup][j] = j
maxPref[mup] = j
}
}
cur[mu - x] = max(cur[mu - x], maxPref[mu])
}
}
for (i in x - 1 downTo 0) {
if (maxPref[i] >= 0) {
var curSum = i
var a = maxPref[i]
var p = prev[curSum][a]
while (p != n) {
used[p] = !used[p]
curSum += nums[p] * if (used[p]) -1 else {
a++
1
}
while (prev[curSum][a] == -1) {
a++
}
p = prev[curSum][a]
}
return used
}
}
return used
}
| 0 | Kotlin | 1 | 2 | f862cc5e7fb6a81715d6ea8ccf7fb08833a58173 | 2,775 | Kotlinaughts | MIT License |
src/main/kotlin/org/sjoblomj/adventofcode/day3/Day3.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day3
import org.sjoblomj.adventofcode.readFile
import kotlin.system.measureTimeMillis
private const val inputFile = "src/main/resources/inputs/day3.txt"
typealias Claims = MutableList<Claim>
typealias Area = Array<Array<Claims>>
inline fun <reified T> matrix2d(height: Int, width: Int, initialize: () -> T) =
Array(height) { Array(width) { initialize() } }
fun day3() {
println("== DAY 3 ==")
val timeTaken = measureTimeMillis { calculateAndPrintDay3() }
println("Finished Day 3 in $timeTaken ms\n")
}
private fun calculateAndPrintDay3() {
val claims = readFile(inputFile).map { parseClaim(it) }.toMutableList()
val area = createArea(claims)
println("Number of overlaps are ${calculateOverlaps(area)}")
println("The ids of the claims that do not overlap with any other are ${findClaimsWithoutOverlaps(area, claims).map { it.id }}")
}
internal fun calculateOverlaps(area: Area): Int {
var overlaps = 0
for (y in area.indices) {
for (x in area[0].indices) {
overlaps += if (area[y][x].size > 1) 1 else 0
}
}
return overlaps
}
internal fun findClaimsWithoutOverlaps(area: Area, claims: Claims): Claims {
val overlaps = arrayListOf<Claim>()
for (y in area.indices) {
for (x in area[0].indices) {
if (area[y][x].size > 1) {
val unseenOverlaps = area[y][x].filter { !overlaps.contains(it) }
overlaps.addAll(unseenOverlaps)
}
}
}
return claims.minus(overlaps).toMutableList()
}
internal fun createArea(claims: Claims): Area {
val width = claims.map { it.x1 }.max()?.plus(1)?: 1
val height = claims.map { it.y1 }.max()?.plus(1)?: 1
val area = matrix2d(height, width) { mutableListOf<Claim>() }
for (claim in claims)
for (x in claim.x0 until claim.x1)
for (y in claim.y0 until claim.y1)
addClaimToArea(area, claim, x, y)
return area
}
private fun addClaimToArea(area: Area, claim: Claim, x: Int, y: Int) {
if (area[y][x].isEmpty()) {
area[y][x] = mutableListOf(claim)
} else {
area[y][x].add(claim)
}
}
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 2,067 | adventofcode2018 | MIT License |
src/main/kotlin/Crane.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() {
Crane.solve()
}
object Crane {
fun solve() {
val input = readInput()
val result = runMoves(input.state, input.moves)
println("Top of stacks: ${result.map { it.first() }.joinToString("")}")
}
private fun readInput(): Input {
val stacks = mutableListOf<Pair<Int, String>>()
val moves = mutableListOf<Move>()
var width = 0
var isStateSection = true
for (line in generateSequence(::readLine)) {
when {
isStateSection -> {
if (line == "") {
isStateSection = false
continue
}
val labelsRowMatch = "^\\s*(\\d+\\s*)+$".toRegex().matchEntire(line)
if (labelsRowMatch != null) {
width = line.trim().split("\\s+".toRegex()).size
}
val matchResults = "\\[(\\w+)]".toRegex().findAll(line)
for (result in matchResults) {
val index = result.range.first / 4
val value = result.groupValues[1]
stacks.add(0, Pair(index, value))
}
}
else -> {
// parse move
val matchResult = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex().matchEntire(line)
?: throw Error("Unexpected move input")
moves.add(
Move(
matchResult.groupValues[2].toInt() - 1,
matchResult.groupValues[3].toInt() - 1,
matchResult.groupValues[1].toInt()
)
)
}
}
}
val state = List<MutableList<String>>(width) { mutableListOf() }
for (item in stacks) {
state[item.first].add(0, item.second)
}
return Input(state, moves)
}
private fun runMoves(state: List<List<String>>, moves: List<Move>): List<List<String>> {
val result = state.map { it.toMutableList() }
for (move in moves) {
val fromStack = result[move.from]
val loaded = fromStack.subList(0, move.count).toList() //.reversed()
for (i in loaded) {
fromStack.removeAt(0)
}
result[move.to].addAll(0,loaded)
}
return result
}
data class Move(val from: Int, val to: Int, val count: Int)
data class Input(val state: List<List<String>>, val moves: List<Move>)
}
| 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 2,684 | aoc2022 | MIT License |
src/main/kotlin/Day14.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | class Day14 {
fun part1(input: List<String>): Int {
val rocks = mapToRocks(input)
return Cave(rocks).dropSand()
}
fun part2(input: List<String>): Int {
val rocks = mapToRocks(input)
return Cave(rocks, true).dropSandWithFloor()
}
private fun mapToRocks(input: List<String>) = input.flatMap {
it.split(" -> ")
.windowed(2)
.flatMap { (line1, line2) -> mapToPoints(line1, line2) }
}.toSet()
private fun mapToPoints(line1: String, line2: String): List<Point> {
val (p1x, p1y) = line1.split(",").map { it.toInt() }
val (p2x, p2y) = line2.split(",").map { it.toInt() }
val xRange = if (p1x <= p2x) p1x..p2x else p2x..p1x
val yRange = if (p1y <= p2y) p1y..p2y else p2y..p1y
return (xRange).flatMap { x -> (yRange).map { y -> Point(x, y) } }
}
data class Point(val x: Int, val y: Int) {
fun possibleMovesDown(): List<Point> {
return listOf(
Point(x, y + 1),
Point(x - 1, y + 1),
Point(x + 1, y + 1)
)
}
}
class Cave(rocks: Set<Point>, withFloor: Boolean = false) {
private val sandPoint = Point(500, 0)
private val rocksAndFloor = mutableSetOf<Point>()
private val sand = mutableSetOf<Point>()
private var lowestRock = 0
init {
rocksAndFloor.addAll(rocks)
lowestRock = if (withFloor) {
val floorLevel = rocks.map { it.y }.max() + 2
val floor = createFloor(rocks, floorLevel)
rocksAndFloor.addAll(floor)
floorLevel
} else {
rocks.map { it.y }.max()
}
}
private fun createFloor(rocks: Set<Point>, floorLevel: Int): List<Point> {
val offset = rocks.map { it.y }.max()
val minX = rocks.map { it.x }.min() - offset
val maxX = rocks.map { it.x }.max() + offset
return (minX..maxX).map { Point(it, floorLevel) }
}
fun dropSand(): Int {
var nextSpot = findLandingPlace(sandPoint)
while (nextSpot != null && nextSpot != sandPoint) {
sand.add(nextSpot)
nextSpot = findLandingPlace(sandPoint)
}
draw()
return sand.size
}
fun dropSandWithFloor(): Int {
return dropSand() + 1
}
private fun findLandingPlace(current: Point): Point? {
if (current.y > lowestRock) return null
val nextPoint = current.possibleMovesDown().firstOrNull { it !in rocksAndFloor && it !in sand }
return when (nextPoint) {
null -> current
else -> findLandingPlace(nextPoint)
}
}
private fun draw() {
val all = mutableListOf<Point>().apply {
addAll(rocksAndFloor)
addAll(sand)
}
val minX = all.map { it.x }.min()
val maxX = all.map { it.x }.max()
val maxY = all.map { it.y }.max()
for (y in 0..maxY) {
for (x in minX..maxX) {
when (Point(x, y)) {
Point(500, 0) -> print('+')
in rocksAndFloor -> print('#')
in sand -> print('o')
else -> print('.')
}
if (x == maxX) {
println()
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 3,640 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/day03/Day03.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day03
import io.kotest.matchers.shouldBe
import utils.readInput
fun main() {
val testInput = readInput("03", "test_input")
val realInput = readInput("03", "input")
testInput.asSequence()
.findDuplicates()
.mapToPriorities()
.sum()
.also(::println) shouldBe 157
realInput.asSequence()
.findDuplicates()
.mapToPriorities()
.sum()
.let(::println)
testInput.asSequence()
.findBadge()
.mapToPriorities()
.sum()
.also(::println) shouldBe 70
realInput.asSequence()
.findBadge()
.mapToPriorities()
.sum()
.let(::println)
}
private fun Sequence<String>.findDuplicates(): Sequence<Char> {
return map { it to separateCompartmentRegex(it) }
.map { (input, regex) -> regex.find(input)!! }
.map { it.groups[1]!!.value.single() }
}
private fun separateCompartmentRegex(input: String): Regex {
return "\\A.{0,${input.length / 2 - 1}}([a-zA-Z]).*\\1.{0,${input.length / 2 - 1}}\\z".toRegex()
}
private fun Sequence<Char>.mapToPriorities() = map {
when (it) {
in 'a'..'z' -> it - 'a' + 1
else -> it - 'A' + 27
}
}
private fun Sequence<String>.findBadge() = chunked(3) { (first, second, third) ->
first.toSet().intersect(second.toSet())
.intersect(third.toSet())
.single()
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 1,403 | Advent-of-Code | Apache License 2.0 |
src/Day05.kt | mihansweatpants | 573,733,975 | false | {"Kotlin": 31704} | import java.util.LinkedList
fun main() {
fun part1(input: List<String>): String {
val (stacks, moves) = parseInput(input)
for (move in moves) {
val fromStack = stacks[move.from]!!
val toStack = stacks[move.to]!!
repeat(move.amount) {
toStack += fromStack.removeLast()
}
}
return stacks.topCrates()
}
fun part2(input: List<String>): String {
val (stacks, moves) = parseInput(input)
for (move in moves) {
val fromStack = stacks[move.from]!!
val toStack = stacks[move.to]!!
val batchOfCrates = LinkedList<Char>()
repeat(move.amount) {
batchOfCrates.addFirst(fromStack.removeLast())
}
toStack += batchOfCrates
}
return stacks.topCrates()
}
val input = readInput("Day05").lines()
println(part1(input))
println(part2(input))
}
private fun parseInput(input: List<String>): Pair<MutableMap<Int, MutableList<Char>>, List<Move>> {
val splitIndex = input.indexOfFirst { it.isBlank() }
val stackNumberConfig = input[splitIndex - 1]
val stackConfig = input.slice(0 until splitIndex - 1).asReversed()
val stacks = mutableMapOf<Int, MutableList<Char>>()
for (line in stackConfig) {
var currIndex = 1
while (currIndex < line.length) {
val stack = stacks.computeIfAbsent(stackNumberConfig[currIndex].digitToInt()) { mutableListOf() }
if (line[currIndex] != ' ') {
stack.add(line[currIndex])
}
currIndex += 4
}
}
val movesConfig = input.takeLast(input.size - splitIndex - 1)
val moves = movesConfig.map { it.parseMove() }
return Pair(stacks, moves)
}
private data class Move(
val amount: Int,
val from: Int,
val to: Int
)
private val numsRegex = Regex("[0-9]+")
private fun String.parseMove(): Move {
val (amount, from, to) = numsRegex.findAll(this)
.map(MatchResult::value)
.toList()
return Move(amount = amount.toInt(), from = from.toInt(), to = to.toInt())
}
private fun Map<Int, List<Char>>.topCrates() =
this.keys.sorted()
.filter { this[it]?.isNotEmpty() ?: false }
.joinToString("") { this[it]?.last().toString() } | 0 | Kotlin | 0 | 0 | 0de332053f6c8f44e94f857ba7fe2d7c5d0aae91 | 2,349 | aoc-2022 | Apache License 2.0 |
src/Day13.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | import org.apache.commons.collections4.ListUtils
fun main() {
fun parseSingleSignal(s: String): Any {
val signal = mutableListOf<Any>()
if (!s.contains("]") && !s.contains("[") && !s.contains(",")) {
return s.takeIf { it != "" }?.toInt() ?: Unit
}
val currentString = s.substring(
s.indexOfFirst { it == '[' } + 1, s.indexOfLast { it == ']' }
)
var start = 0
var openingCount = 0
var closingCount = 0
for (x in currentString.indices) {
if (currentString[x] == ',' && openingCount == closingCount) {
signal.add(parseSingleSignal(currentString.substring(start, x)))
start = x.inc()
}
if (currentString[x] == '[') {
openingCount += 1
}
if (currentString[x] == ']') {
closingCount += 1
}
}
start = currentString.length
for (x in currentString.indices.reversed()) {
if (currentString[x] == ',' && openingCount == closingCount) {
signal.add(parseSingleSignal(currentString.substring(x + 1, start)))
break
}
if (currentString[x] == '[') {
openingCount += 1
}
if (currentString[x] == ']') {
closingCount += 1
}
if (x == 0) {
signal.add(parseSingleSignal(currentString))
}
}
return signal
}
fun compareSignal(signalPair: Pair<Any, Any>): Boolean? {
if (signalPair.first is Int && signalPair.second is Int) {
if (signalPair.first == signalPair.second) {
return null
}
return (signalPair.first as Int) < (signalPair.second as Int)
}
if (signalPair.first is List<*> && signalPair.second is List<*>) {
val signalListOne = (signalPair.first as List<*>)
val signalListTwo = (signalPair.second as List<*>)
val test = (signalListOne.indices)
.asSequence()
.map {
if (!signalListTwo.indices.contains(it)) {
false
} else {
compareSignal(Pair(signalListOne[it]!!, signalListTwo[it]!!))
}
}
.takeWhileInclusive { it == null }
.toList()
return test.firstNotNullOfOrNull { it } ?: if (signalListOne.size >= signalListTwo.size) return null else return true
}
if (signalPair.second !is List<*>) {
return compareSignal(Pair(signalPair.first, listOf(signalPair.second as Int)))
}
return compareSignal(Pair(listOf(signalPair.first as Int), signalPair.second))
}
fun part1(input: List<String>): Int {
val signalList: List<Pair<Any, Any>> = input.splitWhen { it == "" }.map { Pair(parseSingleSignal(it[0]), parseSingleSignal(it[1])) }
val signalValidation = signalList.map {
compareSignal(it)
}
return signalValidation.foldIndexed(0) { index, acc, b -> if (b != false) acc + index + 1 else acc }
}
fun part2(input: List<String>): Int {
val dividerPackages = listOf("[[2]]", "[[6]]").map { parseSingleSignal(it) }
val signalList = input.filter { it != "" }.map { parseSingleSignal(it) }
val sortedList: List<Any> = ListUtils.union(signalList, dividerPackages)
.sortedWith { o1: Any, o2: Any -> if (compareSignal(Pair(o1, o2))!!) -1 else 1 }
return sortedList.foldIndexed(1) { index, acc, signal -> if (dividerPackages.contains(signal)) acc * (index + 1) else acc }
}
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
fun <T> Sequence<T>.takeWhileInclusive(predicate: (T) -> Boolean) = sequence {
with(iterator()) {
while (hasNext()) {
val next = next()
yield(next)
if (!predicate(next)) break
}
}
} | 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 4,115 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/day3/day3Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day3
import lib.*
suspend fun main() {
setupChallenge().solveChallenge()
}
fun setupChallenge(): Challenge<Array<Array<Char>>> {
return setup {
day(3)
year(2023)
//input("example.txt")
parser {
it.readLines().get2DArrayOfColumns()
}
partOne {
val partNumbers = mutableListOf<Int>()
val schematic = it
schematic.first().indices.forEach {j ->
var currentNumber: String? = null
var isPart = false
schematic.indices.forEach {i ->
val char = schematic[i][j]
when {
char.isDigit() -> {
currentNumber = if(currentNumber == null) char.toString() else currentNumber + char
isPart = isPart ||
listOf(Pair(-1, -1), Pair(0, -1), Pair(1, -1), Pair(1, 0), Pair(1, 1), Pair(0, 1), Pair(-1, 1))
.any { schematic.tryMove(Pair(i, j), it).first.isSymbol() }
}
char.isSymbol() -> {
partNumbers.tryAdd(currentNumber)
isPart = true
currentNumber = ""
}
else -> {
if(isPart) {
partNumbers.tryAdd(currentNumber)
}
currentNumber = null
isPart = false
}
}
}
if(isPart) {
partNumbers.tryAdd(currentNumber)
}
}
partNumbers.sum().toString()
}
partTwo {
val gearRatios = mutableListOf<Long>()
val schematic = it
schematic.first().indices.forEach {j ->
schematic.indices.forEach {i ->
if(schematic[i][j] == '*')
{
val numbers = schematic.getAdjacentNumbers(i, j)
if(numbers.size == 2) {
gearRatios.add(numbers[0] * numbers[1])
}
}
}
}
gearRatios.sum().toString()
}
}
}
fun Char?.isSymbol(): Boolean {
return this != null && this != '.' && !this.isDigit()
}
fun MutableList<Int>.tryAdd(ele: String?) {
if(!ele.isNullOrEmpty()) {
this.add(ele.toInt())
}
}
fun Array<Array<Char>>.getAdjacentNumbers(i: Int, j: Int): List<Long> {
val relevantNeighbours = this.getNeighbours(i, j, true).filter { it.second.isDigit() }
val parsed = mutableListOf<Pair<Int, Int>>()
val numbers = mutableListOf<Long>()
relevantNeighbours.forEach {
if(it.first !in parsed) {
val (x, y) = it.first
var start = x
var end = x
while(this.isValidCoord(start - 1, y) && this[start - 1][y].isDigit()) {
start--
parsed.add(Pair(start, y))
}
while(this.isValidCoord(end + 1, y) && this[end + 1][y].isDigit()) {
end++
parsed.add(Pair(end, y))
}
val number = (start .. end).map { this[it][y] }.fold(""){s, digit -> s + digit}.toLong()
numbers.add(number)
}
}
return numbers
}
| 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 3,553 | AoC-2023-DDJ | MIT License |
AOC-2023/src/main/kotlin/Day05.kt | sagar-viradiya | 117,343,471 | false | {"Kotlin": 72737} | import utils.*
object Day05 {
fun part01(input: String): Long {
val inputParts = input.splitAtNewEmptyLines()
val seeds = inputParts[0].splitAtColon()[1].trim().splitAtWhiteSpace().map { it.toLong() }
val mapList = inputParts.drop(0).map { input ->
sourceToDestinationMap(
input.splitAtNewLines().filterIndexed { index, _ -> index > 0 }.map { map ->
val mapRange = map.splitAtWhiteSpace()
Triple(mapRange[0].toLong(), mapRange[1].toLong(), mapRange[2].toLong())
}
)
}
return seeds.minOf { seed -> mapList.fold(seed) { currentValue, map -> getMapValue(currentValue, map) } }
}
fun part02(input: String): Long {
val inputParts = input.splitAtNewEmptyLines()
val seedPair = inputParts[0].splitAtColon()[1].trim().splitAtWhiteSpace().map { it.toLong() }
val mapList = inputParts.drop(0).map { input ->
sourceToDestinationMap(
input.splitAtNewLines().filterIndexed { index, _ -> index > 0 }.map { map ->
val mapRange = map.splitAtWhiteSpace()
Triple(mapRange[0].toLong(), mapRange[1].toLong(), mapRange[2].toLong())
}
)
}
var location: Long = Long.MAX_VALUE
for (index in seedPair.indices step 2) {
location = minOf(
location,
(seedPair[index] until seedPair[index] + seedPair[index + 1]).minOf { seed ->
mapList.fold(seed) { currentValue, map ->
getMapValue(
currentValue,
map
)
}
})
}
return location
}
private fun getMapValue(source: Long, mapping: Map<LongRange, Long>): Long {
for (entry in mapping) {
if (source in entry.key) {
return entry.value + (source - entry.key.first)
}
}
return source
}
private fun sourceToDestinationMap(mapRange: List<Triple<Long, Long, Long>>): Map<LongRange, Long> {
val sourceToDestinationMap = mutableMapOf<LongRange, Long>()
mapRange.forEach { triple ->
sourceToDestinationMap[triple.second until triple.second + triple.third] = triple.first
}
return sourceToDestinationMap
}
} | 0 | Kotlin | 0 | 0 | 7f88418f4eb5bb59a69333595dffa19bee270064 | 2,462 | advent-of-code | MIT License |
src/day02/Day02.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day02
import java.io.File
fun main() {
val data = parse("src/day02/Day02.txt")
println("🎄 Day 02 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class CubeSet(
val redCount: Int,
val blueCount: Int,
val greenCount: Int,
)
private data class Game(
val id: Int,
val sets: List<CubeSet>,
)
private val PATTERN = """(\d+) (red|blue|green)""".toRegex()
private fun String.toCubeSet(): CubeSet {
val colors = PATTERN.findAll(this)
.map { it.destructured }
.associate { (count, color) -> color to count.toInt() }
return CubeSet(
colors.getOrDefault("red", 0),
colors.getOrDefault("blue", 0),
colors.getOrDefault("green", 0),
)
}
private fun String.toGame(): Game {
val parts = this
.split(";", ":")
.map(String::trim)
val id = parts.first()
.filter(Char::isDigit)
.toInt()
val sets = parts
.drop(1)
.map(String::toCubeSet)
return Game(id, sets)
}
private fun parse(path: String): List<Game> =
File(path)
.readLines()
.map(String::toGame)
private fun part1(data: List<Game>): Int =
data.asSequence()
.filter { (_, sets) -> sets.all { it.redCount <= 12 } }
.filter { (_, sets) -> sets.all { it.blueCount <= 14 } }
.filter { (_, sets) -> sets.all { it.greenCount <= 13 } }
.sumOf(Game::id)
private fun part2(data: List<Game>): Int =
data.sumOf { (_, sets) ->
sets.maxOf(CubeSet::redCount) *
sets.maxOf(CubeSet::blueCount) *
sets.maxOf(CubeSet::greenCount)
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 1,823 | advent-of-code-2023 | MIT License |
src/main/kotlin/days/Day15.kt | hughjdavey | 725,972,063 | false | {"Kotlin": 76988} | package days
class Day15 : Day(15) {
private val initSequence = inputString.replace("\n", "").split(',')
override fun partOne(): Any {
return initSequence.sumOf(this::hash)
}
override fun partTwo(): Any {
val boxes = (0..255).associateWith { mutableListOf<Lens>() }
val steps = initSequence.map {
val splits = Regex("([a-z]+)([-=])(\\d+)?").matchEntire(it)!!.groupValues.drop(1)
Step(splits[0], splits[1].first(), if (splits[2].isNotEmpty()) splits[2].toInt() else null )
}
for (step in steps) {
val box = hash(step.lensLabel)
val boxLenses = boxes[box]!!
if (step.operation == '-') {
boxLenses.removeIf { it.label == step.lensLabel }
} else {
val lens = Lens(step.lensLabel, step.lensFocalLength!!)
val lensWithSameLabelIndex = boxLenses.indexOfFirst { it.label == lens.label }
if (lensWithSameLabelIndex != -1) {
boxLenses.removeAt(lensWithSameLabelIndex)
boxLenses.add(lensWithSameLabelIndex, lens)
} else {
boxLenses.add(lens)
}
}
}
return boxes.map { (boxNumber, boxLenses) -> boxLenses.sumOf { it.focusingPower(boxNumber, boxLenses) } }.sum()
}
fun hash(s: String): Int {
return s.fold(0) { value, char -> ((value + char.code) * 17) % 256 }
}
data class Lens(val label: String, val focalLength: Int) {
fun focusingPower(boxNumber: Int, boxLenses: List<Lens>): Int {
return (1 + boxNumber) * (boxLenses.indexOf(this) + 1) * focalLength
}
}
data class Step(val lensLabel: String, val operation: Char, val lensFocalLength: Int?)
}
| 0 | Kotlin | 0 | 0 | 330f13d57ef8108f5c605f54b23d04621ed2b3de | 1,815 | aoc-2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/problems/Day15.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
import java.util.*
class Day15(override val input: String) : Problem {
override val number: Int = 15
override fun runPartOne(): String {
val board = Board.fromStr(input)
return board.lowestTotalRisk().toString()
}
override fun runPartTwo(): String {
val board = Board.fromStr(input).expand(5)
return board.lowestTotalRisk().toString()
}
data class Board(val board: MutableList<MutableList<Int>>) {
companion object {
fun fromStr(input: String): Board {
return Board(
input.lines()
.map { line ->
line
.toCharArray()
.map { i -> i.digitToInt() }
.toMutableList()
}.toMutableList()
)
}
}
private val width = board.first().size
private val height = board.size
fun lowestTotalRisk(): Long {
val distance = List(height) { MutableList(width) { Long.MAX_VALUE } }
val queue = PriorityQueue(compareBy<Cell> { it.distance }
.thenBy { it.m }
.thenBy { it.n })
distance[0][0] = 0
queue.add(Cell(0, 0, 0))
while (queue.isNotEmpty()) {
val cell = queue.poll()!!
cell.neighbours(height - 1, width - 1).forEach { n ->
val neighbourDistanceToCell = distance[cell.m][cell.n] + board[n.m][n.n]
if (distance[n.m][n.n] > neighbourDistanceToCell) {
queue.removeIf { it.m == n.m && it.n == n.n }
distance[n.m][n.n] = neighbourDistanceToCell
queue.add(Cell(n.m, n.n, neighbourDistanceToCell))
}
}
}
return distance.last().last()
}
fun expand(by: Int): Board {
val newWidth = width * by
val newHeight = height * by
val newBoard = MutableList(newHeight) { MutableList(newWidth) { 0 } }
for (m in 0 until newHeight) {
for (n in 0 until newHeight) {
val firstRow = m in 0 until height
val firstColumn = n in 0 until width
newBoard[m][n] = (
if (firstRow && firstColumn) {
board[m][n]
} else if (firstColumn) {
val upM = m - height
newBoard[upM][n] + 1
} else {
val leftN = n - width
newBoard[m][leftN] + 1
}
).wrapValue()
}
}
return Board(newBoard)
}
private fun Int.wrapValue(): Int {
return when {
this > 9 -> 1
else -> this
}
}
private data class Cell(val m: Int, val n: Int, val distance: Long) {
fun neighbours(mMax: Int, nMax: Int): Set<Cell> {
return setOf(
Pair(1, 0),
Pair(0, 1),
Pair(-1, 0),
Pair(0, -1),
)
.map { (dM, dN) -> Cell(this.m + dM, this.n + dN, -1) }
.filter { cell -> cell.m in 0..mMax && cell.n in 0..nMax }
.toSet()
}
}
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 3,668 | AdventOfCode2021 | MIT License |
src/Day04.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | private fun IntRange.contains(other: IntRange): Boolean {
return first <= other.first && last >= other.last
}
private fun IntRange.overlap(other: IntRange): Boolean {
return first <= other.last && other.first <= last
}
fun main() {
fun parse(line: String): List<IntRange> {
return line.split(',').map { segment ->
val (a,b) = segment.split('-').map { it.toInt() }
a..b
}
}
fun part1(input: List<List<IntRange>>): Int {
return input.filter { (a,b) ->
a.contains(b) || b.contains(a)
}.size
}
fun part2(input: List<List<IntRange>>): Int {
return input.filter { (a,b) ->
a.overlap(b)
}.size
}
val testInput = readInput("Day04_test").map { parse(it) }
assert(part1(testInput), 2)
assert(part2(testInput), 4)
val input = readInput("Day04").map { parse(it) }
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 956 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ikueb/advent18/Day22.kt | h-j-k | 159,901,179 | false | null | package com.ikueb.advent18
import com.ikueb.advent18.model.Point
import java.util.*
object Day22 {
fun getRiskLevel(depth: Int, target: Point) = HardCave(depth, target).apply {
(0..target.y).forEach { y ->
(0..target.x).forEach { x -> at(Point(x, y)) }
}
}.getTotalRiskRiskLevel()
fun getShortestTimeTo(depth: Int, target: Point): Int {
val cave = HardCave(depth, target)
val start = cave.at(Point(0, 0)).let { CaveStep(it, it.toolsRequired().first()) }
val seenShortest = mutableMapOf(start.asKey to start.cost)
val stepsRemaining = PriorityQueue<CaveStep>().apply { add(start) }
while (stepsRemaining.isNotEmpty()) {
val step = stepsRemaining.poll()
if (step.at.point == target && step.using == Tool.TORCH) {
return step.cost
}
step.generateSteps(cave).forEach {
val existing = seenShortest[it.asKey]
if (existing == null || it.cost < existing) {
seenShortest[it.asKey] = it.cost
stepsRemaining += it
}
}
}
return -1
}
}
private data class Region(val point: Point, val cave: HardCave) {
val geologicIndex: Int by lazy { deriveGeologicIndex() }
val erosionLevel: Int by lazy { (geologicIndex + cave.depth) % 20183 }
val regionType: RegionType by lazy { RegionType.values()[erosionLevel % 3] }
private val atEnds = point in setOf(Point(0, 0), cave.target)
private fun deriveGeologicIndex() = when {
atEnds -> 0
point.y == 0 -> point.x * 16807
point.x == 0 -> point.y * 48271
else -> (cave.at(point.w()) to cave.at(point.n()))
.let { it.first.erosionLevel * it.second.erosionLevel }
}
fun toolsRequired(): Set<Tool> = if (atEnds) setOf(Tool.TORCH) else
when (regionType) {
RegionType.ROCKY -> setOf(Tool.CLIMBING_GEAR, Tool.TORCH)
RegionType.WET -> setOf(Tool.CLIMBING_GEAR, Tool.NEITHER)
RegionType.NARROW -> setOf(Tool.TORCH, Tool.NEITHER)
}
}
private data class HardCave(val depth: Int, val target: Point) {
private val state = mutableMapOf<Point, Region>()
fun at(point: Point) = state.getOrPut(point) { Region(point, this) }
fun getTotalRiskRiskLevel() = state.values.sumBy { it.regionType.riskLevel }
}
private data class CaveStep(val at: Region, val using: Tool, val cost: Int = 0) :
Comparable<CaveStep> {
val asKey: Pair<Region, Tool> by lazy { at to using }
override fun compareTo(other: CaveStep) = cost.compareTo(other.cost)
fun generateSteps(cave: HardCave) = stepSameTools(cave) + stepOtherTools()
private fun stepSameTools(cave: HardCave) = at.point.orderedCardinal
.asSequence()
.filter { it.isPositive() }
.map { Region(it, cave) }
.filter { using in it.toolsRequired() }
.map { CaveStep(it, using, cost + 1) }
private fun stepOtherTools() = at.toolsRequired().minus(using)
.asSequence()
.map { CaveStep(at, it, cost + 7) }
}
private enum class RegionType {
ROCKY,
WET,
NARROW;
val riskLevel = ordinal
}
private enum class Tool {
TORCH,
CLIMBING_GEAR,
NEITHER
} | 0 | Kotlin | 0 | 0 | f1d5c58777968e37e81e61a8ed972dc24b30ac76 | 3,344 | advent18 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day07.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import util.illegalInput
import kotlin.math.min
// https://adventofcode.com/2022/day/7
object Day07 : AoCDay<Int>(
title = "No Space Left On Device",
part1ExampleAnswer = 95437,
part1Answer = 1792222,
part2ExampleAnswer = 24933642,
part2Answer = 1112963,
) {
private data class CommandAndOutput(val command: String, val output: List<String>)
private fun parseCommandsAndOutputs(input: String) = input
.removePrefix("$ ")
.splitToSequence("\n$ ")
.map { commandAndOutput ->
val lines = commandAndOutput.lines()
CommandAndOutput(command = lines.first(), output = lines.subList(1, lines.size))
}
private sealed interface FileOrDirectory
private class File(val size: Int) : FileOrDirectory
private class Directory(val parent: Directory?) : FileOrDirectory {
val children = HashMap<String, FileOrDirectory>()
}
private fun parseFileSystem(input: String): Directory {
val root = Directory(parent = null)
var cwd = root
for ((command, output) in parseCommandsAndOutputs(input)) {
when {
command.startsWith("cd ") -> {
require(output.isEmpty())
cwd = when (val dir = command.removePrefix("cd ")) {
"/" -> root
".." -> cwd.parent ?: root
else -> cwd.children[dir] as Directory
}
}
command == "ls" -> {
for (child in output) {
val (dirOrSize, name) = child.split(' ', limit = 2)
val prevDirOrSize = when (val prev = cwd.children[name]) {
null -> null
is File -> prev.size.toString()
is Directory -> "dir"
}
if (prevDirOrSize == null) {
cwd.children[name] = when (dirOrSize) {
"dir" -> Directory(parent = cwd)
else -> File(size = dirOrSize.toInt())
}
} else {
check(dirOrSize == prevDirOrSize) { "There was a change in the file system" }
}
}
}
else -> illegalInput(command)
}
}
return root
}
private data class DirectorySize(val size: Int, val children: List<DirectorySize>)
private val EMPTY_DIRECTORY_SIZE = DirectorySize(size = 0, children = emptyList())
private fun Directory.calculateDirectorySize(): DirectorySize =
children.values.fold(initial = EMPTY_DIRECTORY_SIZE) { acc, child ->
when (child) {
is File -> acc.copy(size = acc.size + child.size)
is Directory -> {
val childSize = child.calculateDirectorySize()
DirectorySize(size = acc.size + childSize.size, children = acc.children + childSize)
}
}
}
override fun part1(input: String): Int {
fun DirectorySize.sumOfSizesOfAtMost(n: Int): Int =
(if (size <= n) size else 0) + (children.sumOf { it.sumOfSizesOfAtMost(n) })
return parseFileSystem(input).calculateDirectorySize().sumOfSizesOfAtMost(100000)
}
override fun part2(input: String): Int {
val root = parseFileSystem(input).calculateDirectorySize()
val availableSpace = 70000000 - root.size
val missingSpace = 30000000 - availableSpace
fun DirectorySize.sizeOfSmallestDirectoryToDelete(smallestYet: Int): Int =
if (size < missingSpace) {
smallestYet
} else {
children.fold(initial = min(size, smallestYet)) { smallest, child ->
min(smallest, child.sizeOfSmallestDirectoryToDelete(smallestYet = smallest))
}
}
return root.sizeOfSmallestDirectoryToDelete(smallestYet = root.size)
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 4,168 | advent-of-code-kotlin | MIT License |
src/Day08.kt | dyomin-ea | 572,996,238 | false | {"Kotlin": 21309} | interface Tree {
val height: Int
val u: Tree
val d: Tree
val l: Tree
val r: Tree
}
fun main() {
operator fun List<String>.get(r: Int, c: Int): Int =
this[r][c] - '0'
operator fun <V> MutableMap<Pair<Int, Int>, V>.set(r: Int, c: Int, value: V) {
set(r to c, value)
}
val plain = object : Tree {
override val height = -1
override val u = this
override val d = this
override val l = this
override val r = this
}
fun Tree.iterateBy(body: (Tree) -> Tree): Iterable<Tree> {
var pointer = this
val iterator = iterator {
while (pointer != plain) {
pointer = body(pointer)
if (pointer != plain) {
yield(pointer)
}
}
}
return Iterable { iterator }
}
fun Tree.isShaded(): Boolean =
iterateBy { it.u }.any { it.height >= height } &&
iterateBy { it.d }.any { it.height >= height } &&
iterateBy { it.l }.any { it.height >= height } &&
iterateBy { it.r }.any { it.height >= height }
fun Tree.onWay(next: (Tree) -> Tree): Int {
var result = 0
for (tree in iterateBy(next)) {
when {
tree.height < height -> result++
tree.height >= height -> {
result++
break
}
}
}
return result
}
fun Tree.score(): Int =
onWay(Tree::u) *
onWay(Tree::d) *
onWay { it.l } *
onWay(Tree::r)
fun resolve(input: List<String>): List<Tree> {
val cache = mutableMapOf<Pair<Int, Int>, Tree>()
val maxRow = input.lastIndex
val maxCol = input.first().lastIndex
operator fun MutableMap<Pair<Int, Int>, Tree>.get(r: Int, c: Int): Tree? =
if (r < 0 || c < 0 || r > maxRow || c > maxCol) {
plain
} else {
get(r to c)
}
fun tree(row: Int, col: Int): Tree =
cache[row, col] ?: object : Tree {
override val height = input[row, col]
override val u by lazy { tree(row + 1, col) }
override val d by lazy { tree(row - 1, col) }
override val l by lazy { tree(row, col - 1) }
override val r by lazy { tree(row, col + 1) }
init {
cache[row, col] = this
}
}
val cols = input.first().indices
return input.indices.flatMap { r -> cols.map { c -> tree(r, c) } }
}
fun part1(input: List<String>): Int {
return resolve(input).count { !it.isShaded() }
}
fun part2(input: List<String>): Int =
resolve(input)
.filter { !it.isShaded() }
.maxOf { it.score() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8) {
resolve(testInput)
.map { it.score() }
.chunked(5)
.joinToString(prefix = "\n", separator = "\n") { it.joinToString(separator = " ") }
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 8aaf3f063ce432207dee5f4ad4e597030cfded6d | 2,727 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2018/day11/ChronalCharge.kt | arnab | 75,525,311 | false | null | package aoc2018.day11
data class Grid(val sizeX: Int, val sizeY: Int, val serial: Int) {
private val grid = Array(sizeX + 1) { IntArray(sizeY + 1) }
fun calculateAreaWithHighestPower(sizeOfBox: Int): Pair<Point, Int>? {
for (y in 1 until sizeY + 1 ) {
for (x in 1 until sizeX + 1) {
grid[y][x] = Point(x, y).calculatePowerLevel(serial)
}
}
return (1 until sizeY + 1 - sizeOfBox).flatMap { y ->
(1 until sizeX + 1 - sizeOfBox).map { x ->
val totalPowerOfArea = calculateTotalPowerOfArea(x, y, sizeOfBox)
Pair(Point(x, y), totalPowerOfArea)
}
}.maxBy { it.second }
}
fun calculateAreaOfAnySizeWithHighestPower(): Pair<Int, Pair<Point, Int>?>? {
// Note: Hack/optimization. As the size increases beyond a certain size,
// it is unlikely to have higher total power than smaller boxes. In empirical evidence the optimum
// size is ~15. Since it's also expensive to calculate as the size increases,
// "optimize" to check only till 20 :D
return (1 until 21).map { size ->
val highestPowerForSize = calculateAreaWithHighestPower(size)
println("Highest power for size: $size: $highestPowerForSize")
Pair(size, highestPowerForSize)
}.maxBy { it.second?.second ?: 0 }
}
private fun calculateTotalPowerOfArea(x: Int, y: Int, sizeOfBox: Int): Int {
return (y until y + sizeOfBox).flatMap { yOfPointInsideBox ->
(x until x + sizeOfBox).map { xOfPointInsideBox ->
Point(xOfPointInsideBox, yOfPointInsideBox).calculatePowerLevel(serial)
}
}.sum()
}
}
data class Point(val x: Int, val y: Int) {
public fun calculatePowerLevel(serial: Int) = (x + 10).let { rackId ->
((((rackId * y) + serial) * rackId / 100) % 10) - 5
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,927 | adventofcode | MIT License |
src/Day05.kt | JCampbell8 | 572,669,444 | false | {"Kotlin": 10115} | import java.util.*
fun main() {
data class CrateMovement(val numCrates: Int, val fromStack: Int, val toStack: Int)
fun parseCrates(input: List<String>): MutableList<Deque<String>> {
val crateChart = input.subList(0, input.indexOf(""))
val numRows = crateChart[crateChart.size - 1].replace("\\s".toRegex(), "").length
val crateList: MutableList<Deque<String>> = MutableList(numRows) { LinkedList() }
crateChart.forEach {
var index = it.indexOf("[")
while (index != -1) {
if (index >= 0) {
val crateStack = index / 4
crateList[crateStack].addLast(it[index + 1].toString())
}
index = it.indexOf("[", index + 1)
}
}
return crateList
}
fun parseInstructions(input: List<String>): List<CrateMovement> {
val instructions = input.subList(input.indexOf("") + 1, input.size)
val regex = Regex("[^0-9 ]")
return instructions.map { regex.replace(it, "") }.map { it.trim().split(" ") }.map { CrateMovement(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
}
fun moveCrates(instructionList: List<CrateMovement>, crateList: MutableList<Deque<String>>, is9001: Boolean) {
instructionList.forEach { instruction ->
val crateStack = LinkedList<String>()
for(i in 1..instruction.numCrates) {
if(!is9001) {
crateList[instruction.toStack - 1].addFirst(crateList[instruction.fromStack - 1].removeFirst())
} else {
crateStack.addLast(crateList[instruction.fromStack - 1].removeFirst())
}
}
if(is9001) {
crateStack.reversed().forEach { crateList[instruction.toStack - 1].addFirst(it) }
}
}
}
fun part1(input: List<String>): String {
val crateList = parseCrates(input)
val instructionList = parseInstructions(input)
moveCrates(instructionList, crateList, false)
return crateList.joinToString("") { it.peekFirst() }
}
fun part2(input: List<String>): String {
val crateList = parseCrates(input)
val instructionList = parseInstructions(input)
moveCrates(instructionList, crateList, true)
return crateList.joinToString("") { it.peekFirst() }
}
// 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 | 1 | 0bac6b866e769d0ac6906456aefc58d4dd9688ad | 2,686 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} |
class Day14 {
private fun Point2d.next(map: Set<Point2d>, resting: Set<Point2d>) = listOf(
Point2d(x, y + 1),
Point2d(x - 1, y + 1),
Point2d(x + 1, y + 1)
).firstOrNull { it !in map && it !in resting }
private fun parse(input: List<String>): Set<Point2d>{
val ret = mutableSetOf<Point2d>()
input.map {
"(\\d+,\\d+)".toRegex().findAll(it).map {
val v = it.value.split(",")
Point2d(v.first().toInt(), v.last().toInt())
}.windowed(2,1).forEach { ret.addAll(it.first().lineTo(it.last())) }
}
return ret
}
fun part1(input: List<String>): Int {
val resting = mutableSetOf<Point2d>()
val initial = Point2d(500,0)
var current = initial
val map = parse(input)
val maxY = map.maxOf { it.y }
while (current.y != maxY) {
current = current.next(map, resting) ?: initial.also { resting.add(current) }
}
return resting.size
}
fun part2(input: List<String>): Int {
val resting = mutableSetOf<Point2d>()
val initial = Point2d(500,0)
var current = initial
val map = parse(input)
val floor = map.maxOf { it.y } + 2
while (initial !in resting) {
val next = current.next(map, resting)
current = when (next == null || next.y == floor) {
true -> initial.also { resting.add(current) }
else -> next
}
}
return resting.size
}
}
fun main(){
val testInput = readInput("Day14_test")
check(Day14().part1(testInput) == 24)
measureTimeMillisPrint {
val input = readInput("Day14")
println(Day14().part1(input))
println(Day14().part2(input))
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 1,812 | aoc-22-kotlin | Apache License 2.0 |
src/main/kotlin/leetcode/problem0018/FourSum.kt | ayukatawago | 456,312,186 | false | {"Kotlin": 266300, "Python": 1842} | package leetcode.problem0018
class FourSum {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val sortedNums = nums.sorted()
return kSum(sortedNums, target, 4)
}
private fun kSum(sortedNums: List<Int>, target: Int, k: Int): List<List<Int>> {
if (sortedNums.isEmpty()) {
return emptyList()
}
val answerMap = HashMap<Int, List<List<Int>>>()
sortedNums.forEachIndexed { index, num ->
if (answerMap[num] != null) {
return@forEachIndexed
}
val remainingNums = sortedNums.drop(index + 1)
val answerList = if (k == 3) {
twoSum(remainingNums, target - num)
} else {
kSum(remainingNums, target - num, k - 1)
}
answerMap[num] = answerList.map { getAnswer(num, it) }
}
return answerMap.flatMap { it.value }.distinct()
}
private fun getAnswer(num: Int, numList: List<Int>): List<Int> =
mutableListOf(num).also {
it.addAll(numList)
}
private fun twoSum(sortedNums: List<Int>, target: Int): List<List<Int>> {
if (sortedNums.size < 2) {
return emptyList()
}
val answerList = mutableListOf<List<Int>>()
var left = 0
var right = sortedNums.lastIndex
while (left < right) {
val leftValue = sortedNums[left]
val rightValue = sortedNums[right]
when {
leftValue + rightValue == target -> {
answerList.add(listOf(leftValue, rightValue))
left += 1
}
leftValue + rightValue < target -> left += 1
leftValue + rightValue > target -> right -= 1
}
}
return answerList
}
}
| 0 | Kotlin | 0 | 0 | f9602f2560a6c9102728ccbc5c1ff8fa421341b8 | 1,854 | leetcode-kotlin | MIT License |
src/Day10.kt | jamie23 | 573,156,415 | false | {"Kotlin": 19195} | fun main() {
fun solution(input: List<String>): Int {
val set = setOf(20, 60, 100, 140, 180, 220)
val result = mutableListOf<Int>()
var total = 1
var instructionIndex = 0
val instructions = input
.map { it.split(' ') }
.toInstructions()
var currentInstruction = instructions[instructionIndex]
for (i in 1..237) {
if (i in set) result.add(total * i)
// Part 2
if (((i - 1) % 40) in total - 1..total + 1) {
print("█")
} else {
print(".")
}
if (i % 40 == 0) println()
if (--currentInstruction.cycles <= 0) {
total += currentInstruction.value
currentInstruction = instructions[++instructionIndex]
}
}
return result.sum()
}
val testInput = readInput("Day10_test")
check(solution(testInput) == 13140)
val input = readInput("Day10")
println(solution(input))
}
fun List<List<String>>.toInstructions(): List<Instruction> =
map {
if (it.size == 2) {
val (a, b) = it
a.parseInstruction(b.toInt())
} else {
it.first().parseInstruction()
}
}
fun String.parseInstruction(value: Int = 0) = when (this) {
"addx" -> Instruction(cycles = 2, value)
"noop" -> Instruction(cycles = 1)
else -> error("Unsupported Instruction")
}
data class Instruction(
var cycles: Int,
val value: Int = 0
)
| 0 | Kotlin | 0 | 0 | cfd08064654baabea03f8bf31c3133214827289c | 1,553 | Aoc22 | Apache License 2.0 |
src/main/kotlin/com/tonnoz/adventofcode23/day17/Day17.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day17
import com.tonnoz.adventofcode23.utils.println
import com.tonnoz.adventofcode23.utils.readInput
import com.tonnoz.adventofcode23.utils.toListOfInts
import java.util.*
import kotlin.system.measureTimeMillis
object Day17 {
@JvmStatic
fun main(args: Array<String>) {
val city = "input17.txt".readInput().toListOfInts()
val timer1 = measureTimeMillis { calculateShortestPath(city, ::getCandidatesPt1).println() }
"Part 1: $timer1 ms\n".println()
val timer2 = measureTimeMillis { calculateShortestPath(city, ::getCandidatesPt2).println() }
"Part 2: $timer2 ms\n".println()
}
enum class Direction {
UP, DOWN, LEFT, RIGHT;
fun toChar() = when (this) {
UP -> '↑'
DOWN -> '↓'
LEFT -> '←'
RIGHT -> '→'
}
}
data class Block(val row: Int, val col: Int, var dir: Direction? = null, var minHeatLoss: Int = Int.MAX_VALUE) {
override fun equals(other: Any?): Boolean {
return when {
other == null -> false
other !is Block -> false
this === other -> true
row != other.row -> false
col != other.col -> false
dir != other.dir -> false
else -> true
}
}
override fun hashCode(): Int = 31 * row + col
}
private fun calculateShortestPath(city: List<List<Int>>, getCandidates: (Block, List<List<Int>>) -> List<Block>): Int {
val visited = mutableMapOf<Block, Int>()
val pq = PriorityQueue<Block>(compareBy { it.minHeatLoss })
val start = Block(0, 0, minHeatLoss = 0)
val end = Block(city.size - 1, city[0].size - 1)
pq.add(start)
while (pq.isNotEmpty()) {
val cur = pq.poll()
if (isExit(cur, city)) break
getCandidates(cur, city).filter { block ->
val currentHeatLoss = visited.getOrDefault(block, Int.MAX_VALUE)
currentHeatLoss > block.minHeatLoss
}.forEach { block ->
visited[block] = block.minHeatLoss
pq.add(block)
}
}
return Direction.entries.minOf { visited.getOrDefault(end.copy(dir = it), Int.MAX_VALUE) }
}
private fun isExit(block: Block, city: List<List<Int>>) = block.col == city[0].size && block.row == city.size
private fun getCandidatesPt1(block: Block, city: List<List<Int>>) = getCandidates(block, city, 1..3)
private fun getCandidatesPt2(block: Block, city: List<List<Int>>) = getCandidates(block, city, 1..10)
private fun getCandidates(block: Block, city: List<List<Int>>, range: IntRange): List<Block> {
return buildList {
when (block.dir) {
Direction.LEFT, Direction.RIGHT, null -> { //when null just pick a direction (left or right)
var shortestUP = block.minHeatLoss
var shortestDOWN = block.minHeatLoss
for (s in range) {
shortestUP += city.getOrNull(block.row - s)?.getOrNull(block.col) ?: 0
if (range.last == 3) add(Block(block.row - s, block.col, Direction.UP, shortestUP))
shortestDOWN += city.getOrNull(block.row + s)?.getOrNull(block.col) ?: 0
if (range.last == 3) add(Block(block.row + s, block.col, Direction.DOWN, shortestDOWN))
if (s >= 4) {
add(Block(block.row - s, block.col, Direction.UP, shortestUP))
add(Block(block.row + s, block.col, Direction.DOWN, shortestDOWN))
}
}
}
Direction.UP, Direction.DOWN -> {
var shortestLEFT = block.minHeatLoss
var shortestRIGHT = block.minHeatLoss
for (s in range) {
shortestLEFT += city.getOrNull(block.row)?.getOrNull(block.col - s) ?: 0
if (range.last == 3) add(Block(block.row, block.col - s, Direction.LEFT, shortestLEFT))
shortestRIGHT += city.getOrNull(block.row)?.getOrNull(block.col + s) ?: 0
if (range.last == 3) add(Block(block.row, block.col + s, Direction.RIGHT, shortestRIGHT))
if (s >= 4) {
add(Block(block.row, block.col - s, Direction.LEFT, shortestLEFT))
add(Block(block.row, block.col + s, Direction.RIGHT, shortestRIGHT))
}
}
}
}
}.filter { it.col in city[0].indices && it.row in city.indices }
}
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 4,219 | adventofcode23 | MIT License |
src/Day04.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | fun main() {
fun part1(input: List<String>): Int {
return input.map { it.split(",") }
.map { (first, second) -> first.toIntSet() to second.toIntSet() }
.count { it.first.containsAll(it.second) || it.second.containsAll(it.first) }
}
fun part2(input: List<String>): Int {
return input.map { it.split(",") }
.map { (first, second) -> first.toIntSet() to second.toIntSet() }
.count { (it.first intersect it.second).isNotEmpty() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun String.toIntSet(): Set<Int> {
val (start, end) = this.split("-")
return (start.toInt() .. end.toInt()).toSet()
}
| 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 918 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/jball/aoc2022/day09/Day09.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day09
import de.jball.aoc2022.Day
import kotlin.math.abs
import kotlin.math.sign
class Day09(test: Boolean = false) : Day<Int>(test, 88, 36) {
private val directions = input.map { parseDirectionLine(it) }
private fun parseDirectionLine(directionLine: String): Pair<Direction, Int> {
val blah = directionLine.split(" ")
return Pair(parseDirection(blah[0]), blah[1].toInt())
}
private fun parseDirection(directionString: String): Direction {
return when (directionString) {
"U" -> Direction.UP
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
"D" -> Direction.DOWN
else -> {
error("Should not happen")
}
}
}
override fun part1(): Int {
val rope = Rope(2)
return directions.map { rope.move(it.first, it.second) }
.flatten().toSet().size
}
override fun part2(): Int {
val rope = Rope(10)
return directions.map { rope.move(it.first, it.second) }
.flatten().toSet().size
}
}
enum class Direction(val x: Int, val y: Int) {
RIGHT(1, 0), LEFT(-1, 0), DOWN(0, -1), UP(0, 1)
}
class Rope(length: Int) {
private val knots = MutableList(length) { Pair(0,0) }
/**
* @return tail-trail of that movement
*/
fun move(direction: Direction, steps: Int): List<Pair<Int, Int>> {
val tailTrail = mutableListOf<Pair<Int, Int>>()
repeat(steps) {
val head = knots[0]
knots[0] = Pair(head.first + direction.x, head.second + direction.y)
followHead()
tailTrail.add(knots.last())
}
return tailTrail
}
private fun followHead() {
for (i in 1 until knots.size) {
val leader = knots[i-1]
val knot = knots[i]
knots[i] = if (abs(leader.first - knot.first) > 1 || abs(leader.second - knot.second) > 1) {
Pair(
reduceDistanceIfAboveLength(leader.first, knot.first),
reduceDistanceIfAboveLength(leader.second, knot.second)
)
} else {
knot
}
}
}
private fun reduceDistanceIfAboveLength(a: Int, b: Int) = b + (a - b).sign
}
fun main() {
Day09().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 2,350 | aoc-2022 | Apache License 2.0 |
day04/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import Constants.Companion.MINUTES_IN_AN_HOUR
import java.io.File
import java.lang.Double.NEGATIVE_INFINITY
fun main() {
val guardData = extractGuardData(readInputFile())
println("Part I: the solution is ${solvePartI(guardData)}.")
println("Part II: the solution is ${solvePartII(guardData)}.")
}
fun readInputFile(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun extractGuardData(input: List<String>): Map<Int, List<BooleanArray>> {
val result = HashMap<Int, MutableList<BooleanArray>>()
val sortedEntries = extractAndSortEntries(input)
var currentGuardFirstRow = 0
while (currentGuardFirstRow < sortedEntries.size) {
val guardId = extractGuardId(sortedEntries[currentGuardFirstRow].text)
val nextGuardFirstRow = calculateNextGuardFirstRow(currentGuardFirstRow, sortedEntries)
val isSleepingDataForShift = calculateIsSleepingDataForShift(currentGuardFirstRow, nextGuardFirstRow, sortedEntries)
if (guardId !in result) {
result[guardId] = mutableListOf(isSleepingDataForShift)
} else {
result[guardId]!!.add(isSleepingDataForShift)
}
currentGuardFirstRow = nextGuardFirstRow
}
return result
}
fun extractAndSortEntries(input: List<String>): List<Entry> {
val entries = mutableListOf<Entry>()
input.forEach { line ->
val regex = "\\[(.+)] (.+)".toRegex()
val (dateAsString, text) = regex.matchEntire(line)!!.destructured
entries.add(Entry(dateAsString, text))
}
return entries.sortedWith(compareBy { it.dateAsString })
}
fun calculateNextGuardFirstRow(rowWithGuardId: Int, sortedEntries: List<Entry>): Int {
var result = rowWithGuardId + 1
while ((result < sortedEntries.size - 1) and ("#" !in sortedEntries[result].text)) {
result++
}
if (result == sortedEntries.size - 1) {
result++
}
return result
}
fun extractGuardId(text: String): Int {
return text.split(" ")[1].replace("#".toRegex(), "").toInt()
}
fun calculateIsSleepingDataForShift(
currentGuardFirstRow: Int,
nextGuardFirstRow: Int,
sortedEntries: List<Entry>): BooleanArray {
val result = BooleanArray(MINUTES_IN_AN_HOUR)
var previousMinuteSleepStatusUpdates = 0
var isAsleep = false
for (row in (currentGuardFirstRow + 1) until nextGuardFirstRow) {
val entry = sortedEntries[row]
val nextMinuteSleepStatusUpdates =
entry.dateAsString.substring(entry.dateAsString.length - 2, entry.dateAsString.length).toInt()
for (minute in previousMinuteSleepStatusUpdates until nextMinuteSleepStatusUpdates) {
result[minute] = isAsleep
}
isAsleep = !isAsleep
previousMinuteSleepStatusUpdates = nextMinuteSleepStatusUpdates
}
for (minute in previousMinuteSleepStatusUpdates until MINUTES_IN_AN_HOUR) {
result[minute] = isAsleep
}
return result
}
fun solvePartI(guardData: Map<Int, List<BooleanArray>>): Int {
val guardId = calculateMostAsleepGuardId(guardData)
val minute = calculateDataForMostShiftsAsleepForGuard(guardData[guardId]!!).minute
return guardId * minute
}
fun calculateMostAsleepGuardId(guardData: Map<Int, List<BooleanArray>>): Int {
var maxNumberOfMinutesAsleep = 0
var result = 0
guardData.forEach { (guardId, isSleepingDataAllShifts) ->
var numberOfMinutesAsleep = 0
isSleepingDataAllShifts.forEach { isSleepingDataForShift ->
numberOfMinutesAsleep += isSleepingDataForShift.map(Boolean::toInt).sum()
}
if (numberOfMinutesAsleep > maxNumberOfMinutesAsleep) {
result = guardId
maxNumberOfMinutesAsleep = numberOfMinutesAsleep
}
}
return result
}
fun calculateDataForMostShiftsAsleepForGuard(isSleepingData: List<BooleanArray>): DataForMostShiftsAsleepForGuard {
val numberOfDaysAsleepByMinute = IntArray(MINUTES_IN_AN_HOUR)
isSleepingData.forEach { isSleepingDataForShift ->
for (minute in 0 until MINUTES_IN_AN_HOUR) {
if (isSleepingDataForShift[minute]) {
numberOfDaysAsleepByMinute[minute]++
}
}
}
return DataForMostShiftsAsleepForGuard(numberOfDaysAsleepByMinute.indexOf(numberOfDaysAsleepByMinute.max()!!),
numberOfDaysAsleepByMinute.max()!!)
}
fun solvePartII(guardData: Map<Int, List<BooleanArray>>): Int {
var guardIdWithMaxShiftsAsleepSameMinute = -1
var maxShiftsAsleepSameMinute = -1
var minuteWithMaxShiftsAsleep = -1
guardData.keys.forEach { guardId ->
val (minuteForGuard, numberOfShiftsForGuard) = calculateDataForMostShiftsAsleepForGuard(guardData[guardId]!!)
if (numberOfShiftsForGuard > maxShiftsAsleepSameMinute) {
guardIdWithMaxShiftsAsleepSameMinute = guardId
minuteWithMaxShiftsAsleep = minuteForGuard
maxShiftsAsleepSameMinute = numberOfShiftsForGuard
}
}
return guardIdWithMaxShiftsAsleepSameMinute * minuteWithMaxShiftsAsleep
}
data class Entry(val dateAsString: String, val text: String)
data class DataForMostShiftsAsleepForGuard(val minute: Int, val numberOfShifts: Int)
class Constants {
companion object {
const val MINUTES_IN_AN_HOUR = 60
}
}
fun Boolean.toInt() = if (this) 1 else 0
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 5,405 | AdventOfCode2018 | MIT License |
src/day09/Day09.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day09
import readInput
import kotlin.math.absoluteValue
import kotlin.math.sign
const val day = "09"
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val states = input.executeMoves(2)
return states.countLastKnotPositions()
}
fun calculatePart2Score(input: List<String>): Int {
val states = input.executeMoves(10)
return states.countLastKnotPositions()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val testInput2 = readInput("/day$day/Day${day}_test2")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1Points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1Points")
check(part1TestPoints == 13)
val part2TestPoints = calculatePart2Score(testInput2)
val part2Points = calculatePart2Score(input)
println("Part2 test points: $part2TestPoints")
println("Part2 points: $part2Points")
check(part2TestPoints == 36)
}
fun List<String>.executeMoves(numKnots: Int): List<List<Coordinate>> {
val moves = map { it.split(" ") }
.flatMap { (move, amount) -> List(amount.toInt()) { move } }
val states = moves.runningFold(List(numKnots) { Coordinate(0, 0) }) { coordinates, move ->
coordinates.drop(1)
.runningFold(coordinates.first().applyMove(move)) { previous, current -> current.follow(previous) }
}
return states
}
fun List<List<Coordinate>>.countLastKnotPositions(): Int = map { it.last() }.toSet().size
data class Coordinate(val x: Int, val y: Int) {
fun applyMove(direction: String): Coordinate {
return when (direction) {
"R" -> copy(x = x + 1)
"L" -> copy(x = x - 1)
"U" -> copy(y = y + 1)
"D" -> copy(y = y - 1)
else -> error("Unknown direction $direction")
}
}
fun follow(head: Coordinate): Coordinate {
val deltaX = head.x - x
val deltaY = head.y - y
if (deltaX.absoluteValue <= 1 && deltaY.absoluteValue <= 1) {
return this // don't move, no need
}
return copy(x = x + deltaX.sign, y = y + deltaY.sign)
}
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 2,335 | advent-of-code-22-kotlin | Apache License 2.0 |
src/Day04.kt | derivz | 575,340,267 | false | {"Kotlin": 6141} | fun main() {
fun part1(lines: List<String>): Int {
return lines.map { line ->
val (left, right) = line.split(",")
val (leftStart, leftEnd) = left.split("-").map { it.toInt() }
val (rightStart, rightEnd) = right.split("-").map { it.toInt() }
if ((leftStart <= rightStart && rightEnd <= leftEnd) || (rightStart <= leftStart && leftEnd <= rightEnd)) {
1
} else {
0
}
}.sum()
}
fun part2(lines: List<String>): Int {
return lines.map { line ->
val (left, right) = line.split(",")
val (leftStart, leftEnd) = left.split("-").map { it.toInt() }
val (rightStart, rightEnd) = right.split("-").map { it.toInt() }
if (
(rightStart in leftStart..leftEnd)
|| (rightEnd in leftStart..leftEnd)
|| (leftStart in rightStart..rightEnd)
) {
1
} else {
0
}
}.sum()
}
val lines = readLines("Day04")
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | 24da2ff43dc3878c4e025f5b737dca31913f40a5 | 1,153 | AoC2022.kt | Apache License 2.0 |
src/Day03_RucksackReorganization.kt | raipc | 574,467,742 | false | {"Kotlin": 9511} | fun main() {
checkAndSolve("Day03", 157) { calculateSumOfCommonTypePriorities(it) }
checkAndSolve("Day03", 70) { calculateSumOfCommonAcrossGroupsOfThree(it) }
}
private fun calculateSumOfCommonTypePriorities(lines: List<String>) =
lines.sumOf { calculatePriority(findCommonType(it)) }
private fun uniqueCharCodesInString(content: String, from: Int = 0, to: Int = content.length): HashSet<Int> =
(from until to).mapTo(HashSet()) { content[it].code }
private fun findCommonType(content: String): Char {
val usedChars = uniqueCharCodesInString(content, 0, content.length / 2)
for (i in content.length / 2 until content.length) {
if (usedChars.contains(content[i].code)) {
return content[i]
}
}
throw IllegalStateException("Must have found common type")
}
private fun calculatePriority(charValue: Char): Int =
when (charValue) {
in 'a'..'z' -> charValue - 'a' + 1
in 'A'..'Z' -> charValue - 'A' + 27
else -> throw IllegalArgumentException()
}
private fun calculateSumOfCommonAcrossGroupsOfThree(lines: List<String>): Int = (lines.indices step 3)
.sumOf { calculatePriority(calculateCommonAcrossGroup(lines[it], lines[it +1], lines[it +2])) }
private fun calculateCommonAcrossGroup(first: String, second: String, third: String): Char {
val charsFromFirst = uniqueCharCodesInString(first)
val charsFromSecond = uniqueCharCodesInString(second)
return third.find { charsFromFirst.contains(it.code) && charsFromSecond.contains(it.code) }
?: throw IllegalStateException("Common symbol for three strings not found")
} | 0 | Kotlin | 0 | 0 | 9068c21dc0acb5e1009652b4a074432000540d71 | 1,629 | adventofcode22 | Apache License 2.0 |
src/Day05.kt | a2xchip | 573,197,744 | false | {"Kotlin": 37206} | import java.io.File
class Stacks(val stacks: List<ArrayDeque<Char>>) {
fun move(action: Action) {
repeat(action.times) {
val c = stacks[action.from].removeFirst()
stacks[action.to].addFirst(c)
}
}
fun moveBatched(action: Action) {
val batch = mutableListOf<Char>()
repeat(action.times) {
batch.add(stacks[action.from].removeFirst())
}
for (i in batch.reversed()) {
stacks[action.to].addFirst(i)
}
}
fun getCreatesOnTop(): String {
val resultList = mutableListOf<Char>()
for (s in this.stacks) {
if (s.isEmpty()) continue
resultList.add(s.first())
}
return resultList.joinToString("")
}
companion object {
fun create(input: String): Stacks {
val rows = input.split("\n").dropLast(1)
val crateRows = rows.slice(0..rows.lastIndex).reversed()
val numberOfColumns = rows.maxOf { it.length }
val indices = (0..numberOfColumns step 4).map { it + 1 }
val listOfStacks = MutableList(numberOfColumns) { ArrayDeque<Char>() }
for ((k, position) in indices.withIndex()) {
for (row in crateRows) {
if (row.length - 1 > position && row[position].isLetter()) listOfStacks[k].addFirst(row[position])
}
}
return Stacks(listOfStacks)
}
}
}
data class Action(val from: Int, val to: Int, val times: Int) {
companion object {
fun from(line: String): Action {
val lineSplit = line.split(" ")
return Action(lineSplit[3].toInt() - 1, lineSplit[5].toInt() - 1, lineSplit[1].toInt())
}
}
}
fun main() {
fun readInput(name: String) = File("src", "$name.txt").readText().split("\n\n")
fun part1(input: List<String>): String {
val (stacksString, listOfActions) = input
val stacks = Stacks.create(stacksString)
listOfActions.split("\n").forEach { stacks.move(Action.from(it)) }
return stacks.getCreatesOnTop()
}
fun part2(input: List<String>): String {
val (stacksString, moves) = input
val stacks = Stacks.create(stacksString)
moves.split("\n").forEach {
stacks.moveBatched(Action.from(it))
}
return stacks.getCreatesOnTop()
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
println("Test 1 - ${part1(testInput)}")
println("Test 2 - ${part2(testInput)}")
val input = readInput("Day05")
println("Part 1 - ${part1(input)}")
println("Part 2 - ${part2(input)}")
check(part1(input) == "QMBMJDFTD")
check(part2(input) == "NBTVTJNFJ")
}
| 0 | Kotlin | 0 | 2 | 19a97260db00f9e0c87cd06af515cb872d92f50b | 2,823 | kotlin-advent-of-code-22 | Apache License 2.0 |
src/Day03.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | fun main() {
fun priority(c: Char): Int = if (c in 'A'..'Z') c - 'A' + 27 else c - 'a' + 1
fun countRepetitions(line: String): Int {
val n = line.length
val second = line.subSequence(n / 2, n).toSet()
return line.subSequence(0, n / 2).toSet().filter { it in second }.sumOf { priority(it) }
}
fun part1(input: List<String>): Int {
return input.sumOf { countRepetitions(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { it.map { it2 -> it2.toSet() }.reduce(Set<Char>::intersect).sumOf { c -> priority(c) } }
}
// 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 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 897 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day21.kt | nordberg | 573,769,081 | false | {"Kotlin": 47470} | import kotlin.math.max
fun main() {
fun getOperation(op: Char): (Long, Long) -> Long {
return when (op) {
'/' -> { x: Long, y: Long -> x / y }
'*' -> { x: Long, y: Long -> x * y }
'+' -> { x: Long, y: Long -> x + y }
'-' -> { x: Long, y: Long -> x - y }
else -> throw IllegalStateException("Got $op as operation")
}
}
fun part1(input: List<String>): Long {
val monkeysWithNums = mutableMapOf<String, Long?>()
val monkeyNames = mutableSetOf<String>()
input.forEach {
val (monkeyName, monkeyOp) = it.split(": ")
monkeyNames.add(monkeyName)
if (monkeyOp.first().isDigit()) {
monkeysWithNums[monkeyName] = monkeyOp.toLong()
}
}
var sizeForMonkeysWithNums = monkeysWithNums.keys.size
while (monkeysWithNums.keys != monkeyNames) {
println("${monkeysWithNums.keys.size}/${monkeyNames.size} ")
input.forEach {
val (monkeyName, monkeyOp) = it.split(": ")
val operation = monkeyOp.split(" ")
if (operation.size == 3) {
if (monkeysWithNums.containsKey(operation[0]) && monkeysWithNums.containsKey(operation[2])) {
val applyOperation = getOperation(operation[1].first())
val numForMonkey1 = monkeysWithNums[operation[0]]!!
val numForMonkey2 = monkeysWithNums[operation[2]]!!
val numForNewMonkey = applyOperation(numForMonkey1, numForMonkey2)
monkeysWithNums[monkeyName] = numForNewMonkey
}
}
}
check(monkeysWithNums.keys.size > sizeForMonkeysWithNums) {
"Monkey with nums stopped growing"
}
}
println(monkeysWithNums)
return 5
}
fun part2(input: List<String>): Long {
return 5
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day21")
println(part1(input))
//println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3de1e2b0d54dcf34a35279ba47d848319e99ab6b | 2,265 | aoc-2022 | Apache License 2.0 |
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day22.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwenty
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day22 : Day<Long> {
private data class Player(val name: String, val deck: List<Int>)
private data class Round(val players: List<Player>)
private data class RoundResult(val round: Round, val winner: Player? = null)
private data class GameResult(val winner: Player?)
private val initialRound: Round =
readDayInput()
.split("\n\n")
.map { it.lines() }
.map { playerDeck ->
Player(
name = playerDeck.first().replace(":", ""),
deck = playerDeck.drop(1).map { it.toInt() }
)
}
.let { players ->
Round(players = players)
}
private fun Player.play(): Pair<Int?, Player> {
return when (val card = deck.firstOrNull()) {
null -> null to this
else -> card to copy(deck = deck.drop(1))
}
}
private val Player.score: Long
get() = deck.reversed().mapIndexed { index, card -> (index + 1) * card.toLong() }.sum()
private tailrec fun RoundResult.findGameResult(): GameResult {
if (round.players.count { player -> player.deck.isEmpty() } == round.players.size - 1)
return GameResult(winner = winner)
return round.playRound(recursive = false).findGameResult()
}
private fun Round.playRound(recursive: Boolean): RoundResult {
val decksAfterPlay = players.map { player -> player.play() }
val enoughCardsToRecurse = decksAfterPlay.all { (card, player) ->
card != null && player.deck.size >= card
}
val winner = if (recursive && enoughCardsToRecurse) {
val recursiveRound = Round(players = decksAfterPlay.map { (card, player) ->
player.copy(deck = player.deck.take(card!!.toInt()))
})
RoundResult(round = recursiveRound).findRecursiveGameResult().winner!!
} else {
decksAfterPlay.maxByOrNull { (hand, _) -> hand ?: Int.MIN_VALUE }!!.second
}
val cardsInPlay: List<Int> = decksAfterPlay
.sortedBy { (_, player) -> if (player.name == winner.name) Int.MIN_VALUE else Int.MAX_VALUE }
.mapNotNull { (card, _) -> card }
val playersNewDeck = decksAfterPlay
.map { (_, player) -> player }
.map { state ->
when (state.name) {
winner.name -> state.copy(deck = state.deck + cardsInPlay)
else -> state
}
}
val winnerNewDeck = playersNewDeck.first { it.name == winner.name }
return RoundResult(
winner = winnerNewDeck,
round = copy(players = playersNewDeck)
)
}
private tailrec fun RoundResult.findRecursiveGameResult(previousRoundHashes: List<Int> = emptyList()): GameResult {
if (hashCode() in previousRoundHashes)
return GameResult(winner = round.players.first { player -> player.name == "Player 1" })
val hasAPlayerWon = round.players.count { player -> player.deck.isEmpty() } == round.players.size - 1
if (hasAPlayerWon) return GameResult(winner = winner)
return round.playRound(recursive = true)
.findRecursiveGameResult(previousRoundHashes + hashCode())
}
private fun Round.print() {
players.forEach { player ->
println("${player.name}'s deck: ${player.deck}")
}
println()
}
override fun step1(): Long {
return RoundResult(round = initialRound).findGameResult().winner!!.score
}
override fun step2(): Long {
return RoundResult(round = initialRound).findRecursiveGameResult().winner!!.score
}
override val expectedStep1: Long = 32598
override val expectedStep2: Long = 35836
} | 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 3,950 | adventofcode | Apache License 2.0 |
src/Day13.kt | phoenixli | 574,035,552 | false | {"Kotlin": 29419} | import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
var pairIdx = 0
var idxSum = 0
input.chunked(3).forEach{
pairIdx++
val isInOrder = isInOrder(toList(it[0]), toList(it[1]))
if (isInOrder) {
idxSum += pairIdx
}
}
return idxSum
}
fun part2(input: List<String>): Int {
val filteredList = input.filter{ it.isNotEmpty() }.toMutableList()
filteredList.add("[[2]]")
filteredList.add("[[6]]")
val sortedList = filteredList.sortedWith{ a, b ->
compare(toList(a), toList(b))
}.asReversed()
return (sortedList.indexOf("[[2]]") + 1) * (sortedList.indexOf("[[6]]") + 1)
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day13_test")
// println(part2(testInput))
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
fun isInOrder(leftList: List<*>, rightList: List<*>): Boolean {
return compare(leftList, rightList) > 0
}
fun compare(left: Any?, right: Any?): Int {
// println("left: " + left)
// println("right: " + right)
if (left is Int && right is Int) {
if (left > right) {
return -1
}
if (left < right) {
return 1
}
return 0
}
if (left is Int && right is List<*>) {
return compare(listOf(left), right)
}
if (left is List<*> && right is Int) {
return compare(left, listOf(right))
}
if (left is List<*> && right is List<*>) {
val minSize = min(left.size, right.size)
for (i in 0 until minSize) {
val result = compare(left[i], right[i])
if (result != 0) {
return result
}
}
return -left.size.compareTo(right.size)
}
return 0
}
fun toList(input: String): List<Any> {
val grandList = mutableListOf<Any>()
val parsedInput = input.drop(1).dropLast(1).split(",")
val tmpStack: ArrayDeque<MutableList<Any>> = ArrayDeque()
tmpStack.addLast(grandList)
parsedInput.forEach{
var stripped = it
while (stripped.startsWith('[')) {
val parentList = tmpStack.removeLast()
val childList = mutableListOf<Any>()
parentList.add(childList)
tmpStack.addLast(parentList)
tmpStack.addLast(childList)
stripped = stripped.drop(1)
}
if (stripped.endsWith(']')) {
val intString = stripped.substring(0, stripped.indexOf(']'))
if (intString.isNotEmpty()) {
val list = tmpStack.removeLast()
list.add(intString.toInt())
tmpStack.addLast(list)
}
} else {
if (stripped.isNotEmpty()) {
val list = tmpStack.removeLast()
list.add(stripped.toInt())
tmpStack.addLast(list)
}
}
while (stripped.endsWith("]")) {
tmpStack.removeLast()
stripped = stripped.dropLast(1)
}
}
return grandList
} | 0 | Kotlin | 0 | 0 | 5f993c7b3c3f518d4ea926a792767a1381349d75 | 3,209 | Advent-of-Code-2022 | Apache License 2.0 |
2015/Day05/src/main/kotlin/Main.kt | mcrispim | 658,165,735 | false | null | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
// Rule 1
// It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
fun String.rule1Nice(): Boolean = this.split(Regex("(a|e|i|o|u)")).size > 3
// Rule 2
// It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
fun String.rule2Nice(): Boolean = Regex(".*(.)\\1{1,}.*").matches(this)
// Rule 3
// It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements.
fun String.rule3Nice(): Boolean = this.split(Regex("(ab|cd|pq|xy)")).size <= 1
var nices = 0
for (string in input) {
if (string.rule1Nice() && string.rule2Nice() && string.rule3Nice()) {
nices++
// println("=> $string - nice")
} else {
// println("=> $string - naughty")
}
}
return nices
}
fun part2(input: List<String>): Int {
// Rule 1
// It contains a pair of any two letters that appears at least twice in the string without overlapping,
// like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps).
fun String.rule1Nice(): Boolean = Regex(".*(.)(.).*\\1\\2.*").matches(this)
// Rule 2
// It contains at least one letter which repeats with exactly one letter between them, like xyx,
// abcdefeghi (efe), or even aaa.
fun String.rule2Nice(): Boolean = Regex(".*(.).\\1.*").matches(this)
var nices = 0
for (string in input) {
if (string.rule1Nice() && string.rule2Nice()) {
nices++
}
}
return nices
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == 2)
check(part2(testInput) == 0)
val input = readInput("Day05_data")
println("Part 1 answer: ${part1(input)}")
println("Part 2 answer: ${part2(input)}")
}
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
| 0 | Kotlin | 0 | 0 | 2f4be35e78a8a56fd1e078858f4965886dfcd7fd | 2,282 | AdventOfCode | MIT License |
src/main/kotlin/com/groundsfam/advent/y2021/d03/Day03.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d03
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
// most common bit of position i of all nums
fun gammaRate(binaryNums: List<String>): String {
val n = binaryNums.size
return binaryNums[0].indices.joinToString("") { i ->
if (binaryNums.count { it[i] == '0' } > n / 2) "0"
else "1"
}
}
fun powerConsumption(binaryNums: List<String>): Int {
val gamma = gammaRate(binaryNums)
val epsilon = gamma.indices.joinToString("") { i ->
if (gamma[i] == '0') "1"
else "0"
}
return gamma.toInt(2) * epsilon.toInt(2)
}
fun gasRating(binaryNums: List<String>, keepMostCommon: Boolean): Int {
var i = 0
val nums = binaryNums.toMutableList()
while (nums.size > 1) {
val zeroesCount = nums.count { it[i] == '0' }
val commonBit = if (zeroesCount > nums.size / 2) 0 else 1
val requiredBit = '0' + if (keepMostCommon) commonBit else 1 - commonBit
nums.removeAll { it[i] != requiredBit }
i++
}
return nums.first().toInt(2)
}
fun lifeSupportRating(binaryNums: List<String>): Int {
val oxygen = gasRating(binaryNums, true)
val co2 = gasRating(binaryNums, false)
return oxygen * co2
}
fun main() = timed {
val binaryNums = (DATAPATH / "2021/day03.txt").useLines { lines ->
lines.toList()
}
println("Part one: ${powerConsumption(binaryNums)}")
println("Part two: ${lifeSupportRating(binaryNums)}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,557 | advent-of-code | MIT License |
src/Day05.kt | arnoutvw | 572,860,930 | false | {"Kotlin": 33036} | import java.util.*
import kotlin.collections.ArrayList
fun main() {
fun fillStacks(it: String, buckets: TreeMap<Int, LinkedList<String>>) {
val chunkes = it.chunked(4)
chunkes.forEachIndexed { index, element ->
val letter = element.substring(1..1)
if (letter.isNotBlank() && letter.toIntOrNull() == null) {
val stack = buckets.computeIfAbsent(index + 1) { LinkedList<String>() }
stack.add(letter)
}
}
}
fun part1(input: List<String>): String {
val buckets = TreeMap<Int, LinkedList<String>>()
var moving = false
input.forEach {
if (moving) {
val inputLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
val (move, from, to) = inputLineRegex
.matchEntire(it)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $it")
for (x in 0 until move.toInt()) {
buckets.get(to.toInt())?.addFirst(buckets.get(from.toInt())?.remove())
}
} else {
if (it.isBlank()) {
moving = true
} else {
fillStacks(it, buckets)
}
}
}
return buckets.values.joinToString("") { it.peek() }
}
fun part2(input: List<String>): String {
val buckets = TreeMap<Int, LinkedList<String>>()
var moving = false
input.forEach {
if (moving) {
val inputLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
val (move, from, to) = inputLineRegex
.matchEntire(it)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $it")
val removeList = ArrayList<String>()
for (x in 0 until move.toInt()) {
val element = buckets.get(from.toInt())?.remove()
removeList.add(element.orEmpty())
}
buckets.get(to.toInt())?.addAll(0, removeList)
} else {
if (it.isBlank()) {
moving = true
} else {
fillStacks(it, buckets)
}
}
}
return buckets.values.joinToString("") { it.peek() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
println("Test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
println("Waarde")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4 | 2,841 | aoc-2022-in-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.