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/Day04.kt | Nplu5 | 572,211,950 | false | {"Kotlin": 15289} | fun main() {
fun createSections(input: List<String>) = input.flatMap { line -> line.split(",") }
.map { sectionString -> IntRange.fromSectionString(sectionString) }
.windowed(2, 2)
.map { Sections(it) }
fun part1(input: List<String>): Int {
return createSections(input)
.filter { sections -> sections.areFullyOverlapping() }
.size
}
fun part2(input: List<String>): Int {
return createSections(input)
.filter { sections -> sections.areOverlapping() }
.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun IntRange.Companion.fromSectionString(sectionString: String): IntRange{
return IntRange(
sectionString.split("-")[0].toInt(),
sectionString.split("-")[1].toInt()
)
}
class Sections(sections: List<IntRange>){
private val firstSection: IntRange = sections[0]
private val secondSection: IntRange = sections[1]
init {
if (sections.size != 2){
throw IllegalArgumentException("Sections should only contain two separate sections. Contained: $sections")
}
}
fun areFullyOverlapping(): Boolean{
return firstSection.fullyContains(secondSection) || secondSection.fullyContains(firstSection)
}
fun areOverlapping(): Boolean {
return !(firstSection.last < secondSection.first || secondSection.last < firstSection.first)
}
private fun IntRange.fullyContains(range: IntRange): Boolean{
return contains(range.first) && contains(range.last)
}
}
| 0 | Kotlin | 0 | 0 | a9d228029f31ca281bd7e4c7eab03e20b49b3b1c | 1,800 | advent-of-code-2022 | Apache License 2.0 |
src/day12/Day12.kt | EdwinChang24 | 572,839,052 | false | {"Kotlin": 20838} | package day12
import readInput
fun main() {
part1()
part2()
}
fun part1() = common { s, _ -> setOf(s) }
fun part2() = common { _, aSet -> aSet }
fun common(startingPoints: (s: Pair<Int, Int>, aSet: Set<Pair<Int, Int>>) -> Set<Pair<Int, Int>>) {
val input = readInput(12)
val grid = input.map {
it.map { c ->
when (c) {
'S' -> -1
'E' -> -2
else -> c - 'a'
}
}.toMutableList()
}
operator fun <T> List<List<T>>.get(pair: Pair<Int, Int>) = get(pair.second)[pair.first]
operator fun <T> List<MutableList<T>>.set(pair: Pair<Int, Int>, value: T) {
get(pair.second)[pair.first] = value
}
var s: Pair<Int, Int>? = null
var e: Pair<Int, Int>? = null
val aSet = mutableSetOf<Pair<Int, Int>>()
grid.forEachIndexed { y, ints ->
ints.forEachIndexed { x, i ->
if (i == 0) aSet += x to y
if (i == -1) s = (x to y).also { grid[it] = 0 } else if (i == -2) e = (x to y).also { grid[it] = 26 }
}
}
fun Pair<Int, Int>.surrounding() = listOf(
first + 1 to second,
first - 1 to second,
first to second + 1,
first to second - 1
).filter { it.first in 0..grid[0].lastIndex && it.second in 0..grid.lastIndex }.toSet()
var min = Int.MAX_VALUE
for (start in startingPoints(s!!, aSet)) {
val stepsGrid: List<MutableList<Int?>> = grid.map { it.map { null }.toMutableList() }
var justVisited = setOf(start)
var steps = 0
var actuallyWorked = true
while (true) {
if (e in justVisited) break
val newJustVisited = mutableSetOf<Pair<Int, Int>>()
actuallyWorked = false
for (visited in justVisited) {
for (new in visited.surrounding().filter { stepsGrid[it] == null && grid[it] - grid[visited] <= 1 }) {
stepsGrid[new] = steps
newJustVisited += new
actuallyWorked = true
}
}
if (!actuallyWorked) break
justVisited = newJustVisited
steps++
}
if (actuallyWorked) min = minOf(min, steps)
}
println(min)
}
| 0 | Kotlin | 0 | 0 | e9e187dff7f5aa342eb207dc2473610dd001add3 | 2,264 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | trosendo | 572,903,458 | false | {"Kotlin": 26100} | fun main() {
fun getElfZones(elfPair: String): Pair<Sequence<Int>, Sequence<Int>> {
val (elf1, elf2) = elfPair.split(",").map { it.split("-").map { it.toInt() } }
val elf1Zones = generateSequence(elf1[0]) { if (it < elf1[1]) it + 1 else null }
val elf2Zones = generateSequence(elf2[0]) { if (it < elf2[1]) it + 1 else null }
return elf1Zones to elf2Zones
}
fun part1(input: List<String>) = input.map { elfPair ->
val (elf1Zones, elf2Zones) = getElfZones(elfPair)
if (elf1Zones.toList().containsAll(elf2Zones.toList()) || elf2Zones.toList().containsAll(elf1Zones.toList())) 1
else 0
}.sum()
fun part2(input: List<String>) = input.map { elfPair ->
val (elf1Zones, elf2Zones) = getElfZones(elfPair)
if(elf1Zones.toList().any { elf2Zones.contains(it) } || elf2Zones.toList().any { elf1Zones.contains(it) }) 1 else 0
}.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInputAsList("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInputAsList("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ea66a6f6179dc131a73f884c10acf3eef8e66a43 | 1,204 | AoC-2022 | Apache License 2.0 |
src/Day13.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): List<Packet> =
input.filter { it.isNotEmpty() }.map { Packet.parse(it) }
fun part1(input: List<String>): Int {
val packets = parse(input)
var sum = 0
packets.chunked(2).forEachIndexed { index, pair ->
if (pair[0] < pair[1]) {
sum += index + 1
}
}
return sum
}
fun part2(input: List<String>): Int {
val packets = parse(input)
val divider1 = Packet.parse("[[2]]")
val divider2 = Packet.parse("[[6]]")
val sorted = (packets + divider1 + divider2).sorted()
val i = sorted.indexOf(divider1) + 1
val j = sorted.indexOf(divider2) + 1
return i * j
}
val input = readInput("input13")
println(part1(input))
println(part2(input))
}
sealed interface Packet : Comparable<Packet> {
data class IntPacket(val value: Int) : Packet {
override fun compareTo(other: Packet): Int = when (other) {
is IntPacket -> value compareTo other.value
is ListPacket -> ListPacket(listOf(this)) compareTo other
}
}
data class ListPacket(val packets: List<Packet>) : Packet {
override fun compareTo(other: Packet): Int = when (other) {
is IntPacket -> compareTo(ListPacket(listOf(other)))
is ListPacket -> {
val zipped = packets zip other.packets
val comparisons = zipped.map { it.first compareTo it.second }
comparisons.firstOrNull { it != 0 } ?: (packets.size compareTo other.packets.size)
}
}
}
companion object {
fun parse(input: String): Packet {
if (input.all { it.isDigit() }) {
return IntPacket(input.toInt())
}
if (input == "[]") {
return ListPacket(emptyList())
}
val cleanInput = input.removeSurrounding("[", "]")
val packets = mutableListOf<Packet>()
var current = 0
var level = 0
cleanInput.forEachIndexed { index, c ->
when (c) {
'[' -> level++
']' -> level--
',' -> if (level == 0) {
packets += parse(cleanInput.substring(current, index))
current = index + 1
}
}
}
packets += parse(cleanInput.substring(current))
return ListPacket(packets)
}
}
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 2,575 | advent-of-code-2022 | Apache License 2.0 |
src/Day12/day12.kt | NST-d | 573,224,214 | false | null | package Day12
import utils.*
import java.lang.Integer.min
data class Point(val x: Int, val y: Int)
data class DistancePoints( val point: Point, var distance: Int)
fun main() {
fun findChar(input: List<String>, char: Char): Point {
val x = input.indexOfFirst { it.contains(char) }
val y = input[x].indexOf(char)
return Point(x,y)
}
fun findAllChars(input: List<String>, char: Char): List<Point>{
val list = emptyList<Point>().toMutableList()
for (i in input.indices){
for(j in input[i].indices ){
if(input[i][j] == char){
list.add(Point(i,j))
}
}
}
return list
}
fun parseGraph(input: List<String>): Triple<Point, Point, HashMap<Point, MutableList<Point>>> {
var input = input.toMutableList()
val S = findChar(input, 'S')
val E = findChar(input, 'E')
input[S.x] = input[S.x].replace('S','a')
input[E.x] = input[E.x].replace('E', 'z')
val n = input.size
val m = input.first().length
val Graph = HashMap<Point, MutableList<Point>>()
for (i in 0 until n) {
for(j in 0 until m) {
Graph[Point(i,j)] = emptyList<Point>().toMutableList()
if (i > 0) {
if (input[i - 1][j] <= input[i][j] + 1) {
Graph[Point(i,j)]?.add(Point(i-1,j))
}
}
if (i < n - 1) {
if (input[i + 1][j] <= input[i][j] + 1) {
Graph[Point(i,j)]?.add(Point(i+1,j))
}
}
if (j > 0) {
if (input[i][j-1] <= input[i][j] + 1) {
Graph[Point(i,j)]?.add(Point(i,j-1))
}
}
if (j < m - 1) {
if (input[i][j+1] <= input[i][j] + 1) {
Graph[Point(i,j)]?.add(Point(i,j+1))
}
}
}
}
return Triple(S,E, Graph)
}
fun dijskstra(s: Point, e: Point, graph: Map<Point, List<Point>>): Int{
val reachedPoints = listOf(DistancePoints(s,0)).toMutableList()
val reachablePoints = graph[s]!!.map { DistancePoints(it, 1) }.toMutableList()
while (!reachedPoints.map { it.point }.contains(e)) {
val nearest = reachablePoints.minByOrNull { it.distance } ?: return Int.MAX_VALUE
reachablePoints.remove(nearest)
reachedPoints.add(nearest)
val newReachable = graph[nearest.point]?: emptyList()
val actualReachable = newReachable.filter {
!reachablePoints.map { it.point }.contains(it)
&&
!reachedPoints.map { it.point }.contains(it)
}
reachablePoints.addAll(actualReachable.map { DistancePoints(it, nearest.distance +1) })
}
val eIndex = reachedPoints.indexOfFirst { it.point == e }
return reachedPoints[eIndex].distance
}
fun part1(input: List<String>): Int {
val (S, E, Graph) = parseGraph(input)
return dijskstra(S, E, Graph)
}
fun part2(input: List<String>): Int{
val starters = findAllChars(input, 'a')
val (S, E, Graph) = parseGraph(input)
val minS = dijskstra(S, E, Graph)
//APSP is probably more efficient, but 5 min runtime is better than a lot longer coding
val minPerStarter = starters.minOfOrNull { dijskstra(it, E, Graph) }
return min(minS, minPerStarter?:-1)
}
val test = readTestLines("Day12")
val input = readInputLines("Day12")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c4913b488b8a42c4d7dad94733d35711a9c98992 | 3,782 | aoc22 | Apache License 2.0 |
src/main/kotlin/day11/main.kt | janneri | 572,969,955 | false | {"Kotlin": 99028} | package day11
import util.readTestInput
import java.lang.IllegalArgumentException
data class Operation(val leftOperand: String, val symbol: String, val rightOperand: String) {
companion object {
fun parse(str: String) = str.split(" ").let{Operation(it[0], it[1], it[2])}
}
}
data class Monkey(val monkeyNumber: Int, var inspectCount: Long = 0, val items: MutableList<ULong>,
val operation: Operation, val testDivisor: ULong, val trueMonkeyNum: Int, val falseMonkeyNum: Int)
fun parseMonkey(lines: List<String>) =
Monkey(
monkeyNumber = lines[0].substringAfter("Monkey ")[0].digitToInt(),
items = lines[1].substringAfter("items: ").split(", ").map { it.trim().toULong() }.toMutableList(),
operation = Operation.parse(lines[2].substringAfter("Operation: new = ")),
testDivisor = lines[3].substringAfter("Test: divisible by ").toULong(),
trueMonkeyNum = lines[4].substringAfter("If true: throw to monkey ").toInt(),
falseMonkeyNum = lines[5].substringAfter("If false: throw to monkey ").toInt(),
)
fun runOperation(operation: Operation, item: ULong): ULong {
fun convertToNumber(operand: String) = if (operand == "old") item else operand.toULong()
val leftOperand = convertToNumber(operation.leftOperand)
val rightOperand = convertToNumber(operation.rightOperand)
return when (operation.symbol) {
"+" -> leftOperand + rightOperand
"*" -> leftOperand * rightOperand
else -> throw IllegalArgumentException("Unknown operand")
}
}
fun playRound(monkeys: List<Monkey>, divideBy3Mode: Boolean) {
val commonDivisor = monkeys.map { it.testDivisor }.reduce { acc, divisor -> acc * divisor }
monkeys.forEach {monkey ->
monkey.items.forEach {item ->
var worryLevel = runOperation(monkey.operation, item)
if (divideBy3Mode) {
// In part 1 the worry level is decreased by dividing it with constant 3
worryLevel /= 3.toULong()
}
else {
// In part 2, the keep worry level is decreased by dividing it with a common test divisor
worryLevel %= commonDivisor
}
val targetMonkey = if (worryLevel % monkey.testDivisor == 0.toULong()) monkey.trueMonkeyNum else monkey.falseMonkeyNum
monkeys[targetMonkey].items.add(worryLevel)
monkey.inspectCount += 1
}
monkey.items.clear()
}
}
fun playRounds(inputLines: List<String>, roundCount: Int, divideBy3Mode: Boolean): Long {
val monkeys = inputLines.chunked(7).map { parseMonkey(it) }
for (roundNumber in 1 ..roundCount) {
playRound(monkeys, divideBy3Mode)
}
println(monkeys.joinToString("\n"))
val mostActiveMonkeys = monkeys.sortedBy { it.inspectCount }.reversed().take(2)
return mostActiveMonkeys[0].inspectCount * mostActiveMonkeys[1].inspectCount
}
fun main() {
val inputLines = readTestInput("day11")
println(playRounds(inputLines, 20, true))
println(playRounds(inputLines, 10000, false))
} | 0 | Kotlin | 0 | 0 | 1de6781b4d48852f4a6c44943cc25f9c864a4906 | 3,105 | advent-of-code-2022 | MIT License |
src/Day05.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | fun main() {
fun move(cargos: MutableList<MutableList<Char>>, move: Int, from: Int, to: Int, reverse: Boolean) {
val target = cargos[from].takeLast(move).let { if (reverse) it.reversed() else it }
(1..move).forEach { _ -> cargos[from].removeLast() }
cargos[to].addAll(target)
}
fun parseCargos(input: List<String>): MutableList<MutableList<Char>> =
input.takeWhile { it.isNotBlank() }
.reversed()
.drop(1)
.map { it.slice(1 until it.length step 4) }
.let { matrix ->
matrix.first().mapIndexed { i, _ -> matrix.mapNotNull { it.getOrNull(i) } }
.map { it.filter { c -> c.isUpperCase() } }
.map { it.toMutableList() }
.toMutableList()
}
fun part1(input: List<String>): Int {
val cargos = parseCargos(input)
input.takeLastWhile { it.isNotBlank() }
.map { line -> line.split(' ').slice(1 until 6 step 2) }
.map { it.map { n -> n.toInt() } }
.forEach { params -> move(cargos, params[0], params[1] - 1, params[2] - 1, true) }
cargos.map { it.last() }.joinToString("").println()
return input.size
}
fun part2(input: List<String>): Int {
val cargos = parseCargos(input)
input.takeLastWhile { it.isNotBlank() }
.map { line -> line.split(' ').slice(1 until 6 step 2) }
.map { it.map { n -> n.toInt() } }
.forEach { params -> move(cargos, params[0], params[1] - 1, params[2] - 1, false) }
cargos.map { it.last() }.joinToString("").println()
return input.size
}
val input = readInput("Day05")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 1,780 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day24.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day24(input: List<String>) {
private val hailstones = input.map { MovingObject.parse(it) }
data class Intersection(val point: Vector3D?, val hailstones: Pair<MovingObject, MovingObject>, private val coincident: Boolean = false, private val parallel: Boolean = false) {
val crossesInFuture = when {
point == null -> false
parallel -> false
coincident -> true
else -> (point.x > hailstones.first.pos.x) == (hailstones.first.vel.x > 0) &&
(point.x > hailstones.second.pos.x) == (hailstones.second.vel.x > 0)
}
}
data class MovingObject(val pos: Vector3L, val vel: Vector3L) {
companion object {
fun parse(input: String): MovingObject {
val parts = input.split(" @ ").map { it.split(", ").map { it.toLong() } }
return MovingObject(Vector3L(parts[0][0], parts[0][1], parts[0][2]), Vector3L(parts[1][0], parts[1][1], parts[1][2]))
}
}
// See https://paulbourke.net/geometry/pointlineplane/
fun findXYIntersection(other: MovingObject): Intersection {
val denominator = other.vel.y * vel.x - other.vel.x * vel.y
val numeratorA = other.vel.x * (pos.y - other.pos.y) - other.vel.y * (pos.x - other.pos.x)
val numeratorB = vel.x * (pos.y - other.pos.y) - vel.y * (pos.x - other.pos.x)
if (denominator == 0L) {
if (numeratorA == 0L && numeratorB == 0L) {
return Intersection(null, this to other, coincident = true)
}
return Intersection(null, this to other, parallel = true)
}
val ua = numeratorA.toDouble() / denominator
return Intersection(
Vector3D(pos.x + (ua * vel.x), pos.y + (ua * vel.y), pos.z.toDouble()),
this to other
)
}
}
private fun findPossibleVelocities(a: MovingObject, b: MovingObject, dimension: (Vector3L) -> Long) = buildSet {
if (dimension(a.vel) != dimension(b.vel)) {
return emptySet<Long>()
}
val diff = dimension(b.pos) - dimension(a.pos)
for (v in -1000L..1000L) {
if (v == dimension(a.vel)) {
continue
}
if (diff % (v - dimension(a.vel)) == 0L) {
add(v)
}
}
}
fun solvePart1(min: Long, max: Long) = hailstones
.permutations()
.map { it.first.findXYIntersection(it.second) }
.count { it.crossesInFuture && it.point!!.x > min && it.point.x < max && it.point.y > min && it.point.y < max }
fun solvePart2(): Long {
// Find the only possible velocity for each dimension
val rvx = hailstones.permutations().map { (a, b) -> findPossibleVelocities(a, b, Vector3L::x) }.filter { it.isNotEmpty() }.reduce { acc, set -> acc.intersect(set) }.first()
val rvy = hailstones.permutations().map { (a, b) -> findPossibleVelocities(a, b, Vector3L::y) }.filter { it.isNotEmpty() }.reduce { acc, set -> acc.intersect(set) }.first()
val rvz = hailstones.permutations().map { (a, b) -> findPossibleVelocities(a, b, Vector3L::z) }.filter { it.isNotEmpty() }.reduce { acc, set -> acc.intersect(set) }.first()
// Solve for the line needed to intersect at that velocity so we can determine the start position
val (apx, apy, apz) = hailstones[0].pos
val (avx, avy, avz) = hailstones[0].vel
val (bpx, bpy, _) = hailstones[1].pos
val (bvx, bvy, _) = hailstones[1].vel
// Math based on https://github.com/githuib/AdventOfCode/blob/master/aoc/year2023/day24.py#L73
val m1 = (avy - rvy).toDouble() / (avx - rvx).toDouble()
val m2 = (bvy - rvy).toDouble() / (bvx - rvx).toDouble()
val rpx = (((bpy - (m2 * bpx)) - (apy - (m1 * apx))) / (m1 - m2)).toLong()
val t = (rpx - apx) / (avx - rvx)
val rpy = (apy + (avy - rvy) * t)
val rpz = (apz + (avz - rvz) * t)
return rpx + rpy + rpz
}
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 4,127 | advent-2023 | MIT License |
src/Solution.kt | Shahroz16 | 114,043,227 | false | null | import ListPartitioner.getAllPartitions
import java.util.ArrayList
import java.util.concurrent.TimeUnit
lateinit var distances: Array2D<Double>
/**
* Vehicle Routing Problem, brute-force solution
* Ported from python code at https://github.com/ybashir/vrpfun
*/
fun main(args: Array<String>) {
val vehicles = 3
val locations = getLocations()
val locationIds: List<Int> = locations.map { it.id }.toList()
distances = getDistances()
val startTimeMillis = System.currentTimeMillis()
val shortestRouteSet = shortestRouteWithPartitions(locationIds, vehicles)
println("Solution time: ${TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTimeMillis)} seconds")
System.out.printf("Shortest route time: %.1f minutes\n", maxLengthForRoutes(shortestRouteSet));
println("Shortest route: " + shortestRouteSet)
}
/**
*Distance between first and last and consecutive elements of a list.
**/
fun distance(x: Int, y: Int): Double {
return distances[x, y]
}
/**
* Distance between first and last and consecutive elements of a list
*/
fun routeLength(route: List<Int>): Double {
var sum = 0.0
for (i in 1 until route.size) sum += distance(route[i], route[i - 1])
sum += distance(route[0], route[route.size - 1])
return sum
}
/**
* Returns minimum from a list based on route length
*/
fun shortestRoute(routes: ArrayList<ArrayList<Int>>): ArrayList<Int> {
return routes.minBy {
routeLength(it)
}!!
}
/**
* Return all permutations of a list, each starting with the first item
*/
fun allRoutes(original: ArrayList<Int>): ArrayList<ArrayList<Int>> {
if (original.size < 2) {
return arrayListOf(original)
} else {
val firstElement = original.removeAt(0)
return permutations(original).map {
it.add(0, firstElement)
return@map it
} as ArrayList<ArrayList<Int>>
}
}
/**
* Return maximum from a given route list
*/
fun maxLengthForRoutes(routeList: List<List<Int>>): Double {
val routeLengths = ArrayList<Double>()
return routeList.mapTo(routeLengths) {
routeLength(it)
}.max()!!
}
/**
* This function receives all k-subsets of a route and returns the subset
* with minimum distance cost. Note the total time is always equal to
* the max time taken by any single vehicle
*/
fun shortestRouteWithPartitions(locationIds: List<Int>, partitions: Int): List<List<Int>> {
return allShortRoutesWithPartitions(locationIds, partitions)
.distinct()
.minBy {
maxLengthForRoutes(it)
}!!
}
/**
* Our partitions represent number of vehicles. This function yields
* an optimal path for each vehicle given the destinations assigned to it
*/
fun allShortRoutesWithPartitions(seq: List<Int>, vehicles: Int): ArrayList<List<List<Int>>> {
val shortRoutesList = ArrayList<List<List<Int>>>()
return getAllPartitions(seq.drop(1)).filter {
it.size == vehicles
}.mapTo(shortRoutesList) {
val shortestRouteWithCurrentPartitions = ArrayList<List<Int>>()
it.mapTo(shortestRouteWithCurrentPartitions) {
val r = arrayListOf<Int>(seq[0])
r.addAll(it)
shortestRoute(allRoutes(r))
}
}
} | 0 | Kotlin | 2 | 2 | 3ce13662ee2f93d7308fab3d9173a812331c0b74 | 3,270 | VRP | Apache License 2.0 |
src/Day21.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | sealed class Monkey21 {
abstract val name: String
abstract fun yell(): Long
data class NumberMonkey(override val name: String, val number: Long) : Monkey21() {
override fun yell(): Long = number
}
data class MathMonkey(
override val name: String,
val leftName: String,
val rightName: String,
val op: Char,
val finder: (String) -> Monkey21
) : Monkey21() {
val left: Monkey21 by lazy { finder(leftName) }
val right: Monkey21 by lazy { finder(rightName) }
override fun yell(): Long {
val lv = left.yell()
val rv = right.yell()
return when (op) {
'+' -> lv + rv
'-' -> lv - rv
'*' -> lv * rv
else -> lv / rv
}
}
}
}
fun main() {
fun List<String>.parse(): Map<String, Monkey21> {
val r = mutableMapOf<String, Monkey21>()
val finder = { name: String -> r[name] ?: throw Error("Monkey $name not defined") }
forEach {
val parts = it.split(": ")
val name = parts[0]
val mathParts = parts[1].split(" ")
if (mathParts.size == 1) {
r[name] = Monkey21.NumberMonkey(name, parts[1].toLong())
} else {
r[name] = Monkey21.MathMonkey(name, mathParts[0], mathParts[2], mathParts[1].first(), finder)
}
}
return r
}
fun Map<String, Monkey21>.findRoot() = this["root"] ?: throw Error("Root monkey must be defined.")
fun Monkey21.humanPath(): Set<Monkey21> = when (this) {
is Monkey21.NumberMonkey -> if (name == "humn") setOf(this) else emptySet()
is Monkey21.MathMonkey -> {
val lPath = left.humanPath()
val rPath = right.humanPath()
when {
lPath.isNotEmpty() -> lPath + this
rPath.isNotEmpty() -> rPath + this
else -> emptySet()
}
}
}
fun Monkey21.humanValue(humanPath: Set<Monkey21>, lv: Long): Long = when (this) {
is Monkey21.NumberMonkey -> if (name == "humn") lv else number
is Monkey21.MathMonkey -> {
val lIsHuman = left in humanPath
val rv = if (lIsHuman) right.yell() else left.yell()
val v = when (op) {
'+' -> lv - rv
'-' -> if (lIsHuman) lv + rv else rv - lv
'*' -> lv / rv
else -> lv * rv
}
if (lIsHuman) left.humanValue(humanPath, v) else right.humanValue(humanPath, v)
}
}
fun part1(input: List<String>) = input.parse().findRoot().yell()
fun part2(input: List<String>): Long {
val root = input.parse().findRoot() as Monkey21.MathMonkey
val humanPath = root.humanPath()
return if (root.left in humanPath) {
root.left.humanValue(humanPath, root.right.yell())
} else {
root.right.humanValue(humanPath, root.left.yell())
}
}
val testInput = readInput("Day21_test")
println(part1(testInput)) // 152
println(part2(testInput)) // 301
val input = readInput("Day21")
println(part1(input)) // 268597611536314
println(part2(input)) // 3451534022348
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 3,315 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} |
interface FileOrDirectory {
val size: Int
}
data class File(val name: String, override val size: Int): FileOrDirectory
class Directory(val name: String): FileOrDirectory {
private var files = mutableListOf<FileOrDirectory>()
fun addFile(newFile: FileOrDirectory) {
files.add(newFile)
}
val directories: List<Directory>
get() {
return files.filterIsInstance<Directory>()
}
override val size: Int
get() {
return files.sumOf { it.size }
}
override fun toString(): String {
return "$name: $size"
}
val flatten : List<Directory>
get() {
return listOf(this) + directories.flatMap { it.flatten }
}
}
fun main() {
var root: Directory = Directory("/")
fun parse(input: List<String>) {
root = Directory("/")
val directories = mutableListOf<Directory>()
var currentDirectory = root
input.forEach {
if (it.contains("$ cd")) {
val dirName = it.split(" ").last()
currentDirectory = if (dirName == "..") {
val newCur = directories.removeLast()
newCur
} else if (dirName == "/") {
root
} else {
directories.add(currentDirectory)
val newCur = currentDirectory.directories.first { f -> f.name == dirName }
newCur
}
} else if (it.contains("$ ls")) {
} else {
// It's a file.
val (size, filename) = it.split(" ")
if (size != "dir") {
val parsedSize = size.toInt()
val newFile = File(filename, parsedSize)
currentDirectory.addFile(newFile)
} else {
val newFile = Directory(filename)
currentDirectory.addFile(newFile)
}
}
}
}
fun part1(input: List<String>): Int {
parse(input)
return root.flatten.filter { it.size <= 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val diskSize = 70000000
val needed = 30000000
parse(input)
val available = diskSize - (root.flatten.find { it.name == "/" }?.size ?: 0)
val needToRemove = needed - available
return root.flatten.map { it.size }.filter { it > needToRemove }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 2,805 | 2022-Advent-of-Code | Apache License 2.0 |
src/main/kotlin/letterboxed/Solver.kt | gmarmstrong | 531,249,433 | false | {"Kotlin": 22711} | package letterboxed
import util.zigzagsOver
const val MIN_WORD_LENGTH = 3
/**
* Logic for solving the puzzles.
*/
class Solver(wordsProvider: WordsProvider, private val solutionSteps: Int = 2) {
val words: MutableSet<String> = wordsProvider.getWords()
init {
// Filters a list of words to remove words that could never be legal in any solution.
words.retainAll { isSyntacticallyValid(it) }
}
/**
* Returns a sequence of all possible puzzle solutions
* which use exactly [solutionSteps] words.
*/
fun solve(puzzle: Puzzle): Sequence<List<String>> {
words.retainAll { isValidForPuzzle(it, puzzle) }
return permute(words.toList(), length = solutionSteps).filter { it solves puzzle }
}
/** Determines if this list of words is a solution to [puzzle]. */
infix fun List<String>.solves(puzzle: Puzzle): Boolean {
return size == solutionSteps &&
usesAlphabet(puzzle.letters) &&
fulfillsAlphabet(puzzle.letters) &&
lettersConnected()
}
}
/**
* Checks that the last letter of each word is the same as the first letter of the next word.
*/
fun List<String>.lettersConnected(): Boolean {
for ((a, b) in this.zipWithNext()) {
if (a.last().uppercaseChar() != b.first().uppercaseChar()) {
return false
}
}
return true
}
/**
* Checks that each character in a string is on a different edge than the previous character.
*
* Assumes that all the string's characters are present in the edges.
*/
fun String.alternatesEdges(edges: Set<Set<Char>>): Boolean =
uppercase().toList().zigzagsOver(edges)
/** Generates permutations of the given [length] for a [list] of items. */
fun <T> permute(list: List<T>, length: Int): Sequence<List<T>> =
// Generate a sequence of the yielded lists
sequence {
if (length == 1) { // base case
for (item in list) {
yield(listOf(item))
}
} else { // recursive case
list.forEach { item ->
permute(list, length - 1).forEach { perm ->
yield(listOf(item) + perm)
}
}
}
}
/** Checks that a string only uses characters from a set of characters. */
fun String.usesAlphabet(chars: Set<Char>): Boolean = this.all { it.uppercaseChar() in chars }
/** Checks that a list of strings only uses characters from a set of characters. */
private fun List<String>.usesAlphabet(chars: Set<Char>): Boolean = this.all { it.usesAlphabet(chars) }
/** Checks that a list of strings uses every character from a set of characters at least once. */
private fun List<String>.fulfillsAlphabet(chars: Set<Char>): Boolean =
chars.all { it.uppercaseChar() in this.joinToString("").uppercase() }
/**
* Checks if a word is syntactically valid. That is, that the word is at least three characters long,
* contains only ASCII letters (case-insensitive), and contains no "double letters" (e.g., "egg" fails
* because it contains "gg").
*/
fun isSyntacticallyValid(word: String): Boolean =
word.length >= MIN_WORD_LENGTH &&
word.all { it in 'A'..'z' } &&
word.lowercase().zipWithNext().none { it.first == it.second }
/**
* Checks if a word is valid for the given targetPuzzle. Assumes isSyntacticallyValid(word) is true.
*/
fun isValidForPuzzle(word: String, targetPuzzle: Puzzle): Boolean =
word.usesAlphabet(targetPuzzle.letters) &&
word.alternatesEdges(targetPuzzle.edges)
| 2 | Kotlin | 0 | 0 | a0545396ebe135ebd602f1d874bf8c4dd9b037d5 | 3,534 | letter-boxed | MIT License |
src/Day05.kt | msernheim | 573,937,826 | false | {"Kotlin": 32820} | fun main() {
fun findDividingRow(input: List<String>): Int {
return input.indexOf("")
}
fun getCargoMap(cargoMap: List<String>): MutableMap<Int, String> {
val stacks = mutableMapOf<Int,String>()
val last = cargoMap.last().trimEnd().last().digitToInt()
for (i in 1..last) {
val stackIndex = cargoMap.last().indexOf(i.digitToChar())
var stack = ""
for (level in (cargoMap.size - 1).downTo(0)) {
if (level < cargoMap.size - 1) {
val item = cargoMap[level][stackIndex]
when {
item.isLetter() -> stack += item
else -> break
}
}
}
stacks[i] = stack.trimEnd()
}
return stacks
}
fun getMoves(moves: List<String>): List<Move> {
val result = mutableListOf<Move>()
moves.forEach { move ->
val from = move.substringAfter("from ").substringBefore(" to").toInt()
val to = move.substringAfter("to ").toInt()
val N = move.substringAfter("move ").substringBefore(" from").toInt()
result.add(Move(from, to, N))
}
return result
}
fun executeMoves(cargoMap: MutableMap<Int, String>, moves: List<Move>, reverse: Boolean): Map<Int, String> {
moves.forEach { move ->
val srcStack = cargoMap[move.from].orEmpty()
val itemsToMove = srcStack.substring(srcStack.length - move.N)
cargoMap[move.to] += if (reverse) itemsToMove.reversed() else itemsToMove
cargoMap[move.from] = srcStack.removeSuffix(itemsToMove)
}
return cargoMap
}
fun part1(input: List<String>, reverse: Boolean=true): String {
val index = findDividingRow(input)
val cargoMap = getCargoMap(input.slice(IntRange(0, index - 1)))
val moves = getMoves(input.drop(index + 1))
executeMoves(cargoMap, moves, reverse)
return cargoMap.values.map{ stack -> stack[stack.length - 1]}.toString()
}
fun part2(input: List<String>): String {
return part1(input, false)
}
val input = readInput("Day05")
val part1 = part1(input)
val part2 = part2(input)
println("Result part1: $part1")
println("Result part2: $part2")
}
class Move(val from: Int, val to: Int, val N: Int)
| 0 | Kotlin | 0 | 3 | 54cfa08a65cc039a45a51696e11b22e94293cc5b | 2,419 | AoC2022 | Apache License 2.0 |
src/Day04/Solution.kt | cweinberger | 572,873,688 | false | {"Kotlin": 42814} | package Day04
import readInput
fun main() {
fun parseLine(input: String) : Pair<IntRange, IntRange> {
return input
.split(",")
.map { assignmentString ->
assignmentString.split("-")
.map { it.toInt() }
.let { assigmentList ->
IntRange(assigmentList.first(), assigmentList.last())
}
}
.let {
Pair(it.first(), it.last())
}
}
fun IntRange.contains(other: IntRange) : Boolean {
return (this.contains(other.first) && this.contains(other.last))
}
fun IntRange.overlaps(other: IntRange) : Boolean {
return (this.contains(other.first) || this.contains(other.last))
}
fun part1(input: List<String>): Int {
println("Evaluating ${input.count()} assignment pairs")
return input.map { assigmentString ->
parseLine(assigmentString)
.let {
if (it.first.contains(it.second) || it.second.contains(it.first)) { 1 } else { 0 }
}
}.sum()
}
fun part2(input: List<String>): Int {
println("Evaluating ${input.count()} assignment pairs")
return input.map { assigmentString ->
parseLine(assigmentString)
.let {
if (it.first.overlaps(it.second) || it.second.overlaps(it.first)) { 1 } else { 0 }
}
}.sum()
}
val testInput = readInput("Day04/TestInput")
val input = readInput("Day04/Input")
println("=== Part 1 - Test Input ===")
println(part1(testInput))
println("=== Part 1 - Final Input ===")
println(part1(input))
println("=== Part 2 - Test Input ===")
println(part2(testInput))
println("=== Part 2 - Final Input ===")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 883785d661d4886d8c9e43b7706e6a70935fb4f1 | 1,885 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day08.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 8 - Seven Segment Search
* Problem Description: http://adventofcode.com/2021/day/8
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day8/
*/
package com.ginsberg.advent2021
class Day08(input: List<String>) {
private val inputRows = input.map { InputRow.of(it) }
fun solvePart1(): Int =
inputRows.sumOf { row ->
row.digitSegments.takeLast(4).count { it.size in setOf(2, 3, 4, 7) }
}
fun solvePart2(): Int = inputRows.sumOf { row ->
row.calculateValue()
}
private class InputRow(val digitSegments: List<Set<Char>>) {
private val digitValues = discoverMappings()
fun calculateValue(): Int =
(digitValues.getValue(digitSegments[10]) * 1000) +
(digitValues.getValue(digitSegments[11]) * 100) +
(digitValues.getValue(digitSegments[12]) * 10) +
digitValues.getValue(digitSegments[13])
private fun discoverMappings(): Map<Set<Char>, Int> {
val digitToString = Array<Set<Char>>(10) { emptySet() }
// Unique based on size
digitToString[1] = digitSegments.first { it.size == 2 }
digitToString[4] = digitSegments.first { it.size == 4 }
digitToString[7] = digitSegments.first { it.size == 3 }
digitToString[8] = digitSegments.first { it.size == 7 }
// 3 is length 5 and overlaps 1
digitToString[3] = digitSegments
.filter { it.size == 5 }
.first { it overlaps digitToString[1] }
// 9 is length 6 and overlaps 3
digitToString[9] = digitSegments
.filter { it.size == 6 }
.first { it overlaps digitToString[3] }
// 0 is length 6, overlaps 1 and 7, and is not 9
digitToString[0] = digitSegments
.filter { it.size == 6 }
.filter { it overlaps digitToString[1] && it overlaps digitToString[7] }
.first { it != digitToString[9] }
// 6 is length 6 and is not 0 or 9
digitToString[6] = digitSegments
.filter { it.size == 6 }
.first { it != digitToString[0] && it != digitToString[9] }
// 5 is length 5 and is overlapped by 6
digitToString[5] = digitSegments
.filter { it.size == 5 }
.first { digitToString[6] overlaps it }
// 2 is length 5 and is not 3 or 5
digitToString[2] = digitSegments
.filter { it.size == 5 }
.first { it != digitToString[3] && it != digitToString[5] }
return digitToString.mapIndexed { index, chars -> chars to index }.toMap()
}
private infix fun Set<Char>.overlaps(that: Set<Char>): Boolean =
this.containsAll(that)
companion object {
fun of(input: String): InputRow =
InputRow(
input.split(" ").filterNot { it == "|" }.map { it.toSet() }
)
}
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 3,165 | advent-2021-kotlin | Apache License 2.0 |
src/Day07.kt | ChAoSUnItY | 572,814,842 | false | {"Kotlin": 19036} | import java.util.*
sealed class Node {
abstract val name: String
abstract val size: Int
data class FileNode(override val name: String, override val size: Int) : Node()
data class DirNode(override val name: String, val nodes: MutableSet<Node> = mutableSetOf()) : Node() {
override val size: Int by lazy {
nodes.sumOf(Node::size)
}
}
}
fun main() {
fun processData(data: List<String>): Node.DirNode {
val dirTree = Node.DirNode("/")
val nodeStackTrace = Stack<Node.DirNode>()
for (execution in data.joinToString("\n")
.split("$")
.filter(String::isNotEmpty)
.map { it.split("\n") }) {
val command = execution.first()
// parse command
when (command.substring(1..2)) {
"cd" -> {
when (val name = command.substring(4)) {
"/" -> nodeStackTrace += dirTree
".." -> nodeStackTrace.pop()
else -> nodeStackTrace.peek()
.nodes
.filterIsInstance<Node.DirNode>()
.find { it.name == name }
.let(nodeStackTrace::push)
}
}
"ls" -> {
for (file in execution.subList(1, execution.size - 1)) {
val (size, name) = file.split(" ")
if (file.startsWith("dir")) {
nodeStackTrace.peek().nodes += Node.DirNode(name)
} else {
nodeStackTrace.peek().nodes += Node.FileNode(name, size.toInt())
}
}
}
}
}
return dirTree
}
fun findDirs(dirNode: Node.DirNode): List<Node.DirNode> =
dirNode.nodes
.filterIsInstance<Node.DirNode>()
.let { if (it.isNotEmpty()) it + it.flatMap(::findDirs) else emptyList() }
fun part1(data: Node.DirNode): Int =
findDirs(data).map(Node::size)
.sorted()
.filter { it < 100_000 }
.sum()
fun part2(data: Node.DirNode): Int =
findDirs(data).map(Node::size)
.sorted()
.first { it >= (30_000_000 - (70_000_000 - data.size)) }
val input = readInput("Day07")
val processedData = processData(input)
println(part1(processedData))
println(part2(processedData))
}
| 0 | Kotlin | 0 | 3 | 4fae89104aba1428820821dbf050822750a736bb | 2,558 | advent-of-code-2022-kt | Apache License 2.0 |
src/Day07.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} |
fun main() { // ktlint-disable filename
data class DirInfo(
val path: String,
var size: Long = 0,
val subDirs: MutableList<String> = mutableListOf()
)
fun getDirInfo(input: List<String>): Map<String, DirInfo> {
val dirInfo = mutableMapOf<String, DirInfo>()
var curDir = "/"
for (line in input) {
when {
line.startsWith("\$ cd ") -> {
when (val dir = line.substring("\$ cd ".length)) {
"/" -> curDir = dir
".." -> curDir = curDir.substring(0, curDir.lastIndexOf("/"))
else -> curDir += if (curDir == "/") dir else "/$dir"
}
}
line.startsWith("\$ ls") -> {
dirInfo[curDir] = DirInfo(curDir)
}
line.startsWith("dir ") -> {
dirInfo[curDir]!!.subDirs.add(line.substring("dir ".length))
}
else -> {
// println("file line is $line")
// handle file info
val tokens = line.split(" ")
val fileSize = tokens[0].toLong()
// add file size to dir and all parent dirs
var dir = curDir
while (true) {
dirInfo[dir]!!.size += fileSize
if (dir == "/") break
dir = dir.substring(0, dir.lastIndexOf("/"))
if (dir.isEmpty()) dir = "/"
}
}
}
}
return dirInfo
}
fun part1(input: List<String>): Long {
val maxSize = 100000
val dirInfo = getDirInfo(input)
val dirsLessThanMax = dirInfo.map { it.value }.filter { it.size < maxSize }
return dirsLessThanMax.sumOf { it.size }
}
fun part2(input: List<String>): Long {
val maxDisk = 70000000
val minFree = 30000000
val dirInfo = getDirInfo(input)
val rootDir = dirInfo["/"]!!
val minRemoveSize = minFree - (maxDisk - rootDir.size)
val candidates = dirInfo.map { it.value }
.filter { it.size >= minRemoveSize && it.size != rootDir.size }
println("Possible candidates: $candidates")
return candidates.map { it.size }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
println("Test total size for dirs under 100000: ${part1(testInput)}")
check(part1(testInput) == 95437L)
println("Test smallest directory to delete size: ${part2(testInput)}")
check(part2(testInput) == 24933642L)
val input = readInput("Day07_input")
println("total size for dirs under 100000: ${part1(input)}")
println("smallest directory to delete size is: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 2,937 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/day09/Day09.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day09
import readLines
import kotlin.math.abs
data class Knot(var x: Int, var y: Int)
enum class Direction(val x: Int, val y: Int) {
R(1, 0),
L(-1, 0),
U(0, 1),
D(0, -1)
}
fun tailVisitedCount(input: List<String>, ropeLength: Int): Int {
val rope = ArrayList<Knot>()
(1..ropeLength).map { rope.add(Knot(0, 0)) }
val set = HashSet<Pair<Int, Int>>()
set.add(Pair(0, 0))
for (move in input) {
val direction = Direction.valueOf(move.substringBefore(" "))
var distance = move.substringAfter(" ").toInt()
while (distance > 0) {
rope[0].x += direction.x
rope[0].y += direction.y
for (i in 1 until ropeLength) {
val knot1 = rope[i-1]
val knot2 = rope[i]
val xDistance = knot1.x - knot2.x
val yDistance = knot1.y - knot2.y
if (abs(xDistance) == 2 && abs(yDistance) == 2) {
knot2.x += xDistance / 2
knot2.y += yDistance / 2
} else if (abs(yDistance) == 2) {
knot2.x = knot1.x
knot2.y = knot1.y + (yDistance / 2) * -1
} else if (abs(xDistance) == 2) {
knot2.x = knot1.x + (xDistance / 2) * -1
knot2.y = knot1.y
}
}
set.add(Pair(rope[ropeLength-1].x, rope[ropeLength-1].y))
distance -= 1
}
}
return set.size
}
private fun part1(input: List<String>): Int {
return tailVisitedCount(input, 2)
}
private fun part2(input: List<String>): Int {
return tailVisitedCount(input, 10)
}
fun main() {
val input = readLines("day09/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 1,796 | aoc2022 | Apache License 2.0 |
src/main/kotlin/LargestDivisibleSubset.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* Given a set of distinct positive integers nums,
* return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
*
* answer[i] % answer[j] == 0, or
* answer[j] % answer[i] == 0
* If there are multiple solutions, return any of them.
*
*
*
* Example 1:
*
* Input: nums = [1,2,3]
* Output: [1,2]
* Explanation: [1,3] is also accepted.
* Example 2:
*
* Input: nums = [1,2,4,8]
* Output: [1,2,4,8]
*
*
* Constraints:
*
* 1 <= nums.length <= 1000
* 1 <= nums[i] <= 2 * 10^9
* All the integers in nums are unique.
* @see <a href="https://leetcode.com/problems/largest-divisible-subset/">LeetCode</a>
*/
fun largestDivisibleSubset(nums: IntArray): List<Int> {
val sortedNums = nums.sorted()
val subsets = MutableList(sortedNums.size) { listOf<Int>() }
var largestSubsetIndex = 0
for ((index, num) in sortedNums.withIndex()) {
var currentSubset = listOf(num)
for (previousIndex in 0 until index) {
val previousSubset = subsets[previousIndex]
if (num % previousSubset.last() == 0 && previousSubset.size >= currentSubset.size) {
currentSubset = previousSubset + num
}
}
subsets[index] = currentSubset
if (subsets[index].size > subsets[largestSubsetIndex].size) {
largestSubsetIndex = index
}
}
return subsets[largestSubsetIndex]
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 1,443 | kotlin-codes | Apache License 2.0 |
src/Day03.kt | Jessenw | 575,278,448 | false | {"Kotlin": 13488} | fun main() {
fun part1(input: List<String>): Int =
input.sumOf { line ->
val compartments = line.chunked(line.length / 2)
.map { it.toCharArray() }
compartments[0]
.map {
// Look for duplicate between compartments.
// "%" indicates no duplicate
if (compartments[1].contains(it)) it else '%'
}
.filter { it != '%' }
.distinct()
.sumOf { getItemPriority(it) }
}
fun part2(input: List<String>) =
input
.map { it.toCharArray() }
.chunked(3) { group ->
group[0]
.map {
if (group[1].contains(it) && group[2].contains(it)) it else '%'
}
.filter { it != '%' }
.distinct()
.sumOf { getItemPriority(it) }
}
.sum()
val testInput = readInputLines("Day03_test")
println(part1(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInputLines("Day03")
println(part1(input))
println(part2(input))
}
fun getItemPriority(char: Char) = if (char.isLowerCase()) char.code - 96 else char.code - 64 + 26
| 0 | Kotlin | 0 | 0 | 05c1e9331b38cfdfb32beaf6a9daa3b9ed8220a3 | 1,349 | aoc-22-kotlin | Apache License 2.0 |
src/aoc2022/Day07.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
fun main() {
class DirNode(val name: String, val parent: DirNode?) {
val subdirs = mutableMapOf<String, DirNode>()
var immediateFilesSum: Int = 0
var subdirsSum: Int? = null
}
fun calculateSum(node: DirNode): Int {
if (node.subdirs.isEmpty()) {
node.subdirsSum = node.immediateFilesSum;
return node.subdirsSum!!;
}
var total = 0
for (subdir in node.subdirs.values) {
if (subdir.subdirsSum == null) {
total += calculateSum(subdir)
}
}
node.subdirsSum = total + node.immediateFilesSum
return node.subdirsSum!!
}
fun readTree(input: List<String>): DirNode {
val dirRegex = """dir (\w+)""".toRegex()
val fileRegex = """(\d+) (.+)""".toRegex()
val cdRegex = """\$ cd (\w+)""".toRegex()
val root = DirNode("/", null)
var curNode = root
for (line in input) {
if (line == "$ cd /") continue
if (line == "$ ls") continue
if (line == "$ cd ..") {
curNode = curNode.parent!!
}
if (line.matches(cdRegex)) {
val match = cdRegex.find(line)
val (dirName) = match!!.destructured
curNode = curNode.subdirs[dirName]!!
}
if (line.matches(dirRegex)) {
val match = dirRegex.find(line)
val (dirName) = match!!.destructured
curNode.subdirs.put(dirName, DirNode(dirName, curNode))
}
if (line.matches(fileRegex)) {
val match = fileRegex.find(line)
val (size, name) = match!!.destructured
curNode.immediateFilesSum += size.toInt()
}
}
return root
}
fun part1(input: List<String>): Int {
val root = readTree(input)
calculateSum(root)
var sum = 0
val toCheck = mutableListOf<DirNode>(root)
while (!toCheck.isEmpty()) {
val next = toCheck.removeFirst()
if (next.subdirsSum!! <= 100000) {
sum += next.subdirsSum!!
}
toCheck.addAll(next.subdirs.values)
}
return sum
}
fun part2(input: List<String>): Int {
val root = readTree(input)
calculateSum(root)
val total = 70000000
val minUnused = 30000000
val unused = total - root.subdirsSum!!
val minSize = minUnused - unused
var cur = root.subdirsSum!!
val toCheck = mutableListOf<DirNode>(root)
while (!toCheck.isEmpty()) {
val next = toCheck.removeFirst()
if (next.subdirsSum!! >= minSize && next.subdirsSum!! < cur) {
cur = next.subdirsSum!!
}
toCheck.addAll(next.subdirs.values)
}
return cur
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 3,269 | advent-of-code-kotlin | Apache License 2.0 |
src/Day04.kt | novotnyradekcz | 579,767,169 | false | {"Kotlin": 11517} | fun main() {
fun part1(input: List<String>): Int {
var total = 0
for (line in input) {
val sections = line.split(",") // [1-2, 3-4]
val firstElf = sections[0].split("-") // [1, 2]
val secondElf = sections[1].split("-") // [3, 4]
if ((firstElf[0].toInt() <= secondElf[0].toInt() && firstElf[1].toInt() >= secondElf[1].toInt()) ||
(firstElf[0].toInt() >= secondElf[0].toInt() && firstElf[1].toInt() <= secondElf[1].toInt())) total++
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
for (line in input) {
val sections = line.split(",") // [1-2, 3-4]
val firstElf = sections[0].split("-") // [1, 2]
val secondElf = sections[1].split("-") // [3, 4]
if ((firstElf[1].toInt() >= secondElf[0].toInt() && firstElf[0].toInt() <= secondElf[1].toInt()) ||
(secondElf[1].toInt() >= firstElf[0].toInt() && secondElf[0].toInt() <= firstElf[1].toInt())) total++
}
return total
}
// 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")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 2f1907dc63344cf536f5031bc7e1c61db03fc570 | 1,382 | advent-of-code-kotlin-2022 | Apache License 2.0 |
day11/Part1.kt | anthaas | 317,622,929 | false | null | import java.io.File
private const val EMPTY = 'L'
private const val OCCUPIED = '#'
fun main(args: Array<String>) {
var board = File("input.txt").readLines().map { it.toCharArray() }
var nextIter = evolve(board)
var same = areSame(board, nextIter)
while (!same) {
nextIter = evolve(board)
same = areSame(board, nextIter)
board = nextIter
}
val occupiedSeats = board.map { it.map { it == OCCUPIED }.count { it } }.sum()
println(occupiedSeats)
}
private fun areSame(board: List<CharArray>, nextIter: List<CharArray>): Boolean {
return board.zip(nextIter)
.map { outer -> outer.first.zip(outer.second).map { inner -> inner.first == inner.second }.all { it } }
.all { it }
}
private fun countOccupiedNeigboursOf(x: Int, y: Int, board: List<CharArray>): Int {
var count = 0
(-1..1).forEach { i ->
(-1..1).forEach { j ->
if (!((x + i !in 0 until board.size) || (y + j !in 0 until board[0].size)) && !(j == 0 && i == 0)
&& board[x + i][y + j] == OCCUPIED
) count++
}
}
return count
}
private fun evolve(board: List<CharArray>): List<CharArray> {
val newBoard = MutableList(board.size) { " ".repeat(board[0].size).toCharArray() }
board.forEachIndexed { x, line ->
line.forEachIndexed { y, actualPositionSymbol ->
newBoard[x][y] = when (actualPositionSymbol) {
EMPTY -> if (countOccupiedNeigboursOf(x, y, board) == 0) OCCUPIED else EMPTY
OCCUPIED -> if (countOccupiedNeigboursOf(x, y, board) > 3) EMPTY else OCCUPIED
else -> actualPositionSymbol
}
}
}
return newBoard
}
| 0 | Kotlin | 0 | 0 | aba452e0f6dd207e34d17b29e2c91ee21c1f3e41 | 1,719 | Advent-of-Code-2020 | MIT License |
src/main/kotlin/days/Day8.kt | hughjdavey | 433,597,582 | false | {"Kotlin": 53042} | package days
class Day8 : Day(8) {
override fun partOne(): Any {
val outputValues = inputList.map { it.split(" | ")[1] }.flatMap { it.split(" ") }
return outputValues.count { listOf(2, 3, 4, 7).contains(it.length) }
}
override fun partTwo(): Any {
val signals = inputList.map { it.split(" | ").map { it.split(" ") } }.map { Signal(it[0], it[1]) }
return signals.fold(0) { sum, signal -> sum + signal.deduce() }
}
data class Signal(val inputs: List<String>, val outputs: List<String>) {
private val digits: MutableMap<Int, String> = (0..9).associateWith { "" }.toMutableMap()
fun deduce(): Int {
deduceEasyDigits()
// 0, 6 and 9 have 6 segments; 2, 3 and 5 have 5
val zeroSixNine = inputs.filter { it.length == 6 }.filterNot(digits.values::contains)
val twoThreeFive = inputs.filter { it.length == 5 }.filterNot(digits.values::contains)
// 9 shares all its segments with 4
val nine = zeroSixNine.find { d -> digits[4]!!.all { d.contains(it) } }!!
digits[9] = nine
// 0 has both of 1s segments whereas 6 does not
val zero = zeroSixNine.filterNot { it == nine }.find { d -> digits[1]!!.all { d.contains(it) } }!!
digits[0] = zero
digits[6] = zeroSixNine.first { it != zero && it != nine }
// 3 is the only one of 2, 3 and 5 that has both of 1s segments
val three = twoThreeFive.find { d -> digits[1]!!.all { d.contains(it) } }!!
digits[3] = three
// 5 has 3 of 4s segments whereas 2 only has 2
val five = twoThreeFive.filterNot { it == three }.first { d -> digits[4]!!.count { d.contains(it) } == 3 }
digits[5] = five
digits[2] = twoThreeFive.first { it != three && it != five }
val outs = outputs.map { o -> digits.entries.find { it.value.toCharArray().sorted() == o.toCharArray().sorted() }!!.key }
return outs.joinToString("").toInt()
}
private fun deduceEasyDigits() {
for (input in inputs) {
when (input.length) {
2 -> { digits[1] = input }
3 -> { digits[7] = input }
4 -> { digits[4] = input }
7 -> { digits[8] = input }
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a3c2fe866f6b1811782d774a4317457f0882f5ef | 2,419 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/Day15_pt2.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
/**
* Solution of part one with ranges is way too slow, would take in the order of 90 days, so need to start from scratch
* Steps:
* - for each of the lines between 0 and 4000000 (= y position):
* - for each sensor-beacon combinations, calculate the interval on the line between 0 and 4000000 (x-from and x-t0), if any
* - sort the intervals and merge them using the algorithm described here:
* see https://scicomp.stackexchange.com/questions/26258/the-easiest-way-to-find-intersection-of-two-intervals
* - In the result there should be 1 line, where the merged result is not 1 interval but 2 intervals with a gap of 1
* This gap is the distress signal position. Frequency = x-pos * 4000000 + y-pos
*/
fun part2(input: List<String>) {
val maxCoordinate = if (input.size == 14) 20 else 4000000
val readings = makeReadings(input)
(0..maxCoordinate).toList()
.forEach { y ->
val intervals = readings.mapNotNull { reading ->
val mdBeaconSensor = manhattanDistance(reading.sensor, reading.beacon)
val distance = abs(y - reading.sensor.y) - mdBeaconSensor // negative when useful
if (distance <= 0) return@mapNotNull Interval(
from = reading.sensor.x + distance,
to = reading.sensor.x - distance
)
else return@mapNotNull null
}
val mergedIntervals = mergeIntervals(intervals)
val intervalsInRange = mergedIntervals
.filter { interval -> interval.from <= maxCoordinate && interval.to >= 0 }
.map { interval -> Interval(from = max(interval.from, 0), to = min(interval.to, maxCoordinate)) }
if (intervalsInRange.size > 1) {
val x = intervalsInRange[0].to + 1
val frequency: Long = (x * 4000000L) + y
println("frequency: $frequency") // 12525726647448
}
}
}
//val testInput = readInput("Day15_test")
//part2(testInput)
val input = readInput("Day15")
part2(input)
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 2,320 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | alfr1903 | 573,468,312 | false | {"Kotlin": 9628} | fun main() {
fun part1(input: List<String>): Int = input.count { hasCompleteOverlap(it) }
fun part2(input: List<String>): Int = input.count { hasPartialOverlap(it) }
val input = readInputAsList("Day04Input")
println(part1(input))
println(part2(input))
}
private fun hasCompleteOverlap(inp: String): Boolean {
val ranges: List<String> = inp.split(",")
val firstRange: IntRange = ranges.first().substringBefore("-").toInt()..ranges.first().substringAfter("-").toInt()
val secondRange: IntRange = ranges.last().substringBefore("-").toInt()..ranges.last().substringAfter("-").toInt()
return (firstRange.first <= secondRange.first && firstRange.last >= secondRange.last)
|| (secondRange.first <= firstRange.first && secondRange.last >= firstRange.last)
}
private fun hasPartialOverlap(inp: String): Boolean {
val ranges: List<String> = inp.split(",")
val firstRange: IntRange = ranges.first().substringBefore("-").toInt()..ranges.first().substringAfter("-").toInt()
val secondRange: IntRange = ranges.last().substringBefore("-").toInt()..ranges.last().substringAfter("-").toInt()
return (firstRange.contains(secondRange.first) || firstRange.contains(secondRange.last))
|| (secondRange.contains(firstRange.first) || secondRange.contains(firstRange.last))
}
| 0 | Kotlin | 0 | 0 | c1d1fbf030ac82c643fa5aea4d9f7c302051c38c | 1,330 | advent-of-code-2022 | Apache License 2.0 |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p04/Leet435.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p04
import java.util.TreeMap
private class Leet435 {
val overlaps = TreeMap<Int, Int>()
fun eraseOverlapIntervals(intervals: Array<IntArray>): Int {
for (k in intervals.indices) {
isOverlapPrevious(k, intervals)
println(overlaps)
}
return 0
}
fun isOverlapPrevious(intervalNumber: Int, intervals: Array<IntArray>) {
val overlappedIntervals = TreeMap<Int, Int>()
for (i in 0 until intervalNumber) {
getOverlappedRange(intervals[intervalNumber], intervals[i])
?.let {
overlappedIntervals[it.first] = maxOf(overlappedIntervals[it.first] ?: 0, it.second - it.first)
}
}
val mergedOverlappedIntervals = mergeIntervals(overlappedIntervals)
appendOverlaps(mergedOverlappedIntervals)
}
fun getOverlappedRange(range1: IntArray, range2: IntArray): Pair<Int, Int>? {
val r1s = range1[0]
val r1e = range1[1] - 1
val r2s = range2[0]
val r2e = range2[1] - 1
if (r1s <= r2e && r1e > r2s) return Pair(maxOf(r1s, r2s), minOf(r1e, r2e))
if (r2s <= r1e && r2e > r1s) return Pair(maxOf(r1s, r2s), minOf(r1e, r2e))
return null
}
fun appendOverlaps(overlaps: Map<Int, Int>) {
for (entry in overlaps) {
appendOverlaps(entry.key, entry.value)
}
}
fun appendOverlaps(start: Int, size: Int) {
val end = start + size
val startedValue = overlaps.floorEntry(start).let { (it?.value ?: 0) + 1 }
overlaps[start] = startedValue
overlaps.tailMap(start + 1)
.let { if (start + 1 < end) it.headMap(end) else it }
.forEach { k, v -> overlaps[k] = v + 1 }
overlaps.floorEntry(end + 1)?.let { overlaps[end + 1] = it.value - 1 }
}
/** start, size */
fun mergeIntervals(intervals: TreeMap<Int, Int>): TreeMap<Int, Int> {
val size = intervals.size
if (size <= 1) return intervals
var lastEnd = Int.MIN_VALUE
var lastKey = 0
val newMap = TreeMap<Int, Int>()
for (entry in intervals.entries) {
if (entry.key < lastEnd) newMap[lastKey] = entry.value + newMap[lastKey]!! + (lastKey - entry.key)
lastEnd = entry.key + entry.value - 1
lastKey = entry.key
newMap[entry.key] = entry.value
}
return newMap
}
fun isOverlapped(range1: IntRange, range2: IntRange): Boolean {
return range1.first < range2.last && range1.last > range2.first
}
}
fun main() {
Leet435().eraseOverlapIntervals(
arrayOf(
intArrayOf(1, 10),
intArrayOf(2, 5),
intArrayOf(4, 11),
intArrayOf(1, 4),
)
) // 1
//2, 5 Leet435().eraseOverlapIntervals(
// arrayOf(
// intArrayOf(1, 2),
// intArrayOf(2, 3),
// intArrayOf(3, 4),
// intArrayOf(1, 3),
// )
// ) // 1
// Leet435().eraseOverlapIntervals(
// arrayOf(
// intArrayOf(1, 2),
// intArrayOf(1, 2),
// intArrayOf(1, 2),
// )
// ) // 2
// Leet435().eraseOverlapIntervals(
// arrayOf(
// intArrayOf(1, 2),
// intArrayOf(2, 3),
// )
// ) // 0
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 3,376 | playground | MIT License |
src/Day09.kt | SimoneStefani | 572,915,832 | false | {"Kotlin": 33918} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Point(val x: Int, val y: Int) {
val up get() = Point(x, y + 1)
val down get() = Point(x, y - 1)
val left get() = Point(x - 1, y)
val right get() = Point(x + 1, y)
private fun isAdjacent(other: Point) = other != this && abs(this.x - other.x) <= 1 && abs(y - other.y) <= 1
fun tailStep(tail: Point): Point =
if (isAdjacent(tail)) tail
else Point(tail.x + (x - tail.x).sign, tail.y + (y - tail.y).sign)
}
class Grid(knotsCount: Int = 2) {
private var knots = MutableList(knotsCount) { Point(0, 0) }
val path = mutableListOf(Point(0, 0))
fun step(c: Char) {
when (c) {
'R' -> knots[0] = knots[0].right
'L' -> knots[0] = knots[0].left
'U' -> knots[0] = knots[0].up
'D' -> knots[0] = knots[0].down
}
for (i in 1 until knots.size)
knots[i] = knots[i - 1].tailStep(knots[i])
if (path.last() != knots.last()) path.add(knots.last())
}
}
fun simulateRope(input: List<String>, knotsCount: Int = 2): Int {
return Grid(knotsCount).also { grid ->
input.forEach { motion -> repeat(motion.substringAfter(" ").toInt()) { grid.step(motion[0]) } }
}.path.toSet().size
}
fun part1(input: List<String>): Int {
return simulateRope(input, 2)
}
fun part2(input: List<String>): Int {
return simulateRope(input, 10)
}
val test2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lines()
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(test2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3244a6dfb8a1f0f4b47db2788cbb3d55426d018 | 1,969 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): String {
val emptyLineIndex = input.indexOf("")
val stackInput = input.take(emptyLineIndex)
val rearrangementProcedureInput = input.drop(emptyLineIndex + 1)
val stacks = parseInitialStacks(stackInput)
val rearrangementActions = parseRearrangementProcedure(rearrangementProcedureInput)
for (action in rearrangementActions) {
repeat(action.quantity) { stacks[action.to].add(stacks[action.from].removeLast()) }
}
return stacks.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val emptyLineIndex = input.indexOf("")
val stackInput = input.take(emptyLineIndex)
val rearrangementProcedureInput = input.drop(emptyLineIndex + 1)
val stacks = parseInitialStacks(stackInput)
val rearrangementActions = parseRearrangementProcedure(rearrangementProcedureInput)
for (action in rearrangementActions) {
stacks[action.to].addAll(stacks[action.from].takeLast(action.quantity))
stacks[action.from] = stacks[action.from].dropLast(action.quantity).toMutableList()
}
return stacks.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
assertEquals("CMZ", part1(testInput))
assertEquals("MCD", part2(testInput))
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private fun parseInitialStacks(input: List<String>): MutableList<MutableList<Char>> {
val numberOfStacks = input.last().windowed(4, 4, true).size
val stacks: MutableList<MutableList<Char>> = MutableList(numberOfStacks) { mutableListOf() }
for (currentLine in input.asReversed().drop(1)) {
for ((columnIndex, columnContent) in currentLine.windowed(4, 4, true).withIndex()) {
val stackItem = columnContent[1]
if (stackItem.isLetter()) {
stacks[columnIndex].add(stackItem)
}
}
}
return stacks
}
private fun parseRearrangementProcedure(input: List<String>): List<RearrangementAction> {
return input.map {
val words = it.split(" ")
RearrangementAction(words[1].toInt(), words[3].toInt() - 1, words[5].toInt() - 1)
}
}
data class RearrangementAction(val quantity: Int, val from: Int, val to: Int)
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 2,331 | aoc2022 | Apache License 2.0 |
src/main/kotlin/Day12.kt | clechasseur | 258,279,622 | false | null | import org.clechasseur.adventofcode2019.Pt3D
import org.clechasseur.adventofcode2019.math.leastCommonMultiple
import org.clechasseur.adventofcode2019.toPt3D
import kotlin.math.abs
import kotlin.math.sign
object Day12 {
private val input = """
<x=16, y=-8, z=13>
<x=4, y=10, z=10>
<x=17, y=-5, z=6>
<x=13, y=-3, z=0>
""".trimIndent()
private val initialMoons = input.lineSequence().map { Moon(it.toPt3D(), Pt3D.ZERO) }.toList()
fun part1() = initialMoons.move(1_000).sumBy { it.energy }
fun part2(): Long {
val initialByDimension = initialMoons.byDimension()
val periodsByDimension = mutableMapOf<Dimension, Long>()
var moons = initialMoons
var steps = 0L
while (periodsByDimension.size < Dimension.values().size) {
moons = moons.moveOnce()
steps++
moons.byDimension().filter { !periodsByDimension.containsKey(it.key) }.map { (dimension, state) ->
if (state == initialByDimension[dimension]) {
periodsByDimension[dimension] = steps
}
}
}
return periodsByDimension.values.toList().leastCommonMultiple()
}
private fun List<Moon>.move(steps: Int) = generateSequence(this) { it.moveOnce() }.drop(1).take(steps).last()
private fun List<Moon>.moveOnce() = map { moon ->
Moon(moon.position, this.filter { it != moon }.map {
otherMoon -> velocityChange(moon, otherMoon)
}.fold(moon.velocity) { acc, v -> acc + v })
}.map {
moon -> Moon(moon.position + moon.velocity, moon.velocity)
}
private fun velocityChange(moon: Moon, otherMoon: Moon) = velocityChange(moon.position, otherMoon.position)
private fun velocityChange(position: Pt3D, otherPosition: Pt3D) = Pt3D(
(otherPosition.x - position.x).sign,
(otherPosition.y - position.y).sign,
(otherPosition.z - position.z).sign
)
private fun List<Moon>.byDimension() = Dimension.values().map {
dimension -> dimension to map { it.forSingleDimension(dimension) }
}.toMap()
private fun List<Long>.leastCommonMultiple(): Long = when (size) {
0 -> error("Need at least one element to find LCM")
1 -> first()
2 -> leastCommonMultiple(this[0], this[1])
else -> (drop(2) + take(2).leastCommonMultiple()).leastCommonMultiple()
}
}
private data class Moon(val position: Pt3D, val velocity: Pt3D) : Comparable<Moon> {
override fun compareTo(other: Moon): Int = when (val cmp = position.compareTo(other.position)) {
0 -> velocity.compareTo(other.velocity)
else -> cmp
}
}
private val Pt3D.energy get() = abs(x) + abs(y) + abs(z)
private val Moon.potentialEnergy get() = position.energy
private val Moon.kineticEnergy get() = velocity.energy
private val Moon.energy get() = potentialEnergy * kineticEnergy
private enum class Dimension {
X, Y, Z
}
private fun Moon.forSingleDimension(dimension: Dimension): Pair<Int, Int> = when (dimension) {
Dimension.X -> position.x to velocity.x
Dimension.Y -> position.y to velocity.y
Dimension.Z -> position.z to velocity.z
}
| 0 | Kotlin | 0 | 0 | 187acc910eccb7dcb97ff534e5f93786f0341818 | 3,211 | adventofcode2019 | MIT License |
src/Day02.kt | jordanfarrer | 573,120,618 | false | {"Kotlin": 20954} | fun main() {
val day = "Day02"
val winValue = 6
val loseValue = 0
val drawValue = 3
val rock = Choice("Rock", "X", theirChoice = "A", myPointValue = 1)
val paper = Choice("Paper", "Y", theirChoice = "B", myPointValue = 2)
val scissors = Choice("Scissors", "Z", theirChoice = "C", myPointValue = 3)
val choices = listOf(rock, paper, scissors)
val rules = listOf(
GameRule(rock, rock, drawValue),
GameRule(rock, paper, loseValue),
GameRule(rock, scissors, winValue),
GameRule(paper, rock, winValue),
GameRule(paper, paper, drawValue),
GameRule(paper, scissors, loseValue),
GameRule(scissors, rock, loseValue),
GameRule(scissors, paper, winValue),
GameRule(scissors, scissors, drawValue)
)
fun part1(input: List<String>): Int {
var result = 0
input.forEach { line ->
val (theirChoiceValue, myChoiceValue) = line.split(" ")
val myChoice = choices.find { it.myChoice == myChoiceValue } ?: throw Exception("Can't find matching my choice for $myChoiceValue")
val theirChoice = choices.find { it.theirChoice == theirChoiceValue } ?: throw Exception("Can't find matching their choice for $myChoiceValue")
val matchingRule = rules.find { it.me == myChoice && it.them == theirChoice } ?: throw Exception("Can't find matching rule")
result += myChoice.myPointValue + matchingRule.outcome
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
input.forEach { line ->
val (theirChoice, desiredOutcomeValue) = line.split(" ")
val matchingOutcome = when (desiredOutcomeValue) {
"X" -> loseValue
"Y" -> drawValue
"Z" -> winValue
else -> throw Exception("No matching outcome found")
}
val matchingRule = rules.find { it.outcome == matchingOutcome && it.them.theirChoice == theirChoice } ?: throw Exception("Unable to find matching rule")
result += matchingOutcome + matchingRule.me.myPointValue
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
val part1Result = part1(testInput)
println("Part 1 (test): $part1Result")
check(part1Result == 15)
val part2Result = part2(testInput)
println("Part 2 (test): $part2Result")
check(part2Result == 12)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
data class Choice(val name: String, val myChoice: String, val theirChoice: String, val myPointValue: Int)
data class GameRule(val me: Choice, val them: Choice, val outcome: Int)
| 0 | Kotlin | 0 | 1 | aea4bb23029f3b48c94aa742958727d71c3532ac | 2,804 | advent-of-code-2022-kotlin | Apache License 2.0 |
2021/src/main/kotlin/day8_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.cut
import utils.mapItems
fun main() {
Day8Imp.run()
}
object Day8Imp : Solution<List<Day8Imp.Key>>() {
override val name = "day8"
override val parser = Parser.lines.mapItems {
it.cut("|") { input, output -> Key(input.split(' '), output.split(' ')) }
}
override fun part1(input: List<Key>): Int {
var count = 0
for (key in input) {
for (out in key.output) {
if (out.length == 2 || out.length == 4 || out.length == 3 || out.length == 7) {
count++
}
}
}
return count
}
override fun part2(input: List<Key>): Int {
var sum = 0
for (key in input) {
sum += solve(key)
}
return sum
}
fun <T> Set<T>.one(): T {
if (this.size != 1) { throw IllegalStateException("More than one item in $this!") }
return first()
}
fun solve(key: Key): Int {
// 1: c f // len = 2
// 7: a c f // len = 3
// 4: bcd f // len = 4
// 2: a cde g // len = 5
// 3: a cd fg // len = 5
// 5: ab d fg // len = 5
// 0: abc efg // len = 6
// 6: ab defg // len = 6
// 9: abcd fg // len = 6
// 8: abcdefg // len = 7 <-- ignore
/*
a = chars(3) - chars(2) // fix
b = only char in chars(4) that appears in chars(5) _once_
d = only char in chars(4) that appears in chars(5) _thrice_
f = only char in chars(2) that appears in chars(6) _thrice_
c = chars(2) - 'f'
g = in all of chars(5), chars(6) but not 'a'
e = not 'a', 'b', 'c', 'd', 'f' or 'g'
*/
val track = Array(size = 8) { mutableListOf<Char>() }
key.digits.forEach {
track[it.length].addAll(it.toCharArray().toList())
}
val t5 = track[5].groupBy { g -> track[5].count { g == it } }.mapValues { (_, v) -> v.toSet() }
val t6 = track[5].groupBy { g -> track[6].count { g == it } }.mapValues { (_, v) -> v.toSet() }
val s = mutableMapOf<Char, Char>()
s['a'] = (track[3].toSet() - track[2].toSet()).one()
s['b'] = (track[4].toSet() intersect t5[1]!!).one()
s['d'] = (track[4].toSet() intersect t5[3]!!).one()
s['f'] = (track[2].toSet() intersect t6[3]!!).one()
s['c'] = (track[2].toSet() - setOf(s['f']!!)).one()
s['g'] = ((t5[3]!! intersect t6[3]!!) - setOf(s['a']!!)).one()
s['e'] = (('a' .. 'g').toSet() - s.values.toSet()).one()
val inv = mutableMapOf<Char, Char>()
for ((k, v) in s) {
inv[v] = k
}
var out = 0
for (digit in key.output) {
val mapped = CharArray(digit.length)
digit.forEachIndexed { index, c ->
mapped[index] = inv[c]!!
}
out *= 10
try {
out += A[mapped.sorted().joinToString("")]!!
} catch (e: Exception) {
println("Failed with ${mapped.sorted().joinToString("")}")
}
}
return out
}
val A = mapOf(
"abcefg" to 0,
"cf" to 1,
"acdeg" to 2,
"acdfg" to 3,
"bcdf" to 4,
"abdfg" to 5,
"abdefg" to 6,
"acf" to 7,
"abcdefg" to 8,
"abcdfg" to 9
)
data class Key(val digits: List<String>, val output: List<String>)
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,119 | aoc_kotlin | MIT License |
src/main/kotlin/de/consuli/aoc/year2023/days/Day03.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2023.days
import de.consuli.aoc.common.Day
class Day03 : Day(3, 2023) {
data class Point(val y: Int, val x: Int)
override fun partOne(testInput: Boolean): Int =
calculateSumOfMetrics(toCharArrayList(getInput(testInput)), this::partOnePredicate, this::partOneSelector)
override fun partTwo(testInput: Boolean): Int =
calculateSumOfMetrics(toCharArrayList(getInput(testInput)), this::partTwoPredicate, this::partTwoSelector)
private fun calculateSumOfMetrics(
input: List<CharArray>,
predicate: (Char) -> Boolean,
selector: (Point, List<CharArray>) -> Int
): Int {
return input.indices
.flatMap { row -> input[row].indices.map { col -> Point(row, col) } }
.filter { (row, col) -> predicate(input[row][col]) }.sumOf { selector(it, input) }
}
private fun partOnePredicate(c: Char) = !c.isDigit() && c != '.'
private fun partOneSelector(point: Point, matrix: List<CharArray>) =
getAdjacentNonZeroNumbers(matrix, point.y, point.x).sum()
private fun partTwoPredicate(c: Char) = c == '*'
private fun partTwoSelector(point: Point, matrix: List<CharArray>): Int {
val numbersNextToStars = getAdjacentNonZeroNumbers(matrix, point.y, point.x)
return if (numbersNextToStars.size == 2) numbersNextToStars[0] * numbersNextToStars[1]
else 0
}
private fun getAdjacentNonZeroNumbers(matrix: List<CharArray>, row: Int, col: Int): List<Int> {
return getAdjacentCoordinates(row, col)
.filter { (row, column) -> row in matrix.indices && column in matrix.first().indices }
.map { (row, column) -> extractNumberAt(matrix[row], column) }
.filter { it != 0 }
.toList()
}
private fun getAdjacentCoordinates(row: Int, column: Int): Sequence<Pair<Int, Int>> =
sequenceOf(
-1 to -1, -1 to 0, -1 to 1, 0 to -1, 0 to 1, 1 to -1, 1 to 0, 1 to 1
).map { Pair(row + it.first, column + it.second) }
private fun extractNumberAt(row: CharArray, index: Int): Int {
if (!row[index].isDigit()) return 0
val numberStart = (index downTo 0).find { !row[it].isDigit() }?.plus(1) ?: 0
val numberEnd = (index..row.lastIndex).find { !row[it].isDigit() }?.minus(1) ?: row.lastIndex
val number = row.slice(numberStart..numberEnd).joinToString(separator = "").toInt()
// mask processed number chars with '.'
for (i in numberStart..numberEnd) row[i] = '.'
return number
}
private fun toCharArrayList(inputList: List<String>): List<CharArray> {
return inputList.map { it.toCharArray() }
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 2,705 | advent-of-code | Apache License 2.0 |
src/2022/Day11.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
import splitBy
import top
fun main() {
fun part1(input: List<String>): Int {
val monkeys = input.splitBy { it.isEmpty() }.map { Monkey.fromDesc(it) }
repeat(20) {
monkeys.processRound()
}
val (first, second) = monkeys.map { it.inspects }.asSequence().top(2)
return first * second
}
fun part2(input: List<String>): Long {
val monkeys = input.splitBy { it.isEmpty() }.map { Monkey.fromDesc(it) }
val mod = monkeys.map {it.testValue}.fold(1) { x, y -> x * y }
repeat(10000) {
monkeys.processRoundByMod(mod)
}
val (first, second) = monkeys.map { it.inspects }.asSequence().top(2)
return first.toLong() * second
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
data class Monkey(val itemsWorries: MutableList<Int>, val operationType: String, val amount: Int, val testValue: Int, val trueMonkey: Int, val falseMonkey: Int, var inspects: Int = 0) {
companion object {
fun fromDesc(input: List<String>): Monkey {
val itemsWorries = input[1].substringAfter("Starting items: ").split(",").map { it.trim().toInt() }
var (operationType, amount) = input[2].substringAfter("Operation: new = old ").split(" ").map { it.trim() }
val testValue = input[3].substringAfter("Test: divisible by ").toInt()
val trueMonkey = input[4].substringAfter("If true: throw to monkey ").toInt()
val falseMonkey = input[5].substringAfter("If false: throw to monkey ").toInt()
var amountInt = 0
if (amount == "old") {
operationType += " old"
} else {
amountInt = amount.toInt()
}
return Monkey(itemsWorries.toMutableList(), operationType, amountInt, testValue, trueMonkey, falseMonkey)
}
}
}
fun List<Monkey>.processRound(): List<Monkey> {
forEach { monkey ->
monkey.itemsWorries.forEach {
monkey.inspects++
var newWorry = when (monkey.operationType) {
"* old" -> it * it
"+ old" -> it + it
"*" -> it * monkey.amount
else -> it + monkey.amount
}
newWorry /= 3
if (newWorry % monkey.testValue == 0) {
this[monkey.trueMonkey].itemsWorries.add(newWorry)
} else {
this[monkey.falseMonkey].itemsWorries.add(newWorry)
}
}
monkey.itemsWorries.clear()
}
return this
}
fun List<Monkey>.processRoundByMod(mod: Int): List<Monkey> {
forEach { monkey ->
monkey.itemsWorries.forEach {
monkey.inspects++
val oldWorry = it.toLong()
var newWorry = when (monkey.operationType) {
"* old" -> oldWorry * oldWorry
"+ old" -> oldWorry + oldWorry
"*" -> oldWorry * monkey.amount
else -> oldWorry + monkey.amount
}
newWorry %= mod
if (newWorry % monkey.testValue == 0L) {
this[monkey.trueMonkey].itemsWorries.add(newWorry.toInt())
} else {
this[monkey.falseMonkey].itemsWorries.add(newWorry.toInt())
}
}
monkey.itemsWorries.clear()
}
return this
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 3,617 | aoc-2022-in-kotlin | Apache License 2.0 |
2021/app/src/main/kotlin/net/sympower/aok2021/tonis/Day04.kt | tonisojandu | 573,036,346 | false | {"Rust": 158858, "Kotlin": 15806, "Shell": 1265} | package net.sympower.aok2021.tonis
fun main() {
println("1st: ${day04Part01("/Day04.in")}")
println("2nd: ${day04Part02("/Day04.in")}")
}
fun day04Part01(fileIn: String): Int {
val (pickedNumbers, boards) = readNumbersAndBoards(fileIn)
val (winningBoard, onNumber) = pickWinningBoard(boards, pickedNumbers)
return onNumber * winningBoard.summarizeUnTicked()
}
fun day04Part02(fileIn: String): Int {
val (pickedNumbers, boards) = readNumbersAndBoards(fileIn)
val (winningBoard, onNumber) = pickLastBoard(boards, pickedNumbers)
return onNumber * winningBoard.summarizeUnTicked()
}
fun readNumbersAndBoards(fileIn: String): Pair<List<Int>, List<Board>> {
val lines = readLineFromResource(fileIn) { it }.toTypedArray()
val pickedNumbers = lines[0].split(",").map { it.toInt() }
val boards = Array(lines.size) { it }
.groupBy(::lineBoardMembership) { lines[it] }
.filter { it.key >= 0 }
.map { Board(it.value) }
return pickedNumbers to boards
}
fun pickWinningBoard(boards: List<Board>, pickedNumbers: List<Int>): Pair<Board, Int> {
pickedNumbers.forEach { number ->
boards.forEach { board ->
if (board.isBingo(number)) {
return board to number
}
}
}
throw IllegalStateException("Lottery sport wins!")
}
fun pickLastBoard(boards: List<Board>, pickedNumbers: List<Int>): Pair<Board, Int> {
val boardsLeft = boards.toMutableSet()
pickedNumbers.forEach { number ->
val winners = boardsLeft.filter { board -> board.isBingo(number) }
if (winners.size == boardsLeft.size) {
return boardsLeft.first() to number
}
boardsLeft.removeAll(winners)
}
throw IllegalStateException("Lottery sport wins!")
}
fun lineBoardMembership(lineNumber: Int): Int {
if (lineNumber <= 1) {
return -1
}
if ((lineNumber - 2) % 6 == 5) {
return -1
}
return (lineNumber - 2) / 6
}
class Board(lines: List<String>) {
private val numbers: Array<Array<Int>>
private val ticked: Array<Array<Boolean>>
private val numberCoordinates: Map<Int, List<Pair<Int, Int>>>
init {
numbers = lines.map {
it.replace(Regex("\\s+"), " ")
.trim()
.split(" ")
.map { numIt -> numIt.toInt() }
.toTypedArray()
}.toTypedArray()
ticked = numbers.map { it.map { false }.toTypedArray() }.toTypedArray()
numberCoordinates = numbers.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, number -> number to (rowIndex to columnIndex) }
}
.flatten()
.groupBy({ it.first }) { it.second }
}
fun isBingo(number: Int): Boolean {
numberCoordinates[number]?.let {
return it.map { coordinates ->
ticked[coordinates.first][coordinates.second] = true
isRowBingo(coordinates.first) || isColumnBingo(coordinates.second)
}.reduce { first, second -> first || second }
}
return false
}
fun summarizeUnTicked(): Int {
return ticked.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, isTicked ->
if (!isTicked) {
numbers[rowIndex][columnIndex]
} else {
0
}
}
}.flatten()
.sum()
}
private fun isRowBingo(rowIndex: Int): Boolean {
return ticked[rowIndex]
.reduce { first, second -> first && second }
}
private fun isColumnBingo(columnIndex: Int): Boolean {
return ticked
.map { row -> columnIndex < row.size && row[columnIndex] }
.reduce { first, second -> first && second }
}
}
| 0 | Rust | 0 | 0 | 5ee0c3fb2e461dcfd4a3bdd7db3efae9a4d5aabd | 3,489 | to-advent-of-code | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day02/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day02
import java.io.File
enum class Choice(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
enum class Outcome(val points: Int) {
LOOSE(0),
DRAW(3),
WIN(6)
}
val opponentChoice = mapOf(
"A" to Choice.ROCK,
"B" to Choice.PAPER,
"C" to Choice.SCISSORS,
)
val looseMap = mapOf(
Choice.ROCK to Choice.SCISSORS,
Choice.PAPER to Choice.ROCK,
Choice.SCISSORS to Choice.PAPER,
)
class Round(opponentChoice: Choice, ownChoice: Choice) {
companion object {
private val ownChoice = mapOf(
"X" to Choice.ROCK,
"Y" to Choice.PAPER,
"Z" to Choice.SCISSORS,
)
fun parse(str: String): Round {
val split = str.split(" ")
return Round(
opponentChoice.getValue(split[0]),
ownChoice.getValue(split[1])
)
}
}
private val outcomePoints: Int = (
if (opponentChoice == ownChoice) Outcome.DRAW
else if (looseMap.getValue(opponentChoice) == ownChoice) Outcome.LOOSE
else Outcome.WIN
).points
val points = ownChoice.points + outcomePoints
}
class NeededOutcome(opponentChoice: Choice, neededOutcome: Outcome) {
companion object {
private val neededOutcome = mapOf(
"X" to Outcome.LOOSE,
"Y" to Outcome.DRAW,
"Z" to Outcome.WIN,
)
private val winMap = mapOf(
Choice.ROCK to Choice.PAPER,
Choice.PAPER to Choice.SCISSORS,
Choice.SCISSORS to Choice.ROCK,
)
fun parse(str: String): NeededOutcome {
val split = str.split(" ")
return NeededOutcome(opponentChoice.getValue(split[0]), neededOutcome.getValue(split[1]))
}
}
private val ownChoice = when (neededOutcome) {
Outcome.LOOSE -> looseMap.getValue(opponentChoice)
Outcome.DRAW -> opponentChoice
Outcome.WIN -> winMap.getValue(opponentChoice)
}
val round = Round(opponentChoice, ownChoice)
}
// https://adventofcode.com/2022/day/2
fun main() {
val roundsData = File("src/main/kotlin/com/anahoret/aoc2022/day02/input.txt")
.readText()
.split("\n")
.filter(String::isNotEmpty)
// Part 1
roundsData
.map(Round::parse)
.sumOf(Round::points)
.let(::println)
// Part 2
roundsData
.map(NeededOutcome::parse)
.map(NeededOutcome::round)
.sumOf(Round::points)
.let(::println)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 2,576 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | fun main() {
fun part1(input: List<String>): Int {
return input.asSequence()
.map { Pair(it[0].toCode(), it[2].toCode()) }
.map { it.second + 1 + it.solve() }
.sum()
}
fun part2(input: List<String>): Int {
return input.asSequence()
.map {
val first = it[0] - 'A'
Pair(first, it[2].toCode(first))
}
.map { it.second + 1 + it.solve() }
.sum()
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
private fun Char.toCode(p: Int): Int {
return when (this) {
'X' -> (p - 1).let { if (it < 0) 2 else it }
'Y' -> p
else -> (p + 1) % 3
}
}
private fun Char.toCode(): Int {
return when (this) {
'A', 'X' -> 0
'B', 'Y' -> 1
else -> 2
}
}
private fun Pair<Int, Int>.solve(): Int {
return if (first == second) {
3
} else if ((first + 1) % 3 == second) {
6
} else {
0
}
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 1,087 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day22.kt | poqueque | 430,806,840 | false | {"Kotlin": 101024} | package days
import Coor3
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day22 : Day(22) {
data class Cube(val x: IntRange, val y: IntRange, val z: IntRange) {
fun within(c: Cube): Boolean {
return (x.first in c.x && x.last in c.x &&
y.first in c.y && y.last in c.y &&
z.first in c.z && z.last in c.z)
}
fun intersect(c: Cube): Cube? {
val ax = max(x.first, c.x.first)
val ay = max(y.first, c.y.first)
val az = max(z.first, c.z.first)
val aX = min(x.last, c.x.last)
val aY = min(y.last, c.y.last)
val aZ = min(z.last, c.z.last)
if (ax <= aX && ay <= aY && az <= aZ) return Cube(ax..aX, ay..aY, az..aZ)
return null
}
fun intersects(c: Cube): Boolean {
val irx = (x.first..x.last).intersect(x)
val iry = (y.first..y.last).intersect(y)
val irz = (z.first..z.last).intersect(z)
return irx.size * iry.size * irz.size > 0
}
fun size(): Long {
return (1 + x.last.toLong() - x.first.toLong()) *
(1 + y.last.toLong() - y.first.toLong()) *
(1 + z.last.toLong() - z.first.toLong())
}
}
private var ranges = mutableListOf<Cube>()
private var counts = mutableMapOf<Cube, Int>()
override fun partOne(): Any {
var i = 0
inputList.forEach { line ->
i++
val (a, b) = line.split(" ")
val (c, d, e) = b.split(",")
val (x1, x2) = c.split("=")[1].split("..").map { it.toInt() }
val (y1, y2) = d.split("=")[1].split("..").map { it.toInt() }
val (z1, z2) = e.split("=")[1].split("..").map { it.toInt() }
if (abs(x1) <= 50 && abs(y1) <= 50 && abs(z1) <= 50) {
val newCube = Cube(x1..x2, y1..y2, z1..z2)
for (r in counts.keys.toList()) {
val inter = r.intersect(newCube)
if (inter != null) {
counts[inter] = (counts[inter] ?: 0) - (counts[r] ?: 0)
}
}
if (a == "on") counts[newCube] = (counts[newCube] ?: 0) + 1
}
}
return counts.map { entry -> entry.value * entry.key.size() }.sum()
}
override fun partTwo(): Any {
var i = 0
inputList.forEach { line ->
i++
val (a, b) = line.split(" ")
val (c, d, e) = b.split(",")
val (x1, x2) = c.split("=")[1].split("..").map { it.toInt() }
val (y1, y2) = d.split("=")[1].split("..").map { it.toInt() }
val (z1, z2) = e.split("=")[1].split("..").map { it.toInt() }
val newCube = Cube(x1..x2, y1..y2, z1..z2)
for (r in counts.keys.toList()) {
val inter = r.intersect(newCube)
if (inter != null) {
counts[inter] = (counts[inter] ?: 0) - (counts[r] ?: 0)
}
}
if (a == "on") counts[newCube] = (counts[newCube] ?: 0) + 1
}
return counts.map { entry -> entry.value * entry.key.size() }.sum()
}
}
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
| 0 | Kotlin | 0 | 0 | 4fa363be46ca5cfcfb271a37564af15233f2a141 | 3,450 | adventofcode2021 | MIT License |
src/2022/Day16.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
fun main() {
lateinit var nameToValve: Map<String, Valve>
lateinit var valves: List<Valve>
lateinit var valuableValves: List<Valve>
val pathToCost: MutableMap<Pair<Valve, Valve>, Int> = mutableMapOf()
fun parseInput(input: List<String>) {
valves = input.map { s ->
val (_, name, rate, neighbors) = "Valve (\\w+) has flow rate=(\\d+); \\w+ \\w+ to \\w+ ([\\w\\s,]+)".toRegex().find(s)!!.groups.map { it!!.value }
Valve(name, rate.toInt(), neighbors.split(",").map { it.trim() })
}
valuableValves = valves.filter { it.rate > 0 }
nameToValve = valves.associateBy { it.name }
val first = nameToValve["AA"]!!
(valuableValves + first).forEach { start ->
var currentNodes = start.neighbors
(1..30).forEach { minute ->
currentNodes = currentNodes.flatMap {
val end = (nameToValve[it]!!)
val path = start to end
if (pathToCost.contains(path)) {
emptyList()
} else {
pathToCost[path] = minute
end.neighbors
}
}
}
}
}
fun findMaxPressure(countdown: Int, current: Valve, restValves: List<Valve>, pressure: Int): Int {
if (countdown <= 0) return pressure
return restValves.maxOfOrNull { valve ->
val cost = pathToCost[current to valve]!!
val nextCountdown = countdown - cost - 1
findMaxPressure(nextCountdown, valve, restValves - valve, pressure + nextCountdown * valve.rate)
} ?: pressure
}
fun part1(input: List<String>): Int {
parseInput(input)
val start = nameToValve["AA"]!!
return findMaxPressure(30, start, valuableValves, 0)
}
fun part2(input: List<String>): Int {
parseInput(input)
val start = nameToValve["AA"]!!
val splitValves = valuableValves.buildSubsets()
return splitValves
.asSequence()
.filter { it.isNotEmpty() && it.size != valuableValves.size }
.maxOf { my ->
val elephant = valuableValves.toSet() - my
findMaxPressure(26, start, my.toList(), 0) +
findMaxPressure(26, start, elephant.toList(), 0)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
/*fun printPath(path: List<Valve>) {
var min = 0
var pressure = 0
path.windowed(2).forEach { (prev, next) ->
println("Open valve=${prev.name} at min=${min}")
pressure += (30 - min) * prev.rate
val cost = pathToCost[prev to next]!!
min += cost
println("Go to valve=${next.name} and now min=${min}")
min += 1
}
pressure += (30 - min) * path.last().rate
println("Released $pressure")
}*/
}
private data class Valve(val name: String, val rate: Int, val neighbors: List<String>)
private fun List<Valve>.buildSubsets(): List<Set<Valve>> {
val subsets = mutableListOf<Set<Valve>>()
fun addAllSubsets(subset: Set<Valve> = emptySet(), index: Int = 0) {
if (index == size) {
subsets.add(subset)
return
}
addAllSubsets(subset, index + 1)
addAllSubsets(subset + this[index], index + 1)
}
addAllSubsets()
return subsets
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 3,797 | aoc-2022-in-kotlin | Apache License 2.0 |
src/y2023/Day05.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2023
import utils.readInput
fun main() {
fun List<Long>.toPairs(): List<Pair<Long, Long>> {
return this.chunked(size = 2) { it[0] to it[1] }
}
fun part1(input: List<String>): Long? {
val seeds = input.first().split("seeds: ")[1].split(" ").map { it.toLong() }
val mappings = mutableListOf<MutableList<Pair<LongRange, Long>>>()
input.drop(1).forEach { line ->
when {
line.endsWith("map:") -> {
mappings.add(mutableListOf())
}
line.isNotBlank() -> {
val (dest, src, size) = line.split(" ").map { it.toLong() }
mappings.last().add(src..src + size to dest - src)
}
}
}
val minOf = seeds.minOf { seed ->
mappings.fold(seed) { accumulator, mappings ->
val match = mappings.firstOrNull { it.first.contains(accumulator) }
if (match == null) accumulator else accumulator + match.second
}
}
return minOf
}
fun part2(input: List<String>): Long {
val seeds = input.first().split("seeds: ")[1].split(" ")
.map { it.toLong() }
.toPairs()
val mappings = mutableListOf<MutableMap<LongRange, (Long) -> Long>>()
input.drop(1).forEach { line ->
when {
line.endsWith("map:") -> mappings.add(mutableMapOf())
line.isNotBlank() -> {
val (dest, src, size) = line.split(" ").map { it.toLong() }
val range = src until src + size
val f = { x: Long -> dest + (x - src) }
mappings.last()[range] = f
}
}
}
fun mapValue(value: Long, mappings: List<Map<LongRange, (Long) -> Long>>): Long {
var result = value
for (mapping in mappings) {
val f = mapping.keys.firstOrNull { it.contains(result) }?.let { longRange -> mapping[longRange] }
result = f?.invoke(result) ?: result
}
return result
}
val minOf = seeds.minOfOrNull { seed ->
var minValue = Long.MAX_VALUE
for (value in seed.first..seed.first + seed.second) {
val mapped = mapValue(value, mappings)
if (mapped < minValue) {
minValue = mapped
}
}
minValue
} ?: Long.MAX_VALUE
return minOf
}
// test if implementation meets criteria from the description, like:
var testInput = readInput("y2023", "Day05_test_part1")
// println(part1(testInput))
// check(part1(testInput) == 35)
println(part2(testInput))
// check(part2(testInput) == 2286)
val input = readInput("y2023", "Day05")
// check(part1(input) == 2563)
// println(part1(input))
// check(part2(input) == 70768)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 3,014 | advent-of-code-kotlin | Apache License 2.0 |
src/Day08.kt | touchman | 574,559,057 | false | {"Kotlin": 16512} | fun main() {
val input = readInput("Day08")
fun checkIfValueBiggerThanLeftAndRightValues(listOfInts: List<Int>, j: Int): Boolean {
val height = listOfInts[j]
val leftList = listOfInts.dropLast(listOfInts.size - j)
val rightList = listOfInts.drop(j + 1)
return height > leftList.max() || height > rightList.max()
}
fun convertToListOfNumbers(input: List<String>) =
input.map { it.map { it.digitToInt() } }
fun part1(input: List<String>): Int {
val listOfLists = convertToListOfNumbers(input)
var countOfVisibleTrees = 0
listOfLists.forEachIndexed { i, listOfInts ->
listOfInts.forEachIndexed { j, _ ->
if (i == 0 || i == listOfLists.lastIndex ||
j == 0 || j == listOfInts.lastIndex ||
checkIfValueBiggerThanLeftAndRightValues(listOfInts, j) ||
checkIfValueBiggerThanLeftAndRightValues(listOfLists.map { it[j] }, i)
)
countOfVisibleTrees += 1
}
}
return countOfVisibleTrees
}
fun getNumberOfVisibleTrees(height: Int, list: List<Int>): Int {
var countOfVisibleTrees = 0
for (i in 0..list.lastIndex) {
val elem = list[i]
if (elem < height) {
countOfVisibleTrees++
}
if (elem >= height) {
countOfVisibleTrees++
break
}
}
return countOfVisibleTrees
}
fun part2(input: List<String>): Int {
val listOfLists = convertToListOfNumbers(input)
val scenicScores = mutableListOf<Int>()
listOfLists.forEachIndexed { i, listOfInts ->
listOfInts.forEachIndexed { j, height ->
var scenicScore: Int
val leftList = listOfInts.dropLast(listOfInts.size - j)
val rightList = listOfInts.drop(j + 1)
listOfLists.map { it[j] }.let { upAndDownList ->
val upList = upAndDownList.dropLast(upAndDownList.size - i)
val downList = upAndDownList.drop(i + 1)
scenicScore = getNumberOfVisibleTrees(height, upList.reversed())
scenicScore *= getNumberOfVisibleTrees(height, downList)
}
scenicScore *= getNumberOfVisibleTrees(height, leftList.reversed())
scenicScore *= getNumberOfVisibleTrees(height, rightList)
scenicScores.add(scenicScore)
}
}
return scenicScores.max()
}
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7402063a4a7651884be77bb9e97828a31459a7 | 2,680 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | psy667 | 571,468,780 | false | {"Kotlin": 23245} | //[ , M, , , , Z, , V, ],
//[ , Z, , P, , L, , Z, J],
//[S, D, , W, , W, , H, Q],
//[P, V, N, D, , P, , C, V],
//[H, B, J, V, B, M, , N, P],
//[V, F, L, Z, C, S, P, S, G],
//[F, J, M, G, R, R, H, R, L],
//[G, G, G, N, V, V, T, Q, F]
fun main() {
val id = "05"
fun part1(input: List<String>): String {
val crates = input.slice(0..7)
.map { it.split("")
.drop(1)
.chunked(4)
.map { it[1] }
}
.let { matrix ->
List(9) { List(8) { "" } }
.mapIndexed { idx1, it1 ->
List(it1.size) { idx2 -> matrix[idx2][idx1] }
.reversed()
.filter { it.trim() != "" }
}
}
.map { it
.toMutableList()
}
return input.drop(10).map {
val (n, from, to) = it.split("""move|from|to"""
.toRegex())
.drop(1)
.map { it.trim().toInt() }
repeat(n) {
val a = crates[from - 1].removeLast()
crates[to - 1].add(a)
}
crates.map { it }
}.let {
crates.drop(1).map { it.last() }
}.joinToString("").also(::println)
}
fun part2(input: List<String>): String {
val crates = input.slice(0..7)
.map { it.split("")
.drop(1)
.chunked(4)
.map { it[1] }
}
.let { matrix ->
List(9) { List(8) { "" } }
.mapIndexed { idx1, it1 ->
List(it1.size) { idx2 -> matrix[idx2][idx1] }
.reversed()
.filter { it.trim() != "" }
}
}
.map { it
.toMutableList()
}
return input.map {
val (n, from, to) = it.split("""move|from|to""".toRegex()).drop(1).map { it.trim().toInt() }
val a = crates[from].takeLast(n)
crates[to].addAll(a)
repeat(n) {
crates[from].removeLast()
}
crates.map { it }
}.let {
crates.drop(1).map { it.last() }
}.joinToString("").also(::println)
}
// val testInput = readInput("Day${id}_test")
// check(part1(testInput) == "CMZ")
val input = readInput("Day${id}")
println("==== DAY $id ====")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 73a795ed5e25bf99593c577cb77f3fcc31883d71 | 2,630 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | Shykial | 572,927,053 | false | {"Kotlin": 29698} | fun main() {
fun part1(input: List<String>): Int {
val monkeys = parseInput(input)
val monkeysInspects = monkeys.associate { it.number to 0 }.toMutableMap()
repeat(20) { _ ->
monkeys.forEach { monkey ->
monkeysInspects.computeIfPresent(monkey.number) { _, count -> count + monkey.items.size }
monkey.items.map { monkey.operation(it) / 3 }.forEach { worryLevel ->
if (monkey.test(worryLevel)) monkeys[monkey.monkeyIfTrue].items += worryLevel
else monkeys[monkey.monkeyIfFalse].items += worryLevel
}
monkey.items.clear()
}
}
return monkeysInspects.values.sortedDescending().take(2).product()
}
fun part2(input: List<String>): Long {
val monkeys = parseInput(input)
val itemsPerRound = mutableListOf<Map<Int, Int>>()
// var monkeysInspects = monkeys.associate { it.number to 0L }.toMutableMap()
repeat(10_000) { round ->
val itemsThisRound = mutableMapOf<Int, Int>()
val monkeysInspects = monkeys.associate { it.number to 0L }.toMutableMap()
if (round % 500 == 0) println("round $round")
monkeys.forEach { monkey ->
itemsThisRound[monkey.number] = monkey.items.size
monkeysInspects.computeIfPresent(monkey.number) { _, count -> count + monkey.items.size }
monkey.items.map(monkey.operation).forEach { worryLevel ->
if (monkey.test(worryLevel)) {
monkeys[monkey.monkeyIfTrue].items += worryLevel
} else monkeys[monkey.monkeyIfFalse].items += worryLevel
}
monkey.items.clear()
}
itemsPerRound += itemsThisRound
}
TODO()
// return monkeysInspects.values.sortedDescending().take(2).product()
}
val input = readInput("Day11")
println(part1(input))
// println(part2(input))
}
private fun parseInput(input: List<String>): List<Monkey> = input
.chunkedBy { it.isBlank() }
.map { line ->
val number = Regex("""\d+""").find(line[0])!!.value.toInt()
val startingItems = line[1].substringAfter(": ").split(", ").map(String::toLong)
val operation = line[2].substringAfter("new = ").split(" ").let { (first, second, third) ->
val firstNumber = first.toLongOrNull()
val secondNumber = third.toLongOrNull()
val op: Long.(Long) -> Long = when (second) {
"+" -> { b: Long -> this + b }
"*" -> { b: Long -> this * b }
else -> error("unsupported operation: $second")
}
{ old: Long -> (firstNumber ?: old).op(secondNumber ?: old) }
}
val test: (Long) -> Boolean = { it % line[3].substringAfterLast(" ").toLong() == 0L }
val monkeyIfTrue = line[4].substringAfterLast(" ").toInt()
val monkeyIfFalse = line[5].substringAfterLast(" ").toInt()
Monkey(
number = number,
items = startingItems.toMutableList(),
operation = operation,
test = test,
monkeyIfTrue = monkeyIfTrue,
monkeyIfFalse = monkeyIfFalse
)
}
private class Monkey(
val number: Int,
var items: MutableList<Long>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val monkeyIfTrue: Int,
val monkeyIfFalse: Int
) | 0 | Kotlin | 0 | 0 | afa053c1753a58e2437f3fb019ad3532cb83b92e | 3,511 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | jwalter | 573,111,342 | false | {"Kotlin": 19975} | fun main() {
fun valOf(v: String): Int {
return when {
"AX".contains(v) -> 1
"BY".contains(v) -> 2
"CZ".contains(v) -> 3
else -> 0
}
}
fun score(theirs: Int, mine: Int): Int {
val outcome = when(mine - theirs) {
1 -> 6
-2 -> 6
0 -> 3
else -> 0
}
return outcome + mine
}
fun score(row: String): Int {
val (theirs, mine) = row.split(" ").map { valOf(it) }
return score(theirs, mine)
}
fun makeMove(theirs: Int, outcome: Int): Int {
return when(outcome) {
1 -> if (theirs == 1) 3 else theirs -1
3 -> if (theirs == 3) 1 else theirs +1
else -> theirs
}
}
fun score2(row: String): Int {
val (theirs, outcome) = row.split(" ").map { valOf(it) }
val mine = makeMove(theirs, outcome)
return score(theirs, mine)
}
fun part1(input: List<String>): Int {
return input.sumOf { score(it) }
}
fun part2(input: List<String>): Int {
val scores = input.map { score2(it) }
return scores.sum()
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 576aeabd297a7d7ee77eca9bb405ec5d2641b441 | 1,392 | adventofcode2022 | Apache License 2.0 |
src/Day02.kt | jsebasct | 572,954,137 | false | {"Kotlin": 29119} | enum class PlayOption {
ROCK, PAPER, SCISSOR;
fun score(): Int {
return this.ordinal + 1
}
fun result(another: PlayOption): GameResult {
val res = if (this == another) GameResult.DRAW
else if (this == ROCK && another == PAPER) GameResult.LOST
else if (this == PAPER && another == SCISSOR) GameResult.LOST
else if (this == SCISSOR && another == ROCK) GameResult.LOST
else GameResult.WIN
return res
}
}
enum class GameResult(val value: Int) {
LOST(0), DRAW(3), WIN(6)
}
data class GamePlay(val opponentPlay: PlayOption, val myPlay: PlayOption) {
fun getScore(): Int {
return myPlay.score() + myPlay.result(opponentPlay).value
}
}
fun main() {
fun stringToOpponentPlay(play: String) = when(play) {
"A" -> PlayOption.ROCK
"B" -> PlayOption.PAPER
"C" -> PlayOption.SCISSOR
else -> throw Exception("opponent - value not valid")
}
fun stringToMyPlayPart01(play: String) = when(play) {
"X" -> PlayOption.ROCK
"Y" -> PlayOption.PAPER
"Z" -> PlayOption.SCISSOR
else -> throw Exception("my play - value not valid")
}
fun stringToMyPlayPart02(play: String, opponentPlay: PlayOption): PlayOption {
return when(play) {
// loose
"X" -> when (opponentPlay) {
PlayOption.ROCK -> PlayOption.SCISSOR
PlayOption.PAPER -> PlayOption.ROCK
PlayOption.SCISSOR -> PlayOption.PAPER
}
// draw
"Y" -> opponentPlay
// wing
"Z" -> when (opponentPlay) {
PlayOption.ROCK -> PlayOption.PAPER
PlayOption.PAPER -> PlayOption.SCISSOR
PlayOption.SCISSOR -> PlayOption.ROCK
}
else -> throw Exception("bad input ")
}
}
fun part21(input: List<String>): Int {
val gamePlays = input.map {
val (opponent, me) = it.split(" ")
GamePlay(stringToOpponentPlay(opponent), stringToMyPlayPart01(me))
}
val res = gamePlays.fold(0) { sum, element -> sum + element.getScore() }
return res
}
fun part22(input: List<String>): Int {
val gamePlays = input.map {
val (opponent, me) = it.split(" ")
val opponentPlay = stringToOpponentPlay(opponent)
GamePlay(stringToOpponentPlay(opponent), stringToMyPlayPart02(me, opponentPlay))
}
val res = gamePlays.fold(0) { sum, element -> sum + element.getScore() }
return res
}
val input = readInput("Day02_test")
println("total: ${part21(input)}")
println("Part two")
println(part22(input))
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day02_test")
// check(part2(testInput) == 45000)
}
| 0 | Kotlin | 0 | 0 | c4a587d9d98d02b9520a9697d6fc269509b32220 | 2,930 | aoc2022 | Apache License 2.0 |
src/day13/Day13.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day13
import readInput
interface PacketContent {
val type: String
}
data class PacketItem(
val value: Int
) : PacketContent {
override val type: String = "Item"
}
data class PacketArray(
val items: List<PacketContent>
) : PacketContent {
override val type: String = "Array"
}
fun isOrdered(left: PacketContent, right: PacketContent): Boolean? {
val sameTypes = left.type == right.type
return if (sameTypes) {
when (left.type) {
"Item" -> {
(left as PacketItem to right as PacketItem).let { (l, r) ->
if (l.value == r.value) null else l.value < r.value
}
}
"Array" -> {
(left as PacketArray to right as PacketArray).let { (l, r) ->
arraysOrdered(l, r)
}
}
else -> throw Exception("Unknown Type")
}
} else {
if (left.type == "Array") {
(left as PacketArray to right as PacketItem).let { (l, r) ->
arraysOrdered(l, PacketArray(listOf(r)))
}
} else {
(left as PacketItem to right as PacketArray).let { (l, r) ->
arraysOrdered(PacketArray(listOf(l)), r)
}
}
}
}
fun arraysOrdered(left: PacketArray, right: PacketArray): Boolean? {
return left.items.zip(right.items).let { pairs ->
pairs.firstNotNullOfOrNull { isOrdered(it.first, it.second) }
} ?: if (left.items.size == right.items.size) null else left.items.size < right.items.size
}
fun parseContent(input: String): PacketContent {
return if (input.first() == '[' && input.last() == ']') {
parseArray(input)
} else {
parseItem(input)
}
}
fun parseArray(input: String): PacketArray {
// Empty
if (input == "[]") return PacketArray(emptyList())
// Splitting by "," isn't reliable enough, we must exclude "," inside brackets
val arrayItems = mutableListOf<String>()
input.removePrefix("[").removeSuffix("]").let { innerString ->
var bracketDepth = 0
var currBuffer = ""
innerString.toList().forEach { char ->
var skipBuffer = false
when (char) {
'[' -> bracketDepth++
']' -> bracketDepth--
',' -> if (bracketDepth == 0) {
skipBuffer = true
arrayItems.add(currBuffer)
currBuffer = ""
}
}
if (!skipBuffer) currBuffer += char
}
arrayItems.add(currBuffer)
}
return arrayItems.map { str ->
parseContent(str)
}.let { contents ->
PacketArray(contents)
}
}
fun parseItem(input: String): PacketItem {
return PacketItem(input.toInt())
}
fun main() {
fun part1(input: List<String>): Int {
var orderedSum = 0
input.chunked(3).forEachIndexed { index, packetGroup ->
val packetOne = parseContent(packetGroup[0])
val packetTwo = parseContent(packetGroup[1])
if (isOrdered(packetOne, packetTwo) == true) {
orderedSum += (index + 1)
}
}
return orderedSum
}
fun part2(input: List<String>): Int {
val dividerTwoPacket = parseContent("[[2]]")
val dividerSixPacket = parseContent("[[6]]")
val packets = input.mapNotNull { packet ->
if (packet.isEmpty()) null
else parseContent(packet)
}.plus(dividerTwoPacket).plus(dividerSixPacket)
val sortedPackets = packets.sortedWith(fun (a: PacketContent, b: PacketContent): Int {
return if (isOrdered(a, b) == true) -1 else 1
})
val idxOfTwo = sortedPackets.indexOf(dividerTwoPacket)
val idxOfSix = sortedPackets.indexOf(dividerSixPacket)
return (idxOfTwo + 1) * (idxOfSix + 1)
}
val testInput = readInput("Day13_test")
val input = readInput("Day13")
println("Part 1 [Test] : ${part1(testInput)}")
check(part1(testInput) == 13)
println("Part 1 [Real] : ${part1(input)}")
println("Part 2 [Test] : ${part2(testInput)}")
check(part2(testInput) == 140)
println("Part 2 [Real] : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 4,272 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2023/day10/day10.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day10
import adventofcode2023.*
import kotlin.time.measureTime
fun main() {
println("Day 10")
val input = readInput("day10")
val puzzle1Timing = measureTime {
println("Puzzle 1 ${puzzle1(input)}")
}
println("Puzzle 1 took $puzzle1Timing")
val puzzle2Timing = measureTime {
println("Puzzle 2 ${puzzle2(input)}")
}
println("Puzzle 2 took $puzzle2Timing")
}
fun findStart(field:List<CharSequence>): Point {
var l: Int = 0
var r: Int = 0
field.forEachIndexed { lineIndex, line ->
val rowIndex = line.indexOf('S')
if (rowIndex > -1) {
l = lineIndex
r = rowIndex
}
}
return Point(l, r)
}
tailrec fun findPath(field: List<CharSequence>, point: Point, path: MutableSet<Point> = mutableSetOf()): Set<Point> {
path.add(point)
val pointsAround = point.pointsAround().filter { (l, r) -> l >= 0 && r >= 0 && l <= field.lastIndex && r <= field[l].lastIndex }
val connectedPoints = pointsAround.filter { isPointsConnected(field, point, it) }
val nextPoint = connectedPoints.find { it !in path }
if (nextPoint == null) {
return path
}
// println("NextPoint $nextPoint, ${field[nextPoint.line][nextPoint.row]}")
return findPath(field, nextPoint, path)
}
fun isPointsConnected(field: List<CharSequence>, first: Point, second: Point): Boolean {
val f = field[first.line][first.col]
val s = field[second.line][second.col]
val diff = Pair(second.line - first.line, second.col - first.col)
return when {
diff.line == 0 && diff.col == -1 -> f in "S-7J" && s in "S-FL"
diff.line == -1 && diff.col == 0 -> f in "SJ|L" && s in "SF|7"
diff.line == 0 && diff.col == 1 -> f in "S-FL" && s in "S-J7"
diff.line == 1 && diff.col == 0 -> f in "S|F7" && s in "S|JL"
else -> false
}
}
fun puzzle1(input: List<String>): Int {
val startPoint = findStart(field = input)
val path = findPath(input, startPoint)
return path.size/2
}
fun isPointInsidePath(point: Point, path: List<Point>): Boolean {
val x = point.line
val y = point.col
var isInside = false
for (i in path.indices) {
val j = if (i == path.lastIndex) 0 else i + 1
val xi = path[i].line
val yi = path[i].col
val xj = path[j].line
val yj = path[j].col
val intersect = ((yi > y) != (yj > y)) &&
(x < (xj - xi) * (y - yi) / (yj - yi) + xi)
if (intersect) {
isInside = !isInside
}
}
return isInside
}
fun puzzle2(input: List<String>): Int {
val startPoint = findStart(input)
val path = findPath(input, startPoint)
val pathAsList = path.toList()
val points = buildList {
input.indices.forEach { line ->
input[line].indices.forEach { row ->
val p = Point(line, row)
if (p !in path) {
val symbol = input[line][row]
val isInside = isPointInsidePath(p, pathAsList)
if(isInside) {
// println("$p $symbol $isInside")
add(p)
}
}
}
}
}
return points.size
} | 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 3,286 | adventofcode2023 | MIT License |
aoc2023/day5.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2023
import utils.InputRetrieval
fun main() {
Day5.execute()
}
private object Day5 {
fun execute() {
val input = readInput()
val (seedRanges, maps) = input
println("Part 1: ${part1(seedRanges, maps)}")
println("Part 2: ${part2(seedRanges, maps)}")
}
private fun part1(seeds: Iterable<Long>, maps: List<Mapping>): Long = seeds.minOf {
maps.fold(it) { seed, mapping -> mapping.getMappedValue(seed) }
}
// Same as yesterday. We could improve the performance of this by changing the algorithm, but... I'm cold and the heat from the CPU fans feel nice
private fun part2(seedRanges: List<Long>, maps: List<Mapping>): Long {
return seedRanges.chunked(2).minOf {
println("Start calculation for chunk: ${it.first()}")
part1((it.first()..<(it.first() + it.last())), maps)
}
}
private fun readInput(): Pair<List<Long>, List<Mapping>> {
var lines = InputRetrieval.getFile(2023, 5).readLines()
// Seeds
val seeds = lines.first().removePrefix("seeds: ").split(' ').map { it.toLong() }
lines = lines.drop(2) // Remove seeds and empty line
val mappings = mutableListOf<Mapping>()
repeat(7) {
lines = lines.drop(1) // Remove header
val inputMap = lines.takeWhile { it.isNotBlank() }
mappings.add(Mapping.parse(inputMap))
lines = lines.drop(inputMap.size + 1) // Remove maps and empty line
}
return seeds to mappings
}
private data class Mapping(private val mapping: List<Triple<Long, Long, Long>>) {
fun getMappedValue(value: Long): Long {
val map = mapping.firstOrNull { (it.first <= value) && (value < (it.first + it.third)) }
return map?.let { it.second + (value - it.first) } ?: value
}
companion object {
fun parse(input: List<String>): Mapping {
val mapping = input.map {
val (dest, source, range) = it.split(' ').map { a -> a.toLong() }
Triple(source, dest, range)
}.toList()
return Mapping(mapping)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 2,226 | Advent-Of-Code | MIT License |
src/Day12.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | import java.util.*
fun main() {
data class Data(val x: Int, val y: Int, val value: Char, val step: Int)
fun part1(input: List<String>, sx: Int = 0, sy: Int = 0): Int {
val visited = mutableMapOf<Pair<Int, Int>, Int>()
val queue = LinkedList<Data>()
var min = Int.MAX_VALUE
queue.offer(Data(sx, sy, 'a', 0))
while (queue.isNotEmpty()) {
val (x, y, value, step) = queue.poll()
if (value == 'E') {
min = min.coerceAtMost(step)
continue
}
if (visited[x to y] == null) {
visited[x to y] = step
} else {
continue
}
val dir = listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0)
val allowed = value + 1
dir.map { (dx, dy) -> dx + x to dy + y }.forEach { (x, y) ->
var va = input.getOrNull(y)?.getOrNull(x) ?: return@forEach
val or = va
va = if (va == 'E') 'z' else va
if (va <= allowed) {
queue.offer(Data(x, y, or, step + 1))
}
}
}
return min
}
fun part2(input: List<String>): Int {
val startList = mutableListOf<Pair<Int, Int>>()
input.forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
if (c == 'S' || c == 'a') startList.add(y to x)
}
}
return startList.minOf { (y, x) -> part1(input, x, y) }
}
val input = readInput("Day12")
println(part1(input, 0, input.indexOfFirst { it.startsWith("S") }))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 1,658 | adventOfCode | Apache License 2.0 |
src/main/kotlin/dp/LAS.kt | yx-z | 106,589,674 | false | null | package dp
import util.max
// longest alternating subsequence
fun main(args: Array<String>) {
val A = intArrayOf(7, 5, 6, 10, 2)
println(las(A))
println(lasNoDP(A))
}
// time complexity: O(n)
// space complexity: O(1)
// count the number of local extrema
fun lasNoDP(A: IntArray) = A.indices.filter {
it in 1 until A.size - 1 &&
(A[it] > A[it - 1] && A[it] > A[it + 1]) ||
(A[it] < A[it - 1] && A[it] < A[it + 1])
}.count() + 2
fun las(A: IntArray): Int {
val n = A.size
// inc(i): len of las that increases first (X[2] > X[1]) and starts at A[i]
// dec(i): len of las that decreases first (X[2] < X[1]) and starts at A[i]
// inc(i), dec(i) = 0 if i !in 1..n
// inc(i), dec(i) = 1 if i = n
// assume max{ } = 0
// inc(i) = 1 + max{ dec(k) : k in i + 1..n && A[k] > A[i] } o/w
// dec(i) = 1 + max{ inc(k) : k in i + 1..n && A[k] < A[i] } o/w
// we want max_i { inc(i), dec(i) }
var max = Int.MIN_VALUE
// two 2d array:
// inc[1..n]: inc[i] = inc(i)
// dec[1..n]: dec[i] = inc(i)
val inc = IntArray(n)
val dec = IntArray(n)
// space complexity: O(n)
// base case
inc[n - 1] = 1
dec[n - 1] = 1
// we see that inc(i) depends on dec(k), k > i
// , and dec(i) depends on inc(k), k > i
// so the evaluation order should be from right to left, i.e. i from n down to 1
for (i in n - 2 downTo 0) {
inc[i] = 1 + (dec
.filterIndexed { k, _ -> k in i + 1 until n && A[k] > A[i] }
.max() ?: 0)
dec[i] = 1 + (inc
.filterIndexed { k, _ -> k in i + 1 until n && A[k] < A[i] }
.max() ?: 0)
max = max(max, inc[i], dec[i])
}
// time complexity: O(n^2)
return max
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,614 | AlgoKt | MIT License |
src/Day04.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | fun main() {
fun checkSubRange(range1: Pair<Int, Int>, range2: Pair<Int, Int>): Boolean {
val (firstStarts, firstEnd) = range1
val (secondStarts, secondEnd) = range2
if (firstStarts <= secondStarts && firstEnd >= secondEnd) return true
if (secondStarts <= firstStarts && secondEnd >= firstEnd) return true
return false;
}
fun checkIntersection(range1: Pair<Int, Int>, range2: Pair<Int, Int>): Boolean {
val (firstStarts, firstEnd) = range1
val (secondStarts, secondEnd) = range2
for (i in firstStarts..firstEnd) {
if (i in secondStarts..secondEnd) return true
}
return false
}
fun prepareInput(input: List<String>) = input
.map { pair -> pair.split(',') }
.map { pairs ->
pairs.map { range -> range.split('-') }
.map { rangeList -> Pair(rangeList[0].toInt(), rangeList[1].toInt()) }
}
fun part1(input: List<String>): Int {
return prepareInput(input).count { checkSubRange(it[0], it[1]) }
}
fun part2(input: List<String>): Int {
return prepareInput(input).count{checkIntersection(it[0], it[1])}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 2)
val part2 = part2(testInput)
println(part2)
check(part2 == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 1,558 | aoc-2022 | Apache License 2.0 |
src/aoc2023/Day11.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2023
import utils.checkEquals
import utils.readInputAs2DCharArray
import kotlin.math.abs
fun main(): Unit = with(Day11) {
testInput.solve(2).checkEquals(374)
part1(input)
.checkEquals(10313550)
// .sendAnswer(part = 1, day = "11", year = 2023)
testInput.solve(10).checkEquals(1030)
testInput.solve(100).checkEquals(8410)
part2(input)
.checkEquals(611998089572)
// .sendAnswer(part = 2, day = "11", year = 2023)
}
object Day11 {
data class Galaxy(val id: Int, val y: Long, val x: Long)
fun part1(input: Array<CharArray>) = input.solve(2)
fun part2(input: Array<CharArray>) = input.solve(1_000_000)
fun Array<CharArray>.solve(factor: Int): Long {
val input = this
val (colHeight, rowWidth) = input.size to input.first().size
val emptyRowsIndcies = input.mapIndexedNotNull { index, chars ->
index.takeIf { chars.all { it == '.' } }
}
val emptyColsIndcies = (0..<colHeight).mapNotNull { x ->
x.takeIf { (0..<rowWidth).map { y -> input[y][x] }.all { it == '.' } }
}
val newSpaceToAppend = factor - 1L
val galaxies = buildList {
for (i in input.indices)
for (j in input[i].indices)
if (input[i][j] == '#') {
val newY = i + emptyRowsIndcies.count { it < i } * newSpaceToAppend
val newX = j + emptyColsIndcies.count { it < j } * newSpaceToAppend
add(Galaxy(this.size, y = newY, x = newX))
}
}
val galaxyCombinationPairs = buildSet {
for (i in galaxies.indices)
for (j in i + 1..galaxies.lastIndex)
add(galaxies[i] to galaxies[j])
}
return galaxyCombinationPairs.sumOf { (g1, g2) ->
abs(g1.x - g2.x) + abs(g1.y - g2.y)
}
}
val input
get() = readInputAs2DCharArray("Day11", "aoc2023")
val testInput
get() = readInputAs2DCharArray("Day11_test", "aoc2023")
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 2,099 | Kotlin-AOC-2023 | Apache License 2.0 |
src/com/ncorti/aoc2023/Day05.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
data class Almanac(val seeds: List<Long>, val maps: List<List<Triple<Long, Long, Long>>>) {
companion object {
fun from(input: List<String>): Almanac {
val seeds = input[0].substringAfter("seeds: ")
.split(" ")
.filter(String::isNotBlank)
.map(String::toLong)
val sublist = input.subList(1, input.size)
val maps = mutableListOf<List<Triple<Long, Long, Long>>>()
var submap = mutableListOf<Triple<Long, Long, Long>>()
for (i in sublist.indices) {
if ("map:" in sublist[i]) {
if (submap.isNotEmpty()) maps.add(submap)
submap = mutableListOf()
} else {
submap.add(
Triple(
sublist[i].substringBefore(" ").toLong(),
sublist[i].substringAfter(" ").substringBefore(" ").toLong(),
sublist[i].substringAfterLast(" ").toLong()
)
)
}
}
if (submap.isNotEmpty()) maps.add(submap)
return Almanac(seeds, maps)
}
}
private fun computeLocation(seed: Long): Long {
var current = seed
for (element in maps) {
for (singleMapEntry in element) {
val (destStart, sourceStart, size) = singleMapEntry
if (current in sourceStart..<sourceStart + size) {
val delta = current - sourceStart
current = destStart + (delta)
break
}
}
}
return current
}
fun seedsToLocation(): List<Long> = seeds.map { computeLocation(it) }
fun seedRangesToLowestLocation(): Long {
var lowest = Long.MAX_VALUE
val ranges = seeds.chunked(2).map { it[0]..<it[0] + it[1] }
for (range in ranges) {
for (i in range.first..range.last) {
val location = computeLocation(i)
if (location < lowest) {
lowest = location
}
}
}
return lowest
}
}
fun main() {
fun part1(): Long = getInputAsText("05") {
Almanac.from(split("\n").filter(String::isNotBlank))
}.seedsToLocation().min()
fun part2(): Long = getInputAsText("05") {
Almanac.from(split("\n").filter(String::isNotBlank))
}.seedRangesToLowestLocation()
println(part1())
println(part2())
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 2,598 | adventofcode-2023 | MIT License |
src/main/kotlin/day11/Day11.kt | Jessevanbekkum | 112,612,571 | false | null | package day11
import java.lang.Integer.min
import java.util.function.BiFunction
fun walk(input: String):Int {
val split = input.split(',')
return walk(split)
}
fun walk (split:List<String>):Int {
val counters = mutableMapOf<String, Int>()
val dirs = listOf("n", "ne", "se", "s", "sw", "nw")
dirs.forEach { counters.put(it, 0) }
split.forEach { counters.compute(it, {k, v -> v?.plus(1)})}
removeOpposites(counters)
reduce(counters)
return counters.values.sum()
}
fun furthest(input:String):Int {
val split = input.split(',')
var max = 0
(0..split.size).forEach{
max = Math.max(max, walk(split.subList(0, it)))
}
return max
}
fun removeOpposites(counters: MutableMap<String, Int>) {
val ns = Pair("n", "s")
val nesw = Pair("ne", "sw")
val nwse = Pair("nw", "se")
val ops = listOf<Pair<String, String>>(ns, nesw, nwse)
ops.forEach {
val smallest = min(counters.get(it.first)!!, counters.get(it.second)!!)
counters.put(it.first, counters.get(it.first)!! - smallest)
counters.put(it.second, counters.get(it.second)!! - smallest)
}
}
fun reduce(counters: MutableMap<String, Int>) {
val reducables = listOf(Pair(Pair("n", "sw"), "nw")
, Pair(Pair("n", "se"), "ne")
, Pair(Pair("s", "nw"), "sw")
, Pair(Pair("s", "ne"), "se")
, Pair(Pair("ne", "nw"), "n")
, Pair(Pair("se", "sw"), "s"))
var changes = false
do {
changes = false
reducables.forEach {
if (counters.get(it.first.first)!! > 0 &&
counters.get(it.first.second)!! > 0){
counters.compute(it.first.first, { k, v -> v?.minus(1) });
counters.compute(it.first.second, { k, v -> v?.minus(1) });
counters.compute(it.second, { k, v -> v?.plus(1) });
changes = true
}
}
}while (changes)
}
| 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 1,958 | aoc-2017 | Apache License 2.0 |
src/main/kotlin/aoc2021/day3.kt | sodaplayer | 434,841,315 | false | {"Kotlin": 31068} | package aoc2021
import aoc2021.utils.loadInput
import java.util.*
fun main() {
// part 1
val lines = loadInput("/2021/day3")
.bufferedReader()
.readLines()
fun add(count: List<Int>, line: String) =
count.zip(line.toCharArray().map { it.digitToInt() })
.map { it.first + it.second }
val counts = lines
.fold(Collections.nCopies(12, 0), ::add)
val gamma = counts
.map { if (it > lines.size / 2) '1' else '0' }
.joinToString(separator = "")
.toBigInteger(2)
val epsilon = counts
.map { if (it > lines.size / 2) '0' else '1' }
.joinToString(separator = "")
.toBigInteger(2)
println("gamma: $gamma")
println("epsilon: $epsilon")
println("power: ${gamma * epsilon}")
// part 2
fun oxygenRating(nums: List<String>) =
if (nums.partition { it.first() == '1' }
.run { first.size >= second.size })
'1'
else
'0'
fun carbonRating(nums: List<String>) =
if (nums.partition { it.first() == '0' }
.run { first.size <= second.size })
'0'
else
'1'
fun ratingSeq(ratingMethod: (List<String>) -> Char) =
generateSequence(lines.filterForRating(ratingMethod)) { (_, pass, _) ->
if (pass.size > 1) pass.filterForRating(ratingMethod)
else pass.firstOrNull()
?.let { lastNum ->
lastNum.firstOrNull()?.let {
FilterResult(it, listOf(lastNum.substring(1)), emptyList())
}
}
}
fun rating(ratingMethod: (List<String>) -> Char) =
ratingSeq(ratingMethod)
.map { it.bit }
.joinToString("")
.toInt(2)
val oxygen = rating(::oxygenRating)
val carbon = rating(::carbonRating)
println("oxygen: $oxygen")
println("carbon: $carbon")
println("life support: ${oxygen * carbon}")
}
data class FilterResult(val bit: Char, val pass: List<String>, val fail: List<String>)
fun FilterResult.get(i: Char): List<String> {
return if (i == bit) pass else fail
}
fun List<String>.filterForRating(ratingMethod: (List<String>) -> Char): FilterResult {
val bit = ratingMethod(this)
val (pass, fail) = this.partition { it.first() == bit }
.run {
Pair(
first.map { it.substring(1) },
second.map { it.substring(1) }
)
}
return FilterResult(
bit,
pass,
fail
)
}
| 0 | Kotlin | 0 | 0 | 2d72897e1202ee816aa0e4834690a13f5ce19747 | 2,562 | aoc-kotlin | Apache License 2.0 |
aoc-2023/src/main/kotlin/aoc/aoc8.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.getDayInput
val testInput = """
LR
AAA = (11B, XXX)
11B = (XXX, ZZZ)
ZZZ = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)
""".parselines
class LeftRight(val left: String, val right: String)
fun String.parse() = chunk(0) to LeftRight(
chunk(2).substring(1..3),
chunk(3).substring(0..2))
// part 1
fun List<String>.part1(): Int {
val instruct = get(0)
val rules = drop(2).associate { it.parse() }
return stepsTo(start = "AAA", end = { it == "ZZZ" }, instruct, rules)
}
fun stepsTo(start: String, end: (String) -> Boolean, instruct: String, rules: Map<String, LeftRight>): Int {
var steps = 0
var cur = start
while (!end(cur)) {
val r = instruct[steps % instruct.length]
when (r) {
'L' -> cur = rules[cur]!!.left
'R' -> cur = rules[cur]!!.right
}
steps++
}
return steps
}
// part 2
fun List<String>.part2(): Long {
val instruct = get(0)
val rules = drop(2).associate { it.parse() }
val starts = rules.keys.filter { it.last() == 'A' }
val steps = starts.map { stepsTo(it, { it.last() == 'Z' }, instruct, rules) }
println(steps)
return steps.leastCommonMultiple()
}
fun List<Int>.leastCommonMultiple(): Long {
val list = toMutableList()
var lcm = 1L
var divisor = 2
while (list.any { it > 1 }) {
if (list.any { it % divisor == 0 }) {
lcm *= divisor
list.forEachIndexed { index, i ->
if (i % divisor == 0)
list[index] = i / divisor
}
} else {
divisor++
}
}
return lcm
}
// calculate answers
val day = 8
val input = getDayInput(day, 2023)
val testResult = testInput.part1()
val testResult2 = testInput.part2()
val answer1 = input.part1().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 2,114 | advent-of-code | Apache License 2.0 |
2021/src/main/kotlin/day13.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.IntGrid
import utils.MutableIntGrid
import utils.Parser
import utils.Solution
import utils.Vec2i
fun main() {
Day13.run()
}
object Day13 : Solution<Pair<IntGrid, List<Day13.FoldInsn>>>() {
override val name = "day13"
override val parser = Parser { input ->
val (ptsLines, insnLines) = input.split("\n\n", limit = 2)
val pts = ptsLines.split("\n").filter { it.isNotBlank() }.map {
val (x, y) = it.split(",")
Vec2i(x.toInt(), y.toInt())
}
val w = pts.maxOf { it.x } + 1
val h = pts.maxOf { it.y } + 1
val grid = MutableIntGrid(IntArray(w * h), w, h).apply {
pts.forEach { this[it] = 1 }
}
val insns = insnLines.split("\n").filter { it.isNotBlank() }.map {
val (direction, location) = it.split("=")
when (direction) {
"fold along y" -> FoldInsn(true, location.toInt())
"fold along x" -> FoldInsn(false, location.toInt())
else -> throw IllegalArgumentException("Bad input")
}
}
return@Parser (grid as IntGrid) to insns
}
fun foldH(grid: IntGrid, location: Int): IntGrid {
return MutableIntGrid(IntArray(grid.width * location), grid.width, location).apply {
coords.forEach { c ->
val mc = Vec2i(c.x, location + (location - c.y))
this[c] = grid[c] + if (mc in grid) grid[mc] else 0
}
}
}
fun foldV(grid: IntGrid, location: Int): IntGrid {
return MutableIntGrid(IntArray(location * grid.height), location, grid.height).apply {
coords.forEach { c ->
val mc = Vec2i(location + (location - c.x), c.y)
this[c] = grid[c] + if (mc in grid) grid[mc] else 0
}
}
}
fun fold(grid: IntGrid, insn: FoldInsn): IntGrid {
if (insn.horizontal) {
return foldH(grid, insn.location)
} else {
return foldV(grid, insn.location)
}
}
data class FoldInsn(val horizontal: Boolean, val location: Int)
override fun part1(input: Pair<IntGrid, List<FoldInsn>>): Int {
val folded = fold(input.first, input.second.first())
return folded.values.count { it != 0 }
}
override fun part2(input: Pair<IntGrid, List<FoldInsn>>): Int {
val result = input.second.fold(input.first) { grid, insn -> fold(grid, insn) }
for (y in 0 until result.height) {
for (x in 0 until result.width) {
if (result[x][y] != 0) {
print('#')
} else {
print('.')
}
}
println()
}
return 0
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,463 | aoc_kotlin | MIT License |
src/main/kotlin/io/matrix/IslandPerimeter.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.matrix
import io.utils.runTests
import java.util.*
// https://leetcode.com/problems/island-perimeter/
class IslandPerimeter {
fun execute(input: Array<IntArray>): Int {
input.forEachIndexed { row, rowValue ->
rowValue.forEachIndexed { col, value ->
if (value == 1) return calculateIslandPerimeter(input, row, col)
}
}
return 0
}
private fun calculateIslandPerimeter(input: Array<IntArray>, initialRow: Int, initialCol: Int): Int {
var result = 0
val visited = mutableSetOf<Pair<Int, Int>>()
val stack = LinkedList<Pair<Int, Int>>().apply { add(initialRow to initialCol) }
while (stack.isNotEmpty()) {
val (row, col) = stack.pop()
if (!visited.contains(row to col)) {
visited.add(row to col)
result += calculatePerimeter(input, row, col)
generateNeighbors(input, row, col, visited).forEach { stack.push(it) }
}
}
return result
}
private fun calculatePerimeter(input: Array<IntArray>, row: Int, col: Int): Int {
var result = 0
if (row - 1 < 0 || input[row - 1][col] == 0) result++
if (row + 1 == input.size || input[row + 1][col] == 0) result++
if (col - 1 < 0 || input[row][col - 1] == 0) result++
if (col + 1 == input.first().size || input[row][col + 1] == 0) result++
return result
}
private fun generateNeighbors(input: Array<IntArray>, row: Int, col: Int, visited: Set<Pair<Int, Int>>): List<Pair<Int, Int>> =
mutableListOf<Pair<Int, Int>>().apply {
if (!visited.contains(row - 1 to col) && row - 1 >= 0 && input[row - 1][col] == 1) add(row - 1 to col)
if (!visited.contains(row + 1 to col) && row + 1 < input.size && input[row + 1][col] == 1) add(row + 1 to col)
if (!visited.contains(row to col - 1) && col - 1 >= 0 && input[row][col - 1] == 1) add(row to col - 1)
if (!visited.contains(row to col + 1) && col + 1 < input.first().size && input[row][col + 1] == 1) add(row to col + 1)
}
}
fun main() {
runTests(listOf(
arrayOf(
intArrayOf(0, 1, 0, 0),
intArrayOf(1, 1, 1, 0),
intArrayOf(0, 1, 0, 0),
intArrayOf(1, 1, 0, 0)
) to 16
)) { (input, value) -> value to IslandPerimeter().execute(input) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 2,257 | coding | MIT License |
src/Day20.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import java.util.LinkedList
object Day20 {
const val EXPECTED_PART1_CHECK_ANSWER = 3
const val EXPECTED_PART2_CHECK_ANSWER = 1623178306L
val ANSWER_POSITIONS = setOf(1000, 2000, 3000)
const val DECRYPTION_KEY = 811589153L
}
fun main() {
fun List<String>.parse() = map(String::toLong).foldIndexed(LinkedList<Pair<Long, Int>>()) { idx, acc, nr ->
acc.add(nr to idx)
acc
}
fun LinkedList<Pair<Long, Int>>.mixIt(orgList: List<Pair<Long, Int>>) {
orgList.forEach { nrAndOrgIndex ->
val nr = nrAndOrgIndex.first
val currentIndex = indexOf(nrAndOrgIndex)
val uncappedNewIndex = currentIndex + nr
val moveToIndex = uncappedNewIndex.mod(lastIndex)
remove(nrAndOrgIndex)
add(moveToIndex, nrAndOrgIndex)
}
}
fun part1(input: List<String>): Int {
val numbers = input.parse()
val newList = LinkedList(numbers)
newList.mixIt(numbers)
println(newList)
val indexOfZero = newList.indexOf(newList.find { it.first == 0L })
val result = Day20.ANSWER_POSITIONS.sumOf {
val indexOfNr = indexOfZero + it
val wrappedIndex = indexOfNr % newList.size
newList[wrappedIndex].first
}
return result.toInt()
}
fun part2(input: List<String>): Long {
val numbers = input.parse().map { Pair(it.first * Day20.DECRYPTION_KEY, it.second) }
val newList = LinkedList(numbers)
repeat(10) { newList.mixIt(numbers) }
println(newList)
val indexOfZero = newList.indexOf(newList.find { it.first == 0L })
val result = Day20.ANSWER_POSITIONS.map(Int::toLong).sumOf {
val indexOfNr = indexOfZero + it
val wrappedIndex = indexOfNr % newList.size
newList[wrappedIndex.toInt()].first
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == Day20.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day20.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 2,287 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/endredeak/aoc2022/Day16.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
import kotlin.math.max
fun main() {
solve("Proboscidea Volcanium") {
println("PART 2 takes around a minute!")
val input = lines
.map { it.split(" ", "=", "; ", ", ").filter { s -> s.none { c -> c.isLowerCase() } } }
.map { l -> Triple(l[0], l[1].toInt(), l.drop(2)) }
val valves = input.associateBy { it.first }
fun floydWarshall(): MutableMap<String, MutableMap<String, Int>> {
val res = input
.associate {
it.first to it.third
.associateWith { 1 }
.toMutableMap()
}.toMutableMap()
for (k in res.keys) {
for (i in res.keys) {
for (j in res.keys) {
val ik = res[i]?.get(k) ?: 9999
val kj = res[k]?.get(j) ?: 9999
val ij = res[i]?.get(j) ?: 9999
if (ik + kj < ij) res[i]?.set(j, ik + kj)
}
}
}
res.values.forEach { paths ->
paths.keys.filter { valves[it]?.second == 0 }.forEach { paths.remove(it) }
}
return res
}
val shortestPaths = floydWarshall()
var score = 0
fun dfs(maxTime: Int, s: Int, curr: String, seen: Set<String>, t: Int, e: Int = 0) {
score = max(score, s)
shortestPaths[curr]!!
.filter { (v, d) -> v !in seen && t + d + 1 < maxTime }
.forEach { (v, d) ->
val diff = t+d+1
dfs(maxTime, s + (maxTime-diff) * valves[v]!!.second, v, seen.plus(v), diff, e)
}
repeat(e) { dfs(maxTime, s, "AA", seen, 0, 0) }
}
part1(2080) { dfs(30, 0, "AA", emptySet(), 0); score }
score = 0
part2(2752) { dfs(26, 0, "AA", emptySet(), 0, 1); score }
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 1,992 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/Day08.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | fun main() {
fun part1(input: List<String>): Int {
val grid = parseInput(input)
return (1 until grid.size - 1).sumOf { y ->
(1 until grid[y].size - 1).count { x ->
grid.isVisible(x, y)
}
} + (2 * grid.size) + (2 * grid[0].size) - 4
}
fun part2(input: List<String>): Int {
val grid = parseInput(input)
return (1 until grid.size - 1).maxOf { y ->
(1 until grid[y].size - 1).maxOf { x ->
grid.scoreAt(x, y)
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun parseInput(input: List<String>): Array<IntArray> =
input.map { row -> row.map(Char::digitToInt).toIntArray() }.toTypedArray()
private fun Array<IntArray>.viewFrom(x: Int, y: Int): List<List<Int>> =
listOf(
(y - 1 downTo 0).map { this[it][x] },
(y + 1 until this.size).map { this[it][x] },
this[y].take(x).asReversed(),
this[y].drop(x + 1)
)
private fun Array<IntArray>.isVisible(x: Int, y: Int): Boolean =
viewFrom(x, y).any { direction ->
direction.all { it < this[y][x] }
}
private fun Array<IntArray>.scoreAt(x: Int, y: Int): Int =
viewFrom(x, y).map { direction ->
direction.takeUntil { it >= this[y][x] }.count()
}.product() | 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 1,552 | advent-of-code-2022 | Apache License 2.0 |
src/d02/Day02.kt | Ezike | 573,181,935 | false | {"Kotlin": 7967} | package d02
import readInput
enum class Card(val value: Int) {
Rock(1),
Paper(2),
Scissors(3)
}
fun Card.next() = when (this) {
Card.Rock -> Card.Paper
Card.Paper -> Card.Scissors
Card.Scissors -> Card.Rock
}
fun Card.prev() = when (this) {
Card.Rock -> Card.Scissors
Card.Paper -> Card.Rock
Card.Scissors -> Card.Paper
}
enum class Opponent(val card: Card) {
A(Card.Rock),
B(Card.Paper),
C(Card.Scissors);
}
enum class Strategy(val card: Card, val result: Result) {
X(Card.Rock, Result.Lose),
Y(Card.Paper, Result.Draw),
Z(Card.Scissors, Result.Win);
}
enum class Result(val score: Int) {
Win(6),
Draw(3),
Lose(0)
}
fun main() {
fun part1(opponent: Opponent, strategy: Strategy): Int =
when (opponent.card) {
strategy.card -> Result.Draw
strategy.card.prev() -> Result.Win
else -> Result.Lose
}.score + strategy.card.value
fun part2(opponent: Opponent, strategy: Strategy): Int {
val card = when (strategy.result) {
Result.Win -> opponent.card.next()
Result.Draw -> opponent.card
Result.Lose -> opponent.card.prev()
}
return card.value + strategy.result.score
}
val oppMap = Opponent.values().associateBy { it.name }
val strategyMap = Strategy.values().associateBy { it.name }
val input = readInput("d02/Day02_test")
.map { it.split(" ") }
val result1 = input.sumOf { (a, b) -> part1(oppMap[a]!!, strategyMap[b]!!) }
val result2 = input.sumOf { (a, b) -> part2(oppMap[a]!!, strategyMap[b]!!) }
println(result1)
println(result2)
} | 0 | Kotlin | 0 | 0 | 07ed8acc2dcee09cc4f5868299a8eb5efefeef6d | 1,675 | advent-of-code | Apache License 2.0 |
src/aoc2023/Day5.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2023
import utils.checkEquals
import utils.readInputAsText
fun main(): Unit = with(Day5) {
part1(testInput).checkEquals(35)
part1(input)
.checkEquals(84470622)
// .sendAnswer(part = 1, day = "5", year = 2023)
part2(testInput).checkEquals(46)
part2(input)
.checkEquals(26714516)
// .sendAnswer(part = 2, day = "5", year = 2023)
}
object Day5 {
data class PlantMap(
val sourceRange: LongRange,
val desRange: LongRange,
) {
fun getCorrespondingDestination(currTrack: Long): Long {
val step = currTrack - sourceRange.first
return desRange.first + step
}
}
fun part1(input: String): Long {
val parts = input.split("\n\n")
val seeds = parts.first().substringAfter("seeds: ").split(' ').map { it.toLong() }
val seedPlantPath: List<List<PlantMap>> = parts.drop(1).parseTypesMapsToList()
return seeds.minOf { seed ->
return@minOf seedPlantPath.getLocationTrackedFromSeed(seed)
}
}
fun part2(input: String): Long {
val parts = input.split("\n\n")
val seeds = parts.first().substringAfter("seeds: ").split(' ')
.chunked(2)
.map {
val seedN = it[0].toLong()
val range = it[1].toLong()
seedN..<seedN + range
}
.asSequence()
.flatMap {
it.asSequence()
}
val seedPlantPath: List<List<PlantMap>> = parts.drop(1).parseTypesMapsToList()
return seeds.minOf { seed ->
return@minOf seedPlantPath.getLocationTrackedFromSeed(seed)
}
}
/**
* maps here is sorted as it parsed, that important.
*/
private fun List<String>.parseTypesMapsToList(): List<List<PlantMap>> = map {
val currMapRangesWithoutTitle = it.split("\n").drop(1)
currMapRangesWithoutTitle.map {
val (desRange, sourceRange, len) = it.split(' ').map { it.toLong() }
PlantMap(
sourceRange..<sourceRange + len,
desRange..<desRange + len
)
}
}
private fun List<List<PlantMap>>.getLocationTrackedFromSeed(
seed: Long
) = fold(seed) { currTrack: Long, nextMap: List<PlantMap> ->
val nextCorrespondingNumber = nextMap
.firstOrNull { currTrack in it.sourceRange }
?.getCorrespondingDestination(currTrack)
return@fold nextCorrespondingNumber ?: currTrack
}
val input
get() = readInputAsText("Day5", "aoc2023")
val testInput
get() = readInputAsText("Day5_test", "aoc2023")
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 2,722 | Kotlin-AOC-2023 | Apache License 2.0 |
y2017/src/main/kotlin/adventofcode/y2017/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
import adventofcode.y2017.Day22.Health.*
object Day22 : AdventSolution(2017, 22, "Sporifica Virus") {
override fun solvePartOne(input: String): String {
val map: MutableMap<Point, Health> = parseInput(input)
val weakWorm = object : Worm() {
override fun action(health: Health): Pair<Health, Direction> =
when (health) {
INFECTED -> Pair(HEALTHY, direction.right())
else -> Pair(INFECTED, direction.left())
}
}
repeat(10000) { weakWorm.burst(map) }
return weakWorm.infectionsCount.toString()
}
override fun solvePartTwo(input: String): String {
val map: MutableMap<Point, Health> = parseInput(input)
val strongWorm = object : Worm() {
override fun action(health: Health): Pair<Health, Direction> =
Pair(health.next(), when (health) {
HEALTHY -> direction.left()
WEAKENED -> direction
INFECTED -> direction.right()
FLAGGED -> direction.reverse()
})
}
repeat(10_000_000) { strongWorm.burst(map) }
return strongWorm.infectionsCount.toString()
}
abstract class Worm {
private var position = Point(0, 0)
protected var direction = Direction.UP
var infectionsCount = 0
fun burst(map: MutableMap<Point, Health>) {
val (newHealth, newDirection) = action(map[position] ?: HEALTHY)
map[position] = newHealth
direction = newDirection
position += direction.vector
if (newHealth == INFECTED) infectionsCount++
}
protected abstract fun action(health: Health): Pair<Health, Direction>
}
private fun parseInput(input: String): MutableMap<Point, Health> = input.lines()
.mapIndexed { y, row ->
row.mapIndexed { x, char ->
val position = Point(x - row.length / 2, y - row.length / 2)
val state = if (char == '#') INFECTED else HEALTHY
position to state
}
}
.flatten().toMap().toMutableMap()
enum class Health {
HEALTHY, WEAKENED, INFECTED, FLAGGED;
fun next() = values().let { it[(it.indexOf(this) + 1) % it.size] }
}
enum class Direction(val vector: Point) {
UP(Point(0, -1)), RIGHT(Point(1, 0)), DOWN(Point(0, 1)), LEFT(Point(-1, 0));
fun left() = turn(3)
fun right() = turn(1)
fun reverse() = turn(2)
private fun turn(i: Int): Direction = values().let { it[(it.indexOf(this) + i) % it.size] }
}
data class Point(val x: Int, val y: Int) {
operator fun plus(o: Point) = Point(x + o.x, y + o.y)
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,433 | advent-of-code | MIT License |
src/day11/Day11.kt | lpleo | 572,702,403 | false | {"Kotlin": 30960} | package day11
import readInput
import java.util.DoubleSummaryStatistics
import kotlin.math.floor
private const val FILES_DAY_TEST = "files/Day11_test"
private const val FILES_DAY = "files/Day11"
abstract class Monkey(var worryLevels: ArrayDeque<Double>, var percent: Double) {
var itemInspected = 0L;
abstract fun operation(worryLevel: Double): Double
abstract fun nextMonkey(worryLevel: Double): Int
fun divideLevel(worryLevel: Double): Double {
if (worryLevel % percent == 0.0 && worryLevel > percent) {
return worryLevel / percent;
}
return worryLevel
}
fun countItem() {
itemInspected++
}
}
fun main() {
fun part1(input: List<String>): Long {
val monkeyList = if (input.size < 40) {
listOf(TestMonkey0(), TestMonkey1(), TestMonkey2(), TestMonkey3());
} else {
listOf(Monkey0(), Monkey1(), Monkey2(), Monkey3(), Monkey4(), Monkey5(), Monkey6(), Monkey7());
}
for (i in 0 until 20) {
monkeyList.forEach { monkey ->
monkey.worryLevels.forEach { worryLevel ->
val newWorryLevel = floor(monkey.operation(worryLevel).toDouble() / 3.0)
monkeyList[monkey.nextMonkey(newWorryLevel)].worryLevels.addLast(newWorryLevel)
monkey.countItem()
}
monkey.worryLevels = ArrayDeque();
}
}
return monkeyList.sortedBy { monkey -> monkey.itemInspected }.reversed().subList(0, 2)
.map { monkey -> monkey.itemInspected }.reduce { a, b -> a * b }
}
fun part2(input: List<String>): Long {
var monkeyList: List<Monkey>
var magicNumber = 0.0;
if (input.size < 40) {
monkeyList = listOf(TestMonkey0(), TestMonkey1(), TestMonkey2(), TestMonkey3());
magicNumber = 23.0 * 19.0 * 13.0 * 17.0;
} else {
monkeyList = listOf(Monkey0(), Monkey1(), Monkey2(), Monkey3(), Monkey4(), Monkey5(), Monkey6(), Monkey7());
magicNumber =
monkeyList.map { monkey -> monkey.percent }.reduce { accumulator, percent -> accumulator * percent }
}
for (i in 0 until 10000) {
monkeyList.forEach { monkey ->
monkey.worryLevels.forEach { worryLevel ->
var newWorryLevel = monkey.operation(worryLevel)
newWorryLevel %= magicNumber
monkeyList[monkey.nextMonkey(newWorryLevel)].worryLevels.addLast(newWorryLevel)
monkey.countItem()
}
monkey.worryLevels = ArrayDeque();
}
if (i + 1 == 1 || i + 1 == 20 || i + 1 == 1000 || i + 1 == 2000 || i + 1 == 3000 || i + 1 == 4000) {
monkeyList.forEach { monkey -> println("$monkey -> ${monkey.itemInspected}") }
println()
}
}
return monkeyList.sortedBy { monkey -> monkey.itemInspected }.reversed().subList(0, 2)
.map { monkey -> monkey.itemInspected }.reduce { a, b -> a * b }
}
println(part1(readInput(FILES_DAY_TEST)))
// check(part1(readInput(FILES_DAY_TEST)) == 10605L)
println(part2(readInput(FILES_DAY_TEST)))
check(part2(readInput(FILES_DAY_TEST)) == 2713310158)
val input = readInput(FILES_DAY)
//println(part1(input))
println(part2(input))
}
class TestMonkey0() : Monkey(ArrayDeque(mutableListOf(79.0, 98.0)), 23.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel * 19
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 2
}
return 3
}
}
class TestMonkey1() : Monkey(ArrayDeque(mutableListOf(54.0, 65.0, 75.0, 74.0)), 19.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 6
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 2
}
return 0
}
}
class TestMonkey2() : Monkey(ArrayDeque(mutableListOf(79.0, 60.0, 97.0)), 13.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel * worryLevel
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 1
}
return 3
}
}
class TestMonkey3() : Monkey(ArrayDeque(mutableListOf(74.0)), 17.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 3
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 0
}
return 1
}
}
class Monkey0 : Monkey(ArrayDeque(mutableListOf(54.0, 98.0, 50.0, 94.0, 69.0, 62.0, 53.0, 85.0)), 3.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel * 13
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 2
}
return 1
}
}
class Monkey1 : Monkey(ArrayDeque(mutableListOf(71.0, 55.0, 82.0)), 13.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 2
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 7
}
return 2
}
}
class Monkey2 : Monkey(ArrayDeque(mutableListOf(77.0, 73.0, 86.0, 72.0, 87.0)), 19.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 8
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 4
}
return 7
}
}
class Monkey3 : Monkey(ArrayDeque(mutableListOf(97.0, 91.0)), 17.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 1
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 6
}
return 5
}
}
class Monkey4 : Monkey(ArrayDeque(mutableListOf(78.0, 97.0, 51.0, 85.0, 66.0, 63.0, 62.0)), 5.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel * 17
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 6
}
return 3
}
}
class Monkey5 : Monkey(ArrayDeque(mutableListOf(88.0)), 7.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 3
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 1
}
return 0
}
}
class Monkey6 : Monkey(ArrayDeque(mutableListOf(87.0, 57.0, 63.0, 86.0, 87.0, 53.0)), 11.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel * worryLevel
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 5
}
return 0
}
}
class Monkey7 : Monkey(ArrayDeque(mutableListOf(73.0, 59.0, 82.0, 65.0)), 2.0) {
override fun operation(worryLevel: Double): Double {
return worryLevel + 6
}
override fun nextMonkey(worryLevel: Double): Int {
if (worryLevel % percent == 0.0) {
return 4
}
return 3
}
}
| 0 | Kotlin | 0 | 0 | 115aba36c004bf1a759b695445451d8569178269 | 7,430 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day04.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | fun main() {
fun calculate(input: List<String>, isOverlap: (IntRange, IntRange) -> Boolean): Int = input.map {
val ranges = it.split(",")
val leftRange = ranges[0].split("-").let { range -> range[0].toInt()..range[1].toInt() }
val rightRange = ranges[1].split("-").let { range -> range[0].toInt()..range[1].toInt() }
if (isOverlap(leftRange, rightRange)) 1 else 0
}.sum()
fun part1(input: List<String>): Int = calculate(input) { leftRange, rightRange ->
(leftRange.contains(rightRange.first) && leftRange.contains(rightRange.last)) ||
rightRange.contains(leftRange.first) && rightRange.contains(leftRange.last)
}
fun part2(input: List<String>): Int = calculate(input) { leftRange, rightRange ->
leftRange.contains(rightRange.first) || leftRange.contains(rightRange.last) ||
rightRange.contains(leftRange.first) || rightRange.contains(leftRange.last)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
println(part2(testInput))
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 1,231 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | papichulo | 572,669,466 | false | {"Kotlin": 16864} | data class Dir(
var name: String,
var size: Long = 0L,
var parent: Dir?
)
fun main() {
fun calculateSize(dir: Dir, addSize: Long) {
dir.size += addSize
if (dir.parent != null) calculateSize(dir.parent!!, addSize)
}
fun parseLine(line: List<String>, current: Dir, dirs: MutableMap<String, Dir>): Dir {
println(line)
when (line[0]) {
"$" -> {
return if (line[1] == "cd") {
if (line[2] == "..") current.parent!! else if (line[2].startsWith("/")) dirs[line[2]]!! else dirs["${current.name}/${line[2]}"]!!
} else {
current
}
}
"dir" -> {
val newDir = Dir("${current.name}/${line[1]}", parent = current)
dirs[newDir.name] = newDir
}
else -> calculateSize(current, line[0].toLong())
}
return current
}
fun parseDirs(input: List<String>): Map<String, Dir> {
val dirs = mutableMapOf<String, Dir>()
var current = Dir("/", parent = null)
dirs[current.name] = current
input.forEach { line ->
current = parseLine(line.split(" "), current, dirs)
}
return dirs
}
fun part1(input: List<String>): Long {
return parseDirs(input).values.filter { it.size < 100_000L }.sumOf { it.size }
}
fun part2(input: List<String>): Long {
val dirs = parseDirs(input)
return dirs.values.filter { 70_000_000 - dirs["/"]!!.size + it.size >= 30_000_000 }.minBy { it.size }.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e277ee5bca823ce3693e88df0700c021e9081948 | 1,900 | aoc-2022-in-kotlin | Apache License 2.0 |
aoc2016/src/main/kotlin/io/github/ajoz/aoc16/Day3.kt | ajoz | 116,427,939 | false | null | package io.github.ajoz.aoc16
import java.io.File
/**
* Day 3: Squares With Three Sides
*
* -------------------- Part 1 -----------------------
*
* Now that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up
* this part of Easter Bunny HQ. This must be a graphic design department; the walls are covered in specifications for
* triangles.
*
* Or are they?
*
* The design document gives the side lengths of each triangle it describes, but... 5 10 25? Some of these aren't
* triangles. You can't help but mark the impossible ones.
*
* In a valid triangle, the sum of any two sides must be larger than the remaining side. For example, the "triangle"
* given above is impossible, because 5 + 10 is not larger than 25.
*
* In your puzzle inputDay3, how many of the listed triangles are possible?
*
* https://adventofcode.com/2016/day/3
*/
data class Specification(val a: Int, val b: Int, val c: Int)
val Specification?.isTriangle: Boolean
get() = when (this) {
null -> false
else -> (a + b > c) && (a + c > b) && (b + c > a)
}
fun toSpecification(list: List<String>): Specification? = when (list.size) {
3 -> Specification(list[0].toInt(), list[1].toInt(), list[2].toInt())
else -> null
}
fun getPart1ValidTrianglesCount(rows: List<String>) = rows
.map {
it.split(delimiters = " ")
.filter(String::isNotBlank)
}
.map(::toSpecification)
.filter(Specification?::isTriangle)
.count()
/**
* -------------------- Part 2 -----------------------
*
* Now that you've helpfully marked up their design documents, it occurs to you that triangles are specified in groups
* of three vertically. Each set of three numbers in a column specifies a triangle. Rows are unrelated.
*
* For example, given the following specification, numbers with the same hundreds digit would be part of the same
* triangle:
*
* 101 301 501
* 102 302 502
* 103 303 503
* 201 401 601
* 202 402 602
* 203 403 603
*
* In your puzzle inputDay3, and instead reading by columns, how many of the listed triangles are possible?
*
* https://adventofcode.com/2016/day/3
*/
fun getPart2ValidTrianglesCount(data: String): Int {
// unfortunately functions are not curried by default in Kotlin :(
// I need to the possibility to partially apply the function
fun getColumn(columns: List<String>): (Int) -> List<String> = { position ->
columns.drop(position).windowed(1, 3).flatten()
}
fun getTriangleCount(columns: List<String>) =
columns
.windowed(3, 3)
.map { toSpecification(it) }
.filter { it.isTriangle }
.count()
val columns = data.split(delimiters = " ")
.map { it.trim() }
.filter(String::isNotBlank)
return listOf(0, 1, 2).map(getColumn(columns)).map { getTriangleCount(it) }.sum()
}
val inputDay3 = File("src/main/resources/day3-puzzle-inputDay3")
fun main(args: Array<String>) {
println(getPart2ValidTrianglesCount(inputDay3.readText()))
println(getPart1ValidTrianglesCount(inputDay3.readLines()))
}
| 0 | Kotlin | 0 | 0 | 49ba07dd5fbc2949ed3c3ff245d6f8cd7af5bebe | 3,226 | challenges-kotlin | Apache License 2.0 |
src/main/aoc2022/Day12.kt | Clausr | 575,584,811 | false | {"Kotlin": 65961} | package aoc2022
import java.util.*
typealias Coordinates = Pair<Int, Int>
private fun Coordinates.getNeighbors(): List<Coordinates> {
val leftOf = Coordinates(first - 1, second)
val rightOf = Coordinates(first + 1, second)
val topOf = Coordinates(first, second - 1)
val bottomOf = Coordinates(first, second + 1)
return listOfNotNull(leftOf, rightOf, topOf, bottomOf)
}
class Day12(input: List<String>) {
private val heightMap = input.parseHeightMap()
data class HeightMap(val elevations: Map<Coordinates, Int>, val start: Coordinates, val end: Coordinates) {
fun shortestPath(
start: Coordinates,
isGoal: (Coordinates) -> Boolean,
canMove: (Int, Int) -> Boolean
): Int {
val seen = mutableSetOf<Coordinates>()
val prioQueue = PriorityQueue<PathCost>().apply { add(PathCost(start, 0)) }
while (prioQueue.isNotEmpty()) {
val nextCoord = prioQueue.poll()
if (nextCoord.coordinates !in seen) {
seen += nextCoord.coordinates
val neighbors = nextCoord.coordinates.getNeighbors()
.filter { it in elevations }
.filter { canMove(elevations.getValue(nextCoord.coordinates), elevations.getValue(it)) }
if (neighbors.any { isGoal(it) }) return nextCoord.cost + 1
prioQueue.addAll(neighbors.map { PathCost(it, nextCoord.cost + 1) })
}
}
throw IllegalStateException("No path...")
}
}
private class PathCost(val coordinates: Coordinates, val cost: Int) : Comparable<PathCost> {
override fun compareTo(other: PathCost): Int {
return this.cost.compareTo(other.cost)
}
}
private fun List<String>.parseHeightMap(): HeightMap {
var start: Coordinates? = null
var end: Coordinates? = null
val elevations = this.flatMapIndexed { y, row ->
row.mapIndexed { x, char ->
val here = Coordinates(x, y)
here to when (char) {
'S' -> 0.also { start = here }
'E' -> 25.also { end = here }
else -> char - 'a'
}
}
}.toMap()
return HeightMap(elevations, start!!, end!!)
}
fun solvePart1(): Int {
return heightMap.shortestPath(
start = heightMap.start,
isGoal = { it == heightMap.end },
canMove = { from, to -> to - from <= 1 }
)
}
fun solvePart2(): Int {
return heightMap.shortestPath(
start = heightMap.end,
isGoal = { heightMap.elevations[it] == 0 },
canMove = { from, to -> from - to <= 1 }
)
}
} | 1 | Kotlin | 0 | 0 | dd33c886c4a9b93a00b5724f7ce126901c5fb3ea | 2,845 | advent_of_code | Apache License 2.0 |
src/main/kotlin/com/github/davio/aoc/y2023/Day2.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2023
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsList
/**
* See [Advent of Code 2023 Day X](https://adventofcode.com/2023/day/2#part2])
*/
object Day2 : Day() {
private val bag = mapOf(
"red" to 12,
"green" to 13,
"blue" to 14
)
override fun part1(): Int {
val games = getInputAsList()
.map { it.toGame() }
.toList()
return games.filter { it.isPossible() }.sumOf { it.id }
}
override fun part2(): Long {
return getInputAsList().sumOf { it.toGame().getPower() }
}
private fun String.toGame(): Game {
val id = substringBefore(":").substringAfter("Game ").toInt()
return Game(id).also { game ->
substringAfter(": ").split("; ").forEach { cubePart ->
val subset = subsetOf(cubePart)
game.subsets.add(subset)
}
}
}
private data class Game(val id: Int) {
val subsets: MutableList<Map<String, Int>> = mutableListOf()
fun isPossible(): Boolean {
return subsets.all { subsetIsPossible(it) }
}
fun getPower(): Long {
val minimumCubes: MutableMap<String, Long> = mutableMapOf()
subsets.forEach { subset ->
subset.entries.forEach { entry ->
if (entry.value > minimumCubes.getOrPut(entry.key) { entry.value.toLong() }) {
minimumCubes[entry.key] = entry.value.toLong()
}
}
}
return minimumCubes.values.reduce { acc, e -> acc * e }
}
private fun subsetIsPossible(subset: Map<String, Int>): Boolean =
subset.all { bag.getValue(it.key) >= it.value }
}
private fun subsetOf(part: String): Map<String, Int> =
part.split(", ").map {
val (number, color) = it.split(" ")
color to number.toInt()
}.toMap()
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 2,023 | advent-of-code | MIT License |
src/main/kotlin/day02.kt | mgellert | 572,594,052 | false | {"Kotlin": 19842} | object RockPaperScissors : Solution {
fun scoreAllRounds(rounds: List<Pair<String, String>>): Int = rounds
.map { Pair(it.first.toHand(), it.second.toHand()) }
.sumOf { Hand.scoreRound(it.second, it.first) }
fun calculateHandAndScoreAllRounds(rounds: List<Pair<String, String>>): Int = rounds
.map { Pair(it.first.toHand(), it.second.toOutcome()) }
.map { Pair(it.first, Hand.calculateHandToPlay(it.second, it.first)) }
.sumOf { Hand.scoreRound(it.second, it.first) }
enum class Hand(private val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
companion object {
fun scoreRound(player: Hand, other: Hand): Int {
return player.score + when (Pair(player, other)) {
Pair(ROCK, ROCK) -> 3
Pair(ROCK, PAPER) -> 0
Pair(ROCK, SCISSORS) -> 6
Pair(PAPER, ROCK) -> 6
Pair(PAPER, PAPER) -> 3
Pair(PAPER, SCISSORS) -> 0
Pair(SCISSORS, ROCK) -> 0
Pair(SCISSORS, PAPER) -> 6
Pair(SCISSORS, SCISSORS) -> 3
else -> throw IllegalStateException()
}
}
fun calculateHandToPlay(outcome: Outcome, other: Hand): Hand {
return when (Pair(outcome, other)) {
Pair(Outcome.LOSE, ROCK) -> SCISSORS
Pair(Outcome.LOSE, PAPER) -> ROCK
Pair(Outcome.LOSE, SCISSORS) -> PAPER
Pair(Outcome.DRAW, ROCK) -> ROCK
Pair(Outcome.DRAW, PAPER) -> PAPER
Pair(Outcome.DRAW, SCISSORS) -> SCISSORS
Pair(Outcome.WIN, ROCK) -> PAPER
Pair(Outcome.WIN, PAPER) -> SCISSORS
Pair(Outcome.WIN, SCISSORS) -> ROCK
else -> throw IllegalStateException()
}
}
}
}
enum class Outcome {
LOSE, DRAW, WIN
}
fun readInput(): List<Pair<String, String>> = readInput("day02").readLines()
.map { it.split(" ") }
.filter { it.size == 2 }
.map { Pair(it[0], it[1]) }
private fun String.toHand(): Hand {
return when (this) {
"A", "X" -> Hand.ROCK
"B", "Y" -> Hand.PAPER
"C", "Z" -> Hand.SCISSORS
else -> throw IllegalArgumentException()
}
}
private fun String.toOutcome(): Outcome {
return when (this) {
"X" -> Outcome.LOSE
"Y" -> Outcome.DRAW
"Z" -> Outcome.WIN
else -> throw IllegalArgumentException()
}
}
}
| 0 | Kotlin | 0 | 0 | 4224c762ad4961b28e47cd3db35e5bc73587a118 | 2,729 | advent-of-code-2022-kotlin | The Unlicense |
14/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
const val LAST_STEP = 10
fun readInput() : Polymer {
val input = File("input.txt")
.readText()
.split("\r\n\r\n")
val original = input[0]
val rules = mutableMapOf<String, String>()
input[1].split("\n").filter{ it.isNotEmpty() }.forEach {
val regex = "(\\w+) -> (\\w+)".toRegex()
val (key, value) = regex.find(it)?.destructured!!
rules[key] = value
}
return Polymer(original, rules)
}
class Polymer(original : String, rules : Map<String, String>) {
private val original : String
private val rules : Map<String, String>
private val pairFreq = mutableMapOf<String, Int>()
private var steps = 0
init {
this.original = original
this.rules = rules
for (i in 1 until original.length) {
val pair = original.substring(i - 1, i + 1)
pairFreq[pair] = pairFreq.getOrDefault(pair, 0) + 1
}
}
fun applyStep() {
steps++
val newPairs = mutableMapOf<String, Int>()
for ((key, value) in pairFreq) {
if (key in rules) {
val leftPair = key[0] + rules[key]!!
val rightPair = rules[key]!! + key[1]
newPairs[leftPair] = newPairs.getOrDefault(leftPair, 0) + value
newPairs[rightPair] = newPairs.getOrDefault(rightPair, 0) + value
pairFreq[key] = 0
}
}
for ((key, value) in newPairs) {
pairFreq[key] = pairFreq.getOrDefault(key, 0) + value
}
}
fun calc(): Int {
val elemFreq = mutableMapOf<Char, Int>()
elemFreq[original.last()] = 1
for ((key, value) in pairFreq) {
elemFreq[key[0]] = elemFreq.getOrDefault(key[0], 0) + value
}
val maxi = elemFreq.maxOf { it.value }
val mini = elemFreq.minOf { it.value }
return maxi - mini
}
}
fun solve(polymer : Polymer): Int {
for (i in 1..LAST_STEP) {
polymer.applyStep()
}
return polymer.calc()
}
fun main() {
val polymer = readInput()
val ans = solve(polymer)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,158 | advent-of-code-2021 | MIT License |
src/main/kotlin/io/github/aarjavp/aoc/day12/Day12.kt | AarjavP | 433,672,017 | false | {"Kotlin": 73104} | package io.github.aarjavp.aoc.day12
import io.github.aarjavp.aoc.readFromClasspath
class Day12 {
enum class CaveType { BIG, SMALL }
data class Node(val id: String, val neighbors: MutableSet<String>, val caveType: CaveType) {
constructor(id: String): this(
id = id, neighbors = mutableSetOf(),
caveType = if (id[0].isUpperCase()) { CaveType.BIG } else { CaveType.SMALL }
)
}
class Graph(
val nodes: Map<String, Node>,
val startingNodes: Set<String>,
val endingNodes: Set<String>,
)
fun parse(paths: Sequence<String>): Graph {
val nodes = mutableMapOf<String, Node>()
val startingNodes = mutableSetOf<String>()
val endingNodes = mutableSetOf<String>()
for (path in paths) {
val (left, right) = path.split('-')
when {
left == "start" -> startingNodes += right
left == "end" -> endingNodes += right
right == "start" -> startingNodes += left
right == "end" -> endingNodes += left
else -> {
nodes.computeIfAbsent(left, ::Node).neighbors.add(right)
nodes.computeIfAbsent(right, ::Node).neighbors.add(left)
}
}
}
return Graph(nodes, startingNodes, endingNodes)
}
data class Path(val traveledNodes: List<String>) {
operator fun plus(nodeId: String): Path = Path(traveledNodes = traveledNodes + nodeId)
override fun toString(): String {
return "start,${traveledNodes.joinToString(",")},end"
}
}
fun shouldSkipVisitPt1(path: Path, node: Node): Boolean {
return node.caveType == CaveType.SMALL && node.id in path.traveledNodes
}
fun shouldSkipVisitPt2(path: Path, node: Node): Boolean {
return node.caveType == CaveType.SMALL && node.id in path.traveledNodes
&& path.traveledNodes.asSequence().filter { it[0].isLowerCase() } //FIXME
.groupBy { it }.any { it.value.size > 1 }
}
fun findAllPaths(graph: Graph, visitStrategy: (Path, Node) -> Boolean = ::shouldSkipVisitPt1 ): List<Path> {
val pathsFound = mutableListOf<Path>()
val pathsToExplore = ArrayDeque<Pair<Path, String>>()
for (startingNode in graph.startingNodes) {
pathsToExplore.add(Path(traveledNodes = listOf()) to startingNode)
}
while (pathsToExplore.isNotEmpty()) {
val (path, nodeToVisit) = pathsToExplore.removeFirst()
val node = graph.nodes[nodeToVisit] ?: error("unexpectedly did not find $nodeToVisit")
// check if this node is something we can visit
if (node.caveType == CaveType.SMALL && visitStrategy(path, node)) {
continue
}
val newPath = path + nodeToVisit
if (nodeToVisit in graph.endingNodes) {
pathsFound += newPath
}
for (neighbor in node.neighbors) {
pathsToExplore.addLast(newPath to neighbor)
}
}
return pathsFound
}
}
fun main() {
val solution = Day12()
val graph = readFromClasspath("Day12.txt").useLines { lines -> solution.parse(lines) }
val allPaths = solution.findAllPaths(graph)
println(allPaths.size)
println(solution.findAllPaths(graph, solution::shouldSkipVisitPt2).size)
}
| 0 | Kotlin | 0 | 0 | 3f5908fa4991f9b21bb7e3428a359b218fad2a35 | 3,482 | advent-of-code-2021 | MIT License |
src/Day03.kt | chasebleyl | 573,058,526 | false | {"Kotlin": 15274} |
fun Char.toPriorityValue(): Int {
// LOWERCASE a-z 97-122
if (this.code in 97..122) return this.code - 96
// UPPERCASE A-Z 65-90, with a 26 priority drop due to uppercase (lowercase prioritized ahead of uppercase)
return this.code - 64 + 26
}
fun main() {
fun part1(input: List<String>): Int {
var prioritySum = 0
input.forEach { rucksack ->
val compartmentOne = rucksack.substring(0, (rucksack.length / 2))
val compartmentTwo = rucksack.substring((rucksack.length / 2))
compartment@ for (item in compartmentOne) {
if (compartmentTwo.contains(item)) {
prioritySum += item.toPriorityValue()
break@compartment
}
}
}
return prioritySum
}
fun part2(input: List<String>): Int {
var prioritySum = 0
for (groupCounter in 0..(input.size / 3 - 1)) {
val itemRedundancies = mutableSetOf<Char>()
val currentStartingIndex = groupCounter * 3
val elfOne = input[currentStartingIndex]
val elfTwo = input[currentStartingIndex+1]
val elfThree = input[currentStartingIndex+2]
for (item in elfOne) {
if (elfTwo.contains(item)) {
itemRedundancies.add(item)
}
}
elf@ for (item in itemRedundancies) {
if (elfThree.contains(item)) {
prioritySum += item.toPriorityValue()
break@elf
}
}
}
return prioritySum
}
val input = readInput("Day03")
val testInput = readInput("Day03_test")
// PART 1
check(part1(testInput) == 157)
println(part1(input))
// PART 2
check(part2(testInput) == 70)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | f2f5cb5fd50fb3e7fb9deeab2ae637d2e3605ea3 | 1,869 | aoc-2022 | Apache License 2.0 |
src/Day04/Day04.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day04
import readInput
import java.lang.Error
import java.util.BitSet
fun fullContained(leftPair: Pair<Int, Int>, rightPair: Pair<Int, Int>): Int {
if (leftPair.first >= rightPair.first && leftPair.second <= rightPair.second) {
return 1
} else if (rightPair.first >= leftPair.first && rightPair.second <= leftPair.second) {
return 1
}
return 0
}
fun partialOverlap(leftPair: Pair<Int, Int>, rightPair: Pair<Int, Int>): Int {
if (leftPair.first >= rightPair.first && leftPair.first <= rightPair.second) {
return 1
} else if (leftPair.second >= rightPair.first && leftPair.first <= rightPair.second) {
return 1
} else if (rightPair.first >= leftPair.first && rightPair.first <= leftPair.second) {
return 1
} else if (rightPair.second >= leftPair.first && rightPair.second <= leftPair.second) {
return 1
}
return 0
}
fun rowToPairs(row: String): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val splitRow = row.split(",")
val leftSide = splitRow[0].split("-")
val rightSide = splitRow[1].split("-")
return Pair(Pair(leftSide[0].toInt(), leftSide[1].toInt()), Pair(rightSide[0].toInt(), rightSide[1].toInt()))
}
fun main() {
fun part1(input: List<String>): Int {
var total = 0
for(row in input) {
val pairs = rowToPairs(row)
total += fullContained(pairs.first, pairs.second)
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
for(row in input) {
val pairs = rowToPairs(row)
total += partialOverlap(pairs.first, pairs.second)
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04","Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04","Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 1,989 | advent-of-code-2022 | Apache License 2.0 |
day9/src/main/kotlin/com/lillicoder/adventofcode2023/day9/Day9.kt | lillicoder | 731,776,788 | false | {"Kotlin": 98872} | package com.lillicoder.adventofcode2023.day9
fun main() {
val day9 = Day9()
val readings = ReadingsParser().parse("input.txt")
println("The sum of all next predictions for all sequences is ${day9.part1(readings)}.")
println("The sum of all previous predictions for all sequences is ${day9.part2(readings)}.")
}
class Day9 {
fun part1(readings: List<List<Long>>) = ReadingsPredictor().sumAllProceedingPredictions(readings)
fun part2(readings: List<List<Long>>) = ReadingsPredictor().sumAllPrecedingPredictions(readings)
}
class ReadingsPredictor {
/**
* Finds all predicted values that proceed the last reading in each of the given sequences
* and sums them.
* @param readings Sequence readings to predict.
* @return Sum of all proceeding predictions.
*/
fun sumAllProceedingPredictions(readings: List<List<Long>>) = readings.sumOf { predictNext(it) }
/**
* Finds all predicted values that precede the first reading in each of the given sequences
* and sums them.
* @param readings Sequence of readings to predict.
* @return Sum of all preceding predictions.
*/
fun sumAllPrecedingPredictions(readings: List<List<Long>>) = readings.sumOf { predictPreceding(it) }
/**
* Predicts the next value in the given sequence.
* @param sequence Sequence to predict.
* @return Next predicted value in the sequence.
*/
private fun predictNext(sequence: List<Long>): Long {
// We can predict solely by summing rightmost branch values as we go
var currentRow = sequence
var prediction = currentRow.last()
while (currentRow.last() != 0L) {
currentRow = currentRow.windowed(2, 1).map { it[1] - it[0] }
prediction += currentRow.last()
}
return prediction
}
/**
* Predicts the preceding value in the given sequence.
* @param sequence Sequence to predict.
* @return Preceding predicted value in the sequence.
*/
private fun predictPreceding(sequence: List<Long>): Long {
var currentRow = sequence
val leftmostBranch = mutableListOf(sequence.first())
while (!currentRow.all { it == 0L }) {
currentRow = currentRow.windowed(2, 1).map { it[1] - it[0] }
leftmostBranch.add(currentRow.first())
}
// Can't do a running value while windowing, need to process list in proper order
// from 0 to bottom level of the tree
return leftmostBranch.asReversed().reduce { accumulator, value ->
value - accumulator
}
}
}
class ReadingsParser {
fun parse(raw: List<String>) =
raw.map { line ->
line.split(" ").filter {
it.isNotEmpty()
}.map {
it.toLong()
}
}
/**
* Parses the file with the given filename in a list of reading sequences.
* @param filename Filename.
* @return List of reading sequences.
*/
fun parse(filename: String) = parse(javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines())
}
| 0 | Kotlin | 0 | 0 | 390f804a3da7e9d2e5747ef29299a6ad42c8d877 | 3,133 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/dec13/Main.kt | dladukedev | 318,188,745 | false | null | package dec13
import kotlin.math.ceil
fun getTimestamp(input: String): Int = input.lines().first().toInt()
fun getBusTimes(input: String): List<Int> = input
.lines()
.last()
.split(",")
.filter { it != "x" }
.map { it.toInt() }
fun getQuickestBus(target: Int, buses: List<Int>): Int {
return buses
.map {
val nearestTime = ceil(target.toDouble() / it) * it
it to nearestTime
}.minBy { it.second }!!
.first
}
fun calculateResult(target: Int, bus: Int): Int {
val nearestTime = ceil(target.toDouble() / bus) * bus
val waitTime = nearestTime.toInt() - target
return waitTime * bus
}
fun getBusSchedule(input: String): List<Pair<Int, Int>> {
return input
.lines()
.last()
.split(",")
.mapIndexed { index, bus -> Pair(bus, index) }
.filter { it.first != "x" }
.map { Pair(it.first.toInt(), it.second) }
}
fun getSequentialTime(buses: List<Pair<Int, Int>>): Long {
return buses.foldRight(Pair(0L, 1L)) { bus, acc ->
val (time, step) = acc
val newTime = (time..Long.MAX_VALUE step step)
.first { ((it + bus.second) % bus.first == 0L)}
val newStep = step*bus.first
Pair(newTime, newStep)
}.first
}
fun main() {
println("------------ PART 1 ------------")
val target = getTimestamp(input)
val buses = getBusTimes(input)
val quickestBus = getQuickestBus(target, buses)
val result = calculateResult(target, quickestBus)
println("result: $result")
println("------------ PART 2 ------------")
val busess = getBusSchedule(input)
val result2 = getSequentialTime(busess)
println("result: $result2")
}
| 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 1,726 | advent-of-code-2020 | MIT License |
jvm/src/main/kotlin/io/prfxn/aoc2021/day21.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // <NAME> (https://adventofcode.com/2021/day/21)
package io.prfxn.aoc2021
import kotlin.math.max
import kotlin.math.min
private typealias PositionAndScore = Pair<Int, Int>
fun main() {
val (p1sp, p2sp) = textResourceReader("input/21.txt").readLines().map { it.split(":").last().trim().toInt() }
val rollDice = generateSequence(0) { (it + 1) % 100 }.map(Int::inc).iterator()::next
fun rollDiceThrice() = generateSequence { rollDice() }.take(3).sum()
fun addToPosition(pos: Int, amt: Int) = 1 + ((pos - 1) + amt) % 10
// answer 1
val (turnCount, p1s, p2s) =
generateSequence(0 to listOf((p1sp to 0), (p2sp to 0))) { (currentPlayerIndex, players) ->
(currentPlayerIndex + 1) % players.size to
players.mapIndexed { i, player ->
if (i == currentPlayerIndex) {
val (pos, score) = player
val newPos = addToPosition(pos, rollDiceThrice())
(newPos to score + newPos)
}
else player
}
}
.mapIndexed { i, (_, players) -> Triple(i, players.first().second, players.last().second) }
.find { (_, s1, s2) -> s1 >= 1000 || s2 >= 1000 }!!
println(3 * turnCount * min(p1s, p2s))
// answer 2
val diracDiceThreeRollOutcomes =
(1..3).flatMap { one -> (1..3).flatMap { two -> (1..3).map { three -> one + two + three } } }
fun countWins(currentPlayerIndex: Int,
players: List<PositionAndScore>,
resultCache: MutableMap<Pair<Int, List<PositionAndScore>>, Pair<Long, Long>> = mutableMapOf()
): Pair<Long, Long> =
resultCache.getOrPut(currentPlayerIndex to players) {
when {
players[0].second >= 21 -> 1L to 0L
players[1].second >= 21 -> 0L to 1L
else ->
diracDiceThreeRollOutcomes
.map { amt ->
countWins(
(currentPlayerIndex + 1) % players.size,
players.mapIndexed { i, player ->
if (i == currentPlayerIndex) {
val (pos, score) = player
val newPos = addToPosition(pos, amt)
(newPos to score + newPos)
}
else player
},
resultCache
)
}
.reduce { (totalWins1, totalWins2), (wins1, wins2) ->
(totalWins1 + wins1) to (totalWins2 + wins2)
}
}
}
fun countWins(p1sp: Int, p2sp: Int) = countWins(0, listOf(p1sp to 0, p2sp to 0))
println(countWins(p1sp, p2sp).let { (wins1, wins2) -> max(wins1, wins2) })
}
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 3,074 | aoc2021 | MIT License |
src/Day04.kt | sgc109 | 576,491,331 | false | {"Kotlin": 8641} | fun main() {
fun isIncluded(p1: List<Int>, p2: List<Int>): Boolean {
return (p1[0] <= p2[0] && p1[1] >= p2[1]) ||
(p1[0] >= p2[0] && p1[1] <= p2[1])
}
fun isOverlapped(p1: List<Int>, p2: List<Int>): Boolean {
return !(p1[1] < p2[0] || p2[1] < p1[0])
}
fun toPairs(line: String) =
line.split(",").map { chunk ->
chunk.split("-").map { it.toInt() }
}
fun part1(input: List<String>): Int {
return input.map { line ->
val pairs = toPairs(line)
if (isIncluded(pairs[0], pairs[1])) {
1
} else {
0
}
}.sum()
}
fun part2(input: List<String>): Int {
return input.map { line ->
val pairs = toPairs(line)
if (isOverlapped(pairs[0], pairs[1])) {
1
} else {
0
}
}.sum()
}
val testInput = readLines("Day04_test")
val ans = part1(testInput)
println(ans)
check(ans == 2)
val input = readLines("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 03e4e85283d486430345c01d4c03419d95bd6daa | 1,156 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | /*
* Hindsight notes
* - yeah too much string typing here :-/
*/
fun main() {
fun getScore(key: String): Int {
/*
* Hindsight notes
* `when` here would allow multiple matches to the same value, like
* "AX", "BY", "CZ" -> 3 etc, which is more readable than this
*/
val points = mapOf<String, Int>(
"X" to 1, "Y" to 2, "Z" to 3,
"AX" to 3, "AY" to 6, "AZ" to 0,
"BX" to 0, "BY" to 3, "BZ" to 6,
"CX" to 6, "CY" to 0, "CZ" to 3)
return points.getOrDefault(key, 0) // silence the null
}
fun part1(input: List<String>): Int {
// Rock A X, Paper B Y, Scissors C Z
// var score = 0
// input.forEach {
// val (them: String, you: String) = it.split(' ')
// score += getScore(you)
// score += getScore(them + you)
// }
// return score
// let's try this with sumOf()
return input.sumOf {
val (them: String, you: String) = it.split(' ')
getScore(you) + getScore(them + you)
}
}
/*
* Hindsight notes.
* - Oops didn't need to calculate convertPlay here, because we're already told the desired outcome (lose, tie, win)
* and can infer the score directly from that.
* - OTOH this allows us to re-use the key bots of part1
*/
fun convertPlay(them: String, outcome: String): String {
val convert = mapOf<String, String>(
"AX" to "Z", "AY" to "X", "AZ" to "Y",
"BX" to "X", "BY" to "Y", "BZ" to "Z",
"CX" to "Y", "CY" to "Z", "CZ" to "X"
)
return convert.getOrDefault(them + outcome, "") // silence the null
}
fun part2(input: List<String>): Int {
// Rock A, Paper B, Scissors C
// Muse lose X, tie Y, win Z
var score = 0
input.forEach {
val (them: String, outcome: String) = it.split(' ')
val you = convertPlay(them, outcome)
score += getScore(you)
score += getScore(them + you)
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test.txt")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02.txt")
println(part1(input))
check(part1(input) == 8890)
println(part2(input))
check(part2(input) == 10238)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 2,478 | aoc2022 | Apache License 2.0 |
src/Day07.kt | lmoustak | 573,003,221 | false | {"Kotlin": 25890} | import kotlin.math.abs
abstract class DirectoryItem(open val name: String, open val parent: Directory?) {
abstract fun computeSize(): Int
}
data class File(override val name: String, val size: Int, override val parent: Directory) :
DirectoryItem(name, parent) {
override fun computeSize(): Int = size
}
data class Directory(override val name: String, override val parent: Directory? = null) :
DirectoryItem(name, parent) {
val children: MutableSet<DirectoryItem> = mutableSetOf()
override fun computeSize(): Int = children.sumOf { it.computeSize() }
}
fun main() {
val cdPattern = Regex("""\$ cd (\S+)""")
val lsPattern = "$ ls"
val filePattern = Regex("""(\d+) (\S+)""")
val dirPattern = Regex("""dir (\S+)""")
fun walk(input: List<String>): Directory {
val root = Directory("/")
var currentDirectory: Directory = root
var i = 0;
while (i < input.size) {
val command = input[i].trim()
if (cdPattern.matches(command)) {
val dir = cdPattern.matchEntire(command)!!.groupValues[1]
currentDirectory = when (dir) {
"/" -> root
".." -> currentDirectory.parent!!
else -> currentDirectory.children.find { it.name == dir } as Directory
}
i++
} else if (lsPattern == command) {
var item = input[++i].trim()
while (!item.startsWith('$')) {
if (filePattern.matches(item)) {
val matchGroups = filePattern.matchEntire(item)!!.groupValues
val fileName = matchGroups[2]
val fileSize = matchGroups[1].toInt()
currentDirectory.children.addIfNotPresent(
{ it.name == fileName },
File(fileName, fileSize, currentDirectory)
)
} else if (dirPattern.matches(item)) {
val name = dirPattern.matchEntire(item)!!.groupValues[1]
currentDirectory.children.addIfNotPresent(
{ it.name == name },
Directory(name, currentDirectory)
)
} else {
throw IllegalArgumentException("'$command' is not valid!")
}
if (++i >= input.size) break
item = input[i].trim()
}
} else {
throw IllegalArgumentException("'$command' is not valid!")
}
}
return root
}
fun part1(input: List<String>): Int {
var totalSize = 0
fun computeSize(directory: Directory) {
val size = directory.computeSize()
if (size <= 100_000) totalSize += size
directory.children.filterIsInstance<Directory>().forEach { computeSize(it) }
}
val root = walk(input)
computeSize(root)
return totalSize
}
fun part2(input: List<String>): Int {
val root = walk(input)
val spaceNeeded = abs(70_000_000 - 30_000_000 - root.computeSize())
val directories = mutableListOf<Pair<Directory, Int>>()
fun listDirectory(directory: Directory) {
directories += directory to directory.computeSize()
directory.children.filterIsInstance<Directory>().forEach { listDirectory(it) }
}
listDirectory(root)
return directories
.sortedByDescending { it.second }
.last { it.second >= spaceNeeded }
.second
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd259af405b557ab7e6c27e55d3c419c54d9d867 | 3,816 | aoc-2022-kotlin | Apache License 2.0 |
src/Day02.kt | qmchenry | 572,682,663 | false | {"Kotlin": 22260} | private sealed class RPS {
object Rock : RPS()
object Paper : RPS()
object Scissors : RPS()
fun beats(other: RPS): Boolean {
return when (this) {
Rock -> other == Scissors
Paper -> other == Rock
Scissors -> other == Paper
}
}
val winVs: RPS
get() = when (this) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
val loseVs: RPS
get() = when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
val drawVs: RPS
get() = when (this) {
Rock -> Rock
Paper -> Paper
Scissors -> Scissors
}
val points: Int
get() = when (this) {
Rock -> 1
Paper -> 2
Scissors -> 3
}
fun compete(other: RPS): Int {
return points + when {
this == other -> 3
this.beats(other) -> 6
else -> 0
}
}
companion object {
fun fromString(string: String): RPS {
return when (string.lowercase()) {
"a", "x" -> Rock
"b", "y" -> Paper
"c", "z" -> Scissors
else -> throw IllegalArgumentException("Unknown RPS: $string")
}
}
}
}
private sealed class RPSOutcome {
object Win : RPSOutcome()
object Draw : RPSOutcome()
object Lose : RPSOutcome()
fun rpsForOutcomeVs(otherPlayer: RPS): RPS {
return when (this) {
Win -> otherPlayer.winVs
Draw -> otherPlayer.drawVs
Lose -> otherPlayer.loseVs
}
}
val points: Int
get() = when (this) {
Win -> 6
Draw -> 3
Lose -> 0
}
companion object {
fun fromString(string: String): RPSOutcome {
return when (string.lowercase()) {
"x" -> Lose
"y" -> Draw
"z" -> Win
else -> throw IllegalArgumentException("Unknown RPSOutcome: $string")
}
}
}
}
fun main() {
fun naiveScore(input: List<String>): Int {
return input
.map { row ->
row
.split(" ")
.map { RPS.fromString(it) }
}
.map {
it[1].compete(it[0])
}
.sum()
}
fun strategicScore(input: List<String>): Int {
return input
.map {
val round = it.split(" ")
val player1 = RPS.fromString(round[0])
val outcome = RPSOutcome.fromString(round[1])
val player2 = outcome.rpsForOutcomeVs(player1)
outcome.points + player2.points
}
.sum()
}
fun part1(input: List<String>): Int {
return naiveScore(input)
}
fun part2(input: List<String>): Int {
return strategicScore(input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_sample")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val realInput = readInput("Day02_input")
println("Part 1: ${part1(realInput)}")
println("Part 2: ${part2(realInput)}")
}
| 0 | Kotlin | 0 | 0 | 2813db929801bcb117445d8c72398e4424706241 | 3,368 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day07.kt | Kanialdo | 573,165,497 | false | {"Kotlin": 15615} | import kotlin.math.min
fun main() {
class Node(
val name: String,
val parent: Node?,
val children: MutableList<Node> = mutableListOf(),
var size: Int = 0,
) {
fun print(index: Int = 0) {
println("-".padStart(index * 2, ' ') + " " + name)
children.forEach { it.print(index + 1) }
}
}
fun buildTree(input: List<String>): Node {
val root = Node(name = "/", parent = null)
var currentNode = root
input.drop(1).forEach { line ->
when {
line.startsWith("$ cd ..") -> currentNode = currentNode.parent ?: error("No parent")
line.startsWith("$ cd") -> {
val dir = line.drop(5)
currentNode = currentNode.children.first { it.name == dir }
}
line.startsWith("$ ls") -> Unit
line.startsWith("dir") -> {
val dir = line.drop(4)
currentNode.children.add(Node(name = dir, parent = currentNode))
}
else -> {
currentNode.size += line.split(" ").first().toInt()
}
}
}
fun Node.updateSize() {
children.forEach {
it.updateSize()
}
this.size += children.sumOf { it.size }
}
root.updateSize()
return root
}
fun part1(input: List<String>): Int {
val root = buildTree(input)
root.print()
fun Node.sum(): Int {
return children.sumOf { it.sum() } + if (size <= 100000) size else 0
}
return root.sum()
}
fun part2(input: List<String>): Int {
val root = buildTree(input)
val lookingSpace = 30000000 - (70000000 - root.size)
fun Node.findClosed(threshold: Int): Int {
return min(
a = children.minOfOrNull { it.findClosed(threshold) } ?: Int.MAX_VALUE,
b = if (size > threshold) size else Int.MAX_VALUE
)
}
return root.findClosed(lookingSpace)
}
val testInput = readInput("Day07_test")
check(part1(testInput), 95437)
check(part2(testInput), 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 10a8550a0a85bd0a928970f8c7c5aafca2321a4b | 2,358 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/09/Day09.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`09`
import kotlin.math.abs
import readInput
data class Position(
val x: Int,
val y: Int
)
data class Command(
val direction: Direction,
val amount: Int
) {
enum class Direction {
UP, DOWN, LEFT, RIGHT;
companion object {
fun from(string: String): Direction {
return when (string) {
"R" -> RIGHT
"L" -> LEFT
"D" -> DOWN
"U" -> UP
else -> error("!!!")
}
}
}
}
}
fun Position.move(direction: Command.Direction): Position {
return when (direction) {
Command.Direction.UP -> copy(y = y + 1)
Command.Direction.DOWN -> copy(y = y - 1)
Command.Direction.LEFT -> copy(x = x - 1)
Command.Direction.RIGHT -> copy(x = x + 1)
}
}
fun Position.follow(head: Position): Position {
val tailX = x
val tailY = y
val dX = head.x - tailX
val dY = head.y - tailY
val position = when {
abs(dX) <= 1 && abs(dY) <= 1 -> Position(tailX, tailY)
abs(dX) == 2 && abs(dY) == 2 -> Position(tailX + dX / 2, tailY + dY / 2)
abs(dX) == 2 && abs(dY) == 0 -> Position(tailX + dX / 2, tailY)
abs(dX) == 2 && abs(dY) == 1 -> Position(tailX + dX / 2, tailY + dY)
abs(dX) == 0 && abs(dY) == 2 -> Position(tailX, tailY + dY / 2)
abs(dX) == 1 && abs(dY) == 2 -> Position(tailX + dX, tailY + dY / 2)
else -> error("!! $dX $dY")
}
return position
}
fun main() {
fun parseInput(input: List<String>): List<Command> {
return input.map {
val (direction, amount) = it.split(" ")
Command(Command.Direction.from(direction), amount.toInt())
}
}
fun part1(input: List<String>): Int {
val visited: MutableSet<Position> = mutableSetOf()
var head = Position(0, 0)
var tail = Position(0, 0)
parseInput(input)
.forEach { command ->
repeat(command.amount) {
head = head.move(command.direction)
tail = tail.follow(head)
visited.add(tail)
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val visited: MutableSet<Position> = mutableSetOf()
val knotPositions = MutableList(10) { Position(0, 0) }
parseInput(input)
.forEach { command ->
repeat(command.amount) {
knotPositions.forEachIndexed { index, _ ->
knotPositions[index] = if (index == 0) {
knotPositions[0].move(command.direction)
} else {
knotPositions[index].follow(knotPositions[index - 1])
}
}
visited.add(knotPositions.last())
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val part1Test = part2(testInput)
println(part1Test)
check(part1Test == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,319 | KotlinAdventOfCode | Apache License 2.0 |
src/day04/Day04.kt | ignazio-castrogiovanni | 434,481,121 | false | {"Kotlin": 8657} | package day04
import readInput
fun main() {
val exampleInput = readInput("Day04_example", "day04")
var (numbers, boards) = parseInput(exampleInput)
println("Result for example values: ${part1(numbers, boards)}")
val input = readInput("Day04_test", "day04")
val (numbersData, boardsData) = parseInput(input)
println("Result for real data values: ${part1(numbersData, boardsData)}")
println("----------")
println("Result for example values: ${part2(numbers, boards)}")
println("Result for real data values: ${part2(numbersData, boardsData)}")
}
fun parseInput(input: List<String>): Pair<List<Int>, List<Board>> {
val numbers = input[0].split(",").map {
it.toInt()
}
val boards = mutableListOf<Board>()
var currentBoardValues = mutableListOf<MutableList<Int>>()
for (index in 2 until input.size) {
val currentRow = input[index].split(" ").filter { it != "" }.map { it.toInt() }.toMutableList()
if (!currentRow.isEmpty()) {
currentBoardValues.add(currentRow)
}
if (input[index].isEmpty()) {
boards.add(Board(currentBoardValues))
currentBoardValues = mutableListOf<MutableList<Int>>()
}
}
boards.add(Board(currentBoardValues))
return Pair(numbers, boards)
}
data class Board(val values: MutableList<MutableList<Int>>)
fun part1(numbers: List<Int>, boards: List<Board>): Int {
numbers.forEach { number ->
number
boards.forEach {
board ->
board.values.forEachIndexed() {
rowIndex, row -> row.forEachIndexed {
colIndex, value ->
if (value == number) {
board.values[rowIndex][colIndex] = 0
if(isBingo(board)) {
return sumAll(board) * number
}
}
}
}
}
}
return -1
}
fun sumAll(board: Board): Int {
var total = 0
board.values.forEach {
total += it.sum()
}
return total
}
fun isBingo(board: Board): Boolean {
board.values.forEach {
if (setIsBingo(it)) {
return true
}
}
for (index in board.values.indices) {
val set = mutableListOf(board.values[0][index], board.values[1][index], board.values[2][index], board.values[3][index], board.values[4][index])
if (setIsBingo(set)) {
return true
}
}
return false
}
fun setIsBingo(it: MutableList<Int>): Boolean {
return it.all { it == 0 }
}
fun part2(numbers: List<Int>, boards: List<Board>): Int {
val indexesToSkip = mutableSetOf<Int>()
var lastWinningBoard = Board(mutableListOf())
var lastNumber = -1
numbers.forEach { number ->
boards.forEachIndexed {
boardIndex, board ->
run forBoard@ {
if (boardIndex in indexesToSkip) return@forBoard
board.values.forEachIndexed() { rowIndex, row ->
row.forEachIndexed { colIndex, value ->
if (value == number) {
board.values[rowIndex][colIndex] = 0
if (isBingo(board)) {
indexesToSkip.add(boardIndex)
lastWinningBoard = board
lastNumber = number
}
}
}
}
}
}
}
return sumAll(lastWinningBoard) * lastNumber
}
| 0 | Kotlin | 0 | 0 | 5ce48ba58da7ec5f5c8b05e4430a652710a0b4b9 | 3,616 | advent_of_code_kotlin | Apache License 2.0 |
day-09/src/main/kotlin/SmokeBasin.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
private fun partOne(): Int {
val heightMap = readHeightMap()
val lowPoints = findLowPoints(heightMap)
return lowPoints.sumOf { heightMap[it.first][it.second] + 1 }
}
private fun partTwo(): Long {
val heightMap = readHeightMap()
val lowPoints = findLowPoints(heightMap)
var result = 1L
lowPoints.map {
findBasinSize(it, heightMap, 1, mutableListOf())
}.sortedDescending()
.take(3)
.forEach {
result *= it
}
return result
}
private fun readHeightMap(): List<MutableList<Int>> {
val heightMap = mutableListOf<MutableList<Int>>()
readInputLines()
.forEach {
val row = mutableListOf<Int>()
it.split("")
.filter { it.isNotBlank() }
.map { it.toInt() }
.map { row.add(it) }
heightMap.add(row)
}
return heightMap
}
private fun findLowPoints(heightMap: List<MutableList<Int>>): List<Pair<Int, Int>> {
val lowPoints = mutableListOf<Pair<Int, Int>>()
for (row in heightMap.indices) {
for (column in heightMap[0].indices) {
var isLowPoint = true
if (row - 1 in heightMap.indices) {
if (heightMap[row - 1][column] <= heightMap[row][column]) isLowPoint = false
}
if (row + 1 in heightMap.indices) {
if (heightMap[row + 1][column] <= heightMap[row][column]) isLowPoint = false
}
if (column - 1 in heightMap[0].indices) {
if (heightMap[row][column - 1] <= heightMap[row][column]) isLowPoint = false
}
if (column + 1 in heightMap[0].indices) {
if (heightMap[row][column + 1] <= heightMap[row][column]) isLowPoint = false
}
if (isLowPoint) {
lowPoints.add(Pair(row, column))
}
}
}
return lowPoints
}
fun findBasinSize(
point: Pair<Int, Int>,
map: List<List<Int>>,
initialSize: Int,
visited: MutableList<Pair<Int, Int>>
): Int {
visited.add(point)
var count = initialSize
val previousRow = Pair(point.first - 1, point.second)
if (previousRow.exists(map) &&
previousRow !in visited &&
previousRow.isNotNine(map) &&
previousRow.isHigher(point, map)
) {
count += findBasinSize(previousRow, map, 1, visited)
}
val nextRow = Pair(point.first + 1, point.second)
if (nextRow.exists(map) &&
nextRow !in visited &&
nextRow.isNotNine(map) &&
nextRow.isHigher(point, map)
) {
count += findBasinSize(nextRow, map, 1, visited)
}
val previousColumn = Pair(point.first, point.second - 1)
if (previousColumn.exists(map) &&
previousColumn !in visited &&
previousColumn.isNotNine(map) &&
previousColumn.isHigher(point, map)
) {
count += findBasinSize(previousColumn, map, 1, visited)
}
val nextColumn = Pair(point.first, point.second + 1)
if (nextColumn.exists(map) &&
nextColumn !in visited &&
nextColumn.isNotNine(map) &&
nextColumn.isHigher(point, map)
) {
count += findBasinSize(nextColumn, map, 1, visited)
}
return count
}
fun Pair<Int, Int>.isHigher(other: Pair<Int, Int>, map: List<List<Int>>) =
map[this.first][this.second] > map[other.first][other.second]
fun Pair<Int, Int>.isNotNine(map: List<List<Int>>) = map[this.first][this.second] != 9
fun Pair<Int, Int>.exists(map: List<List<Int>>) = this.first in map.indices && this.second in map[0].indices
fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 3,891 | aoc-2021 | MIT License |
src/main/kotlin/Day22.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
val input = readFileAsList("Day22")
println(Day22.part1(input))
println(Day22.part2(input))
}
object Day22 {
fun part1(input: List<String>): Int {
val (grid, instructions) = parseInput(input)
return followInstructions(instructions, grid) { p,d -> wrapFlat(grid, p, d) }
}
fun part2(input: List<String>): Int {
val (grid, instructions) = parseInput(input)
return followInstructions(instructions, grid) { p,d -> wrapCube(p, d) }
}
private fun parseInput(input: List<String>): Pair<Map<Vector2d, Char>, List<Instruction>> {
val grid = input.dropLast(2)
.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == ' ') null else Vector2d(
x,
y
) to c
}
}
.associate { it }
val instructions = Instruction.allFrom(input.last())
return Pair(grid, instructions)
}
private sealed class Instruction {
companion object {
val pattern = """\d+|[LR]""".toRegex()
fun allFrom(line: String): List<Instruction> {
return pattern.findAll(line).map {
when (it.value) {
"L" -> Left
"R" -> Right
else -> Move(it.value.toInt())
}
}.toList()
}
}
object Left : Instruction()
object Right : Instruction()
data class Move(val steps: Int) : Instruction()
}
private fun followInstructions(
instructions: List<Instruction>,
grid: Map<Vector2d, Char>,
wrap: (Vector2d, Dir) -> Pair<Vector2d, Dir>
): Int {
var position = Vector2d(grid.keys.filter { it.y == 0 }.minOf { it.x }, 0)
var dir = Dir.EAST
instructions.forEach { instruction ->
when (instruction) {
is Instruction.Left -> dir = dir.left()
is Instruction.Right -> dir = dir.right()
is Instruction.Move -> generateSequence(position to dir) { (p, d) ->
val next = p + d.offset
when {
next in grid && grid[next] == '#' -> p to d
next !in grid -> {
val (wrapped, wrappedDir) = wrap(p, d)
if (grid[wrapped] == '.') wrapped to wrappedDir else p to d
}
else -> next to d
}
}.take(instruction.steps + 1).last().let { (p, d) -> position = p; dir = d }
}
}
return 1000 * (position.y + 1) + 4 * (position.x + 1) + dir.score
}
private enum class Dir(
val left: () -> Dir,
val right: () -> Dir,
val offset: Vector2d,
val score: Int
) {
NORTH(left = { WEST }, right = { EAST }, offset = Vector2d(0, -1), score = 3),
EAST(left = { NORTH }, right = { SOUTH }, offset = Vector2d(1, 0), score = 0),
SOUTH(left = { EAST }, right = { WEST }, offset = Vector2d(0, 1), score = 1),
WEST(left = { SOUTH }, right = { NORTH }, offset = Vector2d(-1, 0), score = 2)
}
private fun wrapFlat(grid: Map<Vector2d, Char>, position: Vector2d, dir: Dir): Pair<Vector2d, Dir> {
val rotatedDir = dir.right().right()
return generateSequence(position) { it + rotatedDir.offset }.takeWhile { it in grid }.last() to dir
}
private fun wrapCube(position: Vector2d, dir: Dir): Pair<Vector2d, Dir> {
return when (Triple(dir, position.x / 50, position.y / 50)) {
Triple(Dir.NORTH, 1, 0) -> Vector2d(0, 100 + position.x) to Dir.EAST // 1 -> N
Triple(Dir.WEST, 1, 0) -> Vector2d(0, 149 - position.y) to Dir.EAST // 1 -> W
Triple(Dir.NORTH, 2, 0) -> Vector2d(position.x - 100, 199) to Dir.NORTH // 2 -> N
Triple(Dir.EAST, 2, 0) -> Vector2d(99, 149 - position.y) to Dir.WEST // 2 -> E
Triple(Dir.SOUTH, 2, 0) -> Vector2d(99, -50 + position.x) to Dir.WEST // 2 -> S
Triple(Dir.EAST, 1, 1) -> Vector2d(50 + position.y, 49) to Dir.NORTH // 3 -> E
Triple(Dir.WEST, 1, 1) -> Vector2d(position.y - 50, 100) to Dir.SOUTH // 3 -> W
Triple(Dir.NORTH, 0, 2) -> Vector2d(50, position.x + 50) to Dir.EAST // 4 -> N
Triple(Dir.WEST, 0, 2) -> Vector2d(50, 149 - position.y) to Dir.EAST // 4 -> W
Triple(Dir.EAST, 1, 2) -> Vector2d(149, 149 - position.y) to Dir.WEST // 5 -> E
Triple(Dir.SOUTH, 1, 2) -> Vector2d(49, 100 + position.x) to Dir.WEST // 5 -> S
Triple(Dir.EAST, 0, 3) -> Vector2d(position.y - 100, 149) to Dir.NORTH // 6 -> E
Triple(Dir.SOUTH, 0, 3) -> Vector2d(position.x + 100, 0) to Dir.SOUTH // 6 -> S
Triple(Dir.WEST, 0, 3) -> Vector2d(position.y - 100, 0) to Dir.SOUTH // 6 -> W
else -> error("Invalid state")
}
}
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 5,090 | advent-of-code-2022 | Apache License 2.0 |
lib/src/main/kotlin/aoc/day12/Day12.kt | Denaun | 636,769,784 | false | null | package aoc.day12
const val START: Char = 'S'
const val END: Char = 'E'
typealias HeightMap = List<List<Char>>
fun part1(input: String): Int = shortestPath(parse(input))!!
fun part2(input: String): Int = mostScenicPath(parse(input))!!
fun shortestPath(heightMap: HeightMap): Int? = bfs(
findFirst(heightMap, START),
isEnd = { heightMap[it] == END },
neighbors = { it.uphillNeighbors(heightMap) },
)
fun mostScenicPath(heightMap: HeightMap): Int? = bfs(
findFirst(heightMap, END),
isEnd = { heightMap[it] == 'a' },
neighbors = { it.downhillNeighbors(heightMap) },
)
fun bfs(
start: Coordinate,
isEnd: (Coordinate) -> Boolean,
neighbors: (Coordinate) -> List<Coordinate>,
): Int? {
val toVisit = mutableListOf(start)
val visited = mutableSetOf<Coordinate>()
var steps = 0
while (toVisit.isNotEmpty()) {
repeat(toVisit.size) {
val current = toVisit.removeFirst()
if (isEnd(current)) {
return steps
}
if (!visited.contains(current)) {
visited.add(current)
toVisit.addAll(neighbors(current))
}
}
steps += 1
}
return null
}
data class Coordinate(val row: Int, val column: Int) {
private fun neighbors(): List<Coordinate> = listOf(
Coordinate(row - 1, column),
Coordinate(row + 1, column),
Coordinate(row, column - 1),
Coordinate(row, column + 1),
)
private fun visitableNeighbors(heightMap: HeightMap): List<Coordinate> = neighbors()
.filter {
0 <= it.row && it.row < heightMap.size &&
0 <= it.column && it.column < heightMap[it.row].size
}
fun uphillNeighbors(heightMap: HeightMap): List<Coordinate> =
visitableNeighbors(heightMap)
.filter { height(heightMap[it]) - height(heightMap[this]) <= 1 }
fun downhillNeighbors(heightMap: HeightMap): List<Coordinate> =
visitableNeighbors(heightMap)
.filter { height(heightMap[this]) - height(heightMap[it]) <= 1 }
}
fun findFirst(heightMap: HeightMap, cell: Char): Coordinate {
val row = heightMap.indexOfFirst { it.contains(cell) }
val column = heightMap[row].indexOf(cell)
return Coordinate(row, column)
}
fun height(c: Char): Int = when (c) {
START -> height('a')
END -> height('z')
else -> c.code
}
operator fun HeightMap.get(c: Coordinate): Char = this[c.row][c.column] | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 2,482 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2019/SpaceStoichiometry.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.nonEmptyLines
fun spaceStoichiometry1(input: String): Long {
val rules = input.nonEmptyLines().map { Rule.parse(it) }
return requirements(rules, 1)
}
private fun requirements(rules: List<Rule>, fuel: Long): Long {
val stock = Stock()
stock.take("FUEL", fuel)
while (true) {
val material = stock.findMaterialNeedingReplenishing() ?: break
val count = stock[material]
check(count < 0)
val rule = rules.findRule(material)
val batches = rule.batchesNeeded(-count)
for (req in rule.requirements)
stock.take(req.material, req.units * batches)
stock.add(rule.target, rule.produces * batches)
}
return stock.ore
}
fun spaceStoichiometry2(input: String): Long {
val rules = input.nonEmptyLines().map { Rule.parse(it) }
val trillion = 1000000000000L
var low = 0L
var high = 1000000000L
var mid = 0L
while (low <= high) {
mid = (low + high) / 2
val result = requirements(rules, mid)
when {
result < trillion -> low = mid + 1
result > trillion -> high = mid - 1
else -> return mid
}
}
return if (requirements(rules, mid) > trillion) mid - 1 else mid
}
private class Stock {
val stock = mutableMapOf<String, Long>()
var ore = 0L
operator fun get(material: String): Long =
stock[material] ?: 0
fun findMaterialNeedingReplenishing(): String? =
stock.entries.find { it.value < 0 }?.key
fun add(material: String, units: Long) {
stock[material] = this[material] + units
}
fun take(material: String, units: Long) {
if (material == "ORE") {
ore += units
} else {
stock[material] = this[material] - units
}
}
}
private fun List<Rule>.findRule(target: String): Rule =
find { it.target == target } ?: error("no rule for $target")
private class MaterialCount(val units: Long, val material: String) {
override fun toString() = "$units $material"
companion object {
private val regex = Regex("""(\d+) (\w+)""")
fun parse(input: String): MaterialCount {
val (_, count, material) = regex.matchEntire(input)?.groupValues ?: error("invalid input '$input'")
return MaterialCount(count.toLong(), material)
}
}
}
private class Rule(val requirements: List<MaterialCount>, val target: String, val produces: Long) {
override fun toString() = "${requirements.joinToString()} => $produces $target"
fun batchesNeeded(count: Long) = 1 + ((count - 1) / produces)
companion object {
private val regex = Regex("""(.+) => (\d+) (.+)""")
fun parse(input: String): Rule {
val (_, requirements, produces, material) = regex.matchEntire(input)?.groupValues
?: error("invalid input '$input'")
return Rule(
requirements = requirements.split(Regex(", ")).map { MaterialCount.parse(it) },
target = material,
produces = produces.toLong()
)
}
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 3,190 | advent-of-code | MIT License |
2022/src/main/kotlin/de/skyrising/aoc2022/day21/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day21
import de.skyrising.aoc.*
private interface MonkeyMath {
fun compute(monkeys: Map<String, MonkeyMath>): LongFraction
fun toPolynomial(monkeys: Map<String, MonkeyMath>): LongPolynomial
}
private data class MonkeyConst(val value: Long) : MonkeyMath {
override fun compute(monkeys: Map<String, MonkeyMath>) = LongFraction(value)
override fun toPolynomial(monkeys: Map<String, MonkeyMath>) = LongPolynomial(arrayOf(LongFraction(value)))
}
private data class MonkeyOp(val lhs: String, val rhs: String, val op: Char) : MonkeyMath {
override fun compute(monkeys: Map<String, MonkeyMath>): LongFraction {
val a = monkeys[lhs]!!.compute(monkeys)
val b = monkeys[rhs]!!.compute(monkeys)
return when (op) {
'+' -> a + b
'-' -> a - b
'*' -> a * b
'/' -> a / b
else -> error("Unknown op $op")
}
}
override fun toPolynomial(monkeys: Map<String, MonkeyMath>): LongPolynomial {
val a = if (lhs == "humn") LongPolynomial.X else monkeys[lhs]!!.toPolynomial(monkeys)
val b = if (rhs == "humn") LongPolynomial.X else monkeys[rhs]!!.toPolynomial(monkeys)
val c = when (op) {
'+' -> a + b
'-' -> a - b
'=' -> b - a
'*' -> a * b
'/' -> a / b.coefficients[0]
else -> error("Unknown op $op")
}
return c
}
}
private fun parseInput(input: PuzzleInput): MutableMap<String, MonkeyMath> {
val monkeys = linkedMapOf<String, MonkeyMath>()
for (line in input.lines) {
val name = line.substring(0, 4)
val parts = line.substring(6).split(' ')
if (parts.size == 1) {
monkeys[name] = MonkeyConst(parts[0].toLong())
} else {
monkeys[name] = MonkeyOp(parts[0], parts[2], parts[1][0])
}
}
return monkeys
}
val test = TestInput("""
root: pppw + sjmn
dbpl: 5
cczh: sllz + lgvd
zczc: 2
ptdq: humn - dvpt
dvpt: 3
lfqf: 4
humn: 5
ljgn: 2
sjmn: drzm * dbpl
sllz: 4
pppw: cczh / lfqf
lgvd: ljgn * ptdq
drzm: hmdt - zczc
hmdt: 32
""")
@PuzzleName("Monkey Math")
fun PuzzleInput.part1(): Any {
val monkeys = parseInput(this)
return monkeys["root"]!!.compute(monkeys)
}
fun PuzzleInput.part2(): Any? {
val monkeys = parseInput(this)
val root = monkeys["root"] as MonkeyOp
return MonkeyOp(root.lhs, root.rhs, '=').toPolynomial(monkeys).rootNear(LongFraction(0))
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,553 | aoc | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day15/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day15
import de.skyrising.aoc.*
val test = TestInput("""
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
""")
@PuzzleName("Chiton")
fun PuzzleInput.part1(): Any? {
val input = lines
val g = Graph.build<Pair<Int, Int>, Int> {
for (y in input.indices) {
val line = input[y]
for (x in line.indices) {
val value = line[x].digitToInt()
if (y > 0) edge(Pair(x, y - 1), Pair(x, y), value)
if (x > 0) edge(Pair(x - 1, y), Pair(x, y), value)
}
}
}
val path = g.dijkstra(Pair(0, 0), Pair(input.lastIndex, input.last().lastIndex))
return path?.sumOf { e -> e.weight }
}
fun PuzzleInput.part2(): Any {
val input = lines
val width = input.last().length
val height = input.size
val map = Array(height * 5) { IntArray(width * 5) }
for (y in input.indices) {
val line = input[y]
for (x in line.indices) {
val value = line[x].digitToInt()
for (i in 0..4) {
for (j in 0..4) {
val y1 = i * height + y
val x1 = j * width + x
val offset = i + j
val v1 = 1 + ((value - 1) + offset) % 9
map[y1][x1] = v1
}
}
}
}
val dist = Array(height * 5) { IntArray(width * 5) }
val unvisited = ArrayDeque<Pair<Int, Int>>()
unvisited.add(Pair(0, 1))
unvisited.add(Pair(1, 0))
while (unvisited.isNotEmpty()) {
val (x, y) = unvisited.removeFirst()
var top = if (y > 0) dist[y - 1][x] else 0
var left = if (x > 0) dist[y][x - 1] else 0
var bottom = if (y < dist.size - 1) dist[y + 1][x] else 0
var right = if (x < dist.size - 1) dist[y][x + 1] else 0
if (top == 0 && (y != 0 || x != 1)) top = Int.MAX_VALUE
if (left == 0 && (x != 0 || y != 1)) left = Int.MAX_VALUE
if (bottom == 0) bottom = Int.MAX_VALUE
if (right == 0) right = Int.MAX_VALUE
val newValue = minOf(minOf(top, bottom), minOf(left, right)) + map[y][x]
if (dist[y][x] == 0 || newValue < dist[y][x]) {
dist[y][x] = newValue
if (y > 0) unvisited.add(Pair(x, y - 1))
if (x > 0) unvisited.add(Pair(x - 1, y))
if (y < dist.size - 1) unvisited.add(Pair(x, y + 1))
if (x < dist.size - 1) unvisited.add(Pair(x + 1, y))
}
}
return dist.last().last()
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,621 | aoc | MIT License |
src/main/kotlin/sschr15/aocsolutions/Day7.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
enum class HandResult(val next: HandResult? = null) {
FIVE_OF_A_KIND,
FOUR_OF_A_KIND(FIVE_OF_A_KIND),
FULL_HOUSE(FOUR_OF_A_KIND),
THREE_OF_A_KIND(FOUR_OF_A_KIND),
TWO_PAIRS(FULL_HOUSE),
ONE_PAIR(THREE_OF_A_KIND),
HIGH_CARD(ONE_PAIR)
}
fun String.handResult(part2: Boolean): HandResult {
// no suits, just values
val values = this.map { it.toString() }.sorted()
val valueCounts = values.groupingBy { it }.eachCount()
val valueCountCounts = valueCounts
.filterKeys { !part2 || it != "J" }.values // jacks are "jokers" in p2 and don't count on their own
.groupingBy { it }.eachCount()
var result = when {
valueCounts["J"] == 5 -> return HandResult.FIVE_OF_A_KIND // (p2 needs this exception)
valueCountCounts.containsKey(5) -> HandResult.FIVE_OF_A_KIND
valueCountCounts.containsKey(4) -> HandResult.FOUR_OF_A_KIND
valueCountCounts.containsKey(3) && valueCountCounts.containsKey(2) -> HandResult.FULL_HOUSE
valueCountCounts.containsKey(3) -> HandResult.THREE_OF_A_KIND
valueCountCounts.containsKey(2) && valueCountCounts.getValue(2) == 2 -> HandResult.TWO_PAIRS
valueCountCounts.containsKey(2) -> HandResult.ONE_PAIR
else -> HandResult.HIGH_CARD
}
if (part2) {
// Each "J" (joker) counts as whatever makes a better hand
repeat(valueCounts["J"] ?: 0) {
result = result.next ?: error("what")
}
}
return result
}
data class Hand(val cards: String, val bid: Int, val result: HandResult) : Comparable<Hand> {
private val cardNums = cards.map { completeOrder.indexOf(it) }
fun toPart2(): Hand {
if (cards == "JJJJJ") return Hand("LLLLL", bid, result) // an all-jacks hand becomes the best hand (aside from sorting)
if ('J' !in cards) return this // no jokers, no change
return Hand(cards.replace('J', 'L'), bid, cards.handResult(true))
}
override fun compareTo(other: Hand): Int {
if (result != other.result) return other.result.compareTo(result)
repeat(5) {
val thisVal = cardNums[it]
val otherVal = other.cardNums[it]
if (thisVal != otherVal) return thisVal.compareTo(otherVal)
}
return 0 // equal
}
companion object {
private val completeOrder = listOf('L') + (2..9).map { it.digitToChar() } + listOf('T', 'J', 'Q', 'K', 'A')
fun fromString(input: String): Hand {
val (cards, bid) = input.split(" ")
return Hand(cards, bid.toInt(), cards.handResult(false))
}
}
}
/**
* AOC 2023 [Day 7](https://adventofcode.com/2023/day/7)
* Challenge: Playing Camel Cards (it's like poker but meant to be
* "easier to play while riding a camel")
*/
object Day7 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 7) {
// test()
val hands: List<Hand>
part1 {
hands = inputLines.map(Hand::fromString)
hands.sorted()
.mapIndexed { index, hand -> hand.bid.toLong() * (index + 1) }.sum()
}
part2 {
hands.map(Hand::toPart2)
.sorted()
.mapIndexed { index, hand -> hand.bid.toLong() * (index + 1) }.sum()
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 3,448 | advent-of-code | MIT License |
src/main/kotlin/com/tonnoz/adventofcode23/day11/Day11Part2.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day11
import com.tonnoz.adventofcode23.utils.readInput
import com.tonnoz.adventofcode23.utils.toCharMatrix
import kotlin.system.measureTimeMillis
const val EXPANDING_FACTOR = 1_000_000L
object Day11Part2 {
@JvmStatic
fun main(args: Array<String>) {
val input = "input11.txt".readInput().toCharMatrix()
val time = measureTimeMillis {
val (universe, galaxyPairs) = createUniverseAndGalaxyPairs(input)
val distances = galaxyPairs.map { it.calculateDistanceBetween(universe) }
println("Part2: ${distances.sum()}")
}
println("P2 time: $time ms")
}
data class Galaxy(val row: Int, val column: Int, val value: Char)
data class GalaxyPair(val a: Galaxy, val b: Galaxy)
private fun GalaxyPair.calculateDistanceBetween(universe: List<List<Galaxy>>): Long {
val (smallICol, bigICol) = listOf(this.a.column, this.b.column).sorted()
val (smallIRow, bigIRow) = listOf(this.a.row, this.b.row).sorted()
val expandedSpaceRow = countNrExpandedSpace(smallIRow, bigIRow, universe, ::isExpandedSpacesRow)
val expandedSpaceColumn = countNrExpandedSpace(smallICol, bigICol, universe, ::isExpandedSpacesColumn)
val rowDistance = bigIRow.toLong() - smallIRow.toLong() + expandedSpaceRow
val colDistance = bigICol.toLong() - smallICol.toLong() + expandedSpaceColumn
return colDistance + rowDistance
}
private fun countNrExpandedSpace(smallI: Int, bigI: Int, universe: List<List<Galaxy>>, isExpandedFunction: (List<List<Galaxy>>, Int) -> Long) =
(smallI..<bigI).sumOf { isExpandedFunction(universe, it) }
private fun Boolean.toLong() = if(this) EXPANDING_FACTOR-1 else 0L
private fun isExpandedSpacesRow(universe:List<List<Galaxy>>, row: Int) = universe[row].all { it.value == '.' }.toLong()
private fun isExpandedSpacesColumn(universe: List<List<Galaxy>>, col: Int) = universe.all { it[col].value == '.' }.toLong()
private fun List<List<Galaxy>>.findGalaxy(aChar: Char) : Galaxy { // naive linear search
this.forEach { it.forEach { galaxy -> if(galaxy.value == aChar) return galaxy } }
throw IllegalArgumentException("Not possible to find galaxy with char $aChar")
}
private fun createUniverseAndGalaxyPairs(input: ArrayList<CharArray>): Pair<List<List<Galaxy>>, Set<GalaxyPair>> {
var counter = FIRST_CHAR
val universe = input.mapIndexed { rowI, row -> row.mapIndexed { columnI, aChar ->
if (aChar == '#') Galaxy(rowI, columnI, counter++.toChar()) else Galaxy(rowI, columnI, aChar)
}}
return Pair(universe, createGalaxyPairs(counter, universe))
}
private fun createGalaxyPairs(counter: Int, universe: List<List<Galaxy>>): Set<GalaxyPair> {
val galaxyPairs = mutableSetOf<GalaxyPair>()
for (i in FIRST_CHAR..<counter) { for (j in i..<counter) {
if (i != j) galaxyPairs.add(GalaxyPair(universe.findGalaxy(i.toChar()), universe.findGalaxy(j.toChar())))
}}
return galaxyPairs.toSet()
}
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 2,955 | adventofcode23 | MIT License |
app/src/main/kotlin/day14/Day14.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day14
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 14
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay14Part1, ::solveDay14Part2)
}
fun solveDay14Part1(input: List<String>): Long {
return execute(input, 10)
}
fun solveDay14Part2(input: List<String>): Long {
return execute(input, 40)
}
private fun execute(input: List<String>, steps: Int): Long {
val dictionary = input.subList(2, input.size).map { it.split(" -> ") }.associate { it[0] to it[1] }
var pairCounts = input.first().windowed(2).groupBy { it }.map { it.key to it.value.size.toLong() }.toMap()
repeat(steps) {
pairCounts = calculateNextStep(pairCounts, dictionary)
}
val elementCounts = getElementCounts(pairCounts, input)
val mostCommon = elementCounts.maxOfOrNull { it.value } ?: 0L
val leastCommon = elementCounts.minOfOrNull { it.value } ?: 0L
return mostCommon - leastCommon
}
private fun calculateNextStep(
pairCounts: Map<String, Long>,
dictionary: Map<String, String>
): Map<String, Long> {
val nextPairCounts = pairCounts.toMutableMap()
pairCounts.forEach { (pair, count) ->
val insertElement = dictionary[pair]
val newPairLeft = pair.substring(0, 1) + insertElement
val newPairRight = insertElement + pair.substring(1, 2)
nextPairCounts.decreaseBy(pair, count)
nextPairCounts.increaseBy(newPairLeft, count)
nextPairCounts.increaseBy(newPairRight, count)
}
return nextPairCounts.toMap()
}
private fun getElementCounts(
pairCounts: Map<String, Long>,
input: List<String>
): MutableMap<Char, Long> {
val elementCounts = mutableMapOf<Char, Long>()
pairCounts.forEach { (pair, count) ->
elementCounts[pair[0]] = elementCounts.getOrDefault(pair[0], 0L) + count
}
elementCounts[input.first().last()] = elementCounts[input.first().last()]!! + 1
return elementCounts
}
private fun executeSlow(input: List<String>, steps: Int): Long {
val dictionary = input.subList(2, input.size).map { it.split(" -> ") }.associate { it[0] to it[1] }
var template = input.first()
val nextTemplate = template.toCharArray().toMutableList()
repeat(steps) {
var insertIndex = 1
template.windowed(2) { pair ->
val insert = dictionary.getOrDefault(pair, "")
nextTemplate.addAll(insertIndex, insert.toCharArray().toList())
insertIndex += insert.length + 1
}
template = nextTemplate.toCharArray().concatToString()
}
val mostCommon = nextTemplate.groupBy { it }.maxOfOrNull { it.value.size.toLong() } ?: 0L
val leastCommon = nextTemplate.groupBy { it }.minOfOrNull { it.value.size.toLong() } ?: 0L
return mostCommon - leastCommon
}
fun MutableMap<String, Long>.increaseBy(key: String, add: Long) {
this[key] = getOrDefault(key, 0L) + add
}
fun MutableMap<String, Long>.decreaseBy(key: String, sub: Long) {
this[key] = getOrDefault(key, 0L) - sub
}
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 3,108 | advent-of-code-kt | Apache License 2.0 |
src/day18/Day18.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day18
import Runner
fun main() {
Day18Runner().solve()
}
class Day18Runner : Runner<Int>(
day = 18,
expectedPartOneTestAnswer = 64,
expectedPartTwoTestAnswer = 58
) {
override fun partOne(input: List<String>, test: Boolean): Int {
val cubes = cubes(input)
return cubes.map { cube -> cube.adjacentCoords() }
.sumOf { adjacent -> adjacent.count { adjacentCoord -> !cubes.contains(adjacentCoord) } }
}
override fun partTwo(input: List<String>, test: Boolean): Int {
val cubes = cubes(input)
val external = cubes.calculateExternal()
return cubes.map { cube -> cube.adjacentCoords() }
.sumOf { adjacent -> adjacent.count { adjacentCoord -> !cubes.contains(adjacentCoord) && external.contains(adjacentCoord) } }
}
private fun List<Coord>.calculateExternal() : Set<Coord> {
val xOuter = (minOf { coord -> coord.x } - 1 .. maxOf { coord -> coord.x } + 1)
val yOuter = (minOf { coord -> coord.y } - 1 .. maxOf { coord -> coord.y } + 1)
val zOuter = (minOf { coord -> coord.z } - 1 .. maxOf { coord -> coord.z } + 1)
fun recurse(outers: Set<Coord>) : Set<Coord> {
val adjacentOuters = outers.flatMap { outer -> outer.adjacentOuter(
cubes = this,
xOuter = xOuter,
yOuter = yOuter,
zOuter = zOuter
) }.toSet()
return outers
.takeIf { it.size == adjacentOuters.size }
?: recurse(adjacentOuters)
}
return recurse(initial(
xOuter = xOuter,
yOuter = yOuter,
zOuter = zOuter
).toSet())
}
private fun Coord.adjacentOuter(
cubes: List<Coord>,
xOuter : IntRange,
yOuter : IntRange,
zOuter : IntRange,
) : Set<Coord> {
return (adjacentCoords() + this).filter { coord ->
coord.x in xOuter && coord.y in yOuter && coord.z in zOuter && !cubes.contains(coord)
}.toSet()
}
private fun initial(
xOuter : IntRange,
yOuter : IntRange,
zOuter : IntRange,
): List<Coord> {
return listOf(
xOuter.flatMap { x -> yOuter.map { y -> Coord(x, y, zOuter.first) } },
xOuter.flatMap { x -> yOuter.map { y -> Coord(x, y, zOuter.last) } },
xOuter.flatMap { x -> zOuter.map { z -> Coord(x, yOuter.first, z) } },
xOuter.flatMap { x -> zOuter.map { z -> Coord(x, yOuter.last, z) } },
yOuter.flatMap { y -> zOuter.map { z -> Coord(zOuter.first, y, z) } },
yOuter.flatMap { y -> zOuter.map { z -> Coord(zOuter.last, y, z) } },
).flatten()
}
private fun Coord.adjacentCoords() : List<Coord> {
return listOf(
copy(x = x + 1),
copy(x = x - 1),
copy(y = y + 1),
copy(y = y - 1),
copy(z = z + 1),
copy(z = z - 1),
)
}
private fun cubes(input: List<String>) : List<Coord> {
return input.map { line ->
val split = line.split(",").map { s -> s.toInt() }
Coord(
x = split[0],
y = split[1],
z = split[2]
)
}
}
}
data class Coord(
val x: Int,
val y: Int,
val z: Int
) | 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 3,372 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day3.kt | cbrentharris | 712,962,396 | false | {"Kotlin": 171464} | import kotlin.String
import kotlin.collections.List
object Day3 {
data class NumberPosition(
val number: Int,
val start: Int,
val end: Int,
val row: Int
)
data class Symbol(val symbol: Char, val coordinate: Coordinate)
data class Coordinate(val x: Int, val y: Int)
private val reservedSymbol = ".".first()
fun part1(input: List<String>): String {
val numbers = parseNumbers(input)
val specialCharacters = parseSpecialCharacters(input).associateBy { it.coordinate }
val partNumbers = numbers.filter {
val (_, start, end, row) = it
val up = row - 1
val down = row + 1
val left = start - 1
val right = end + 1
val coordinateCandidates = (left..right).flatMap { x ->
listOf(
Coordinate(x, up),
Coordinate(x, down)
)
} + listOf(Coordinate(left, row), Coordinate(right, row))
coordinateCandidates.any { specialCharacters.containsKey(it) }
}
return partNumbers.sumOf { it.number }.toString()
}
private fun parseNumbers(input: List<String>): List<NumberPosition> {
return input.zip(input.indices).flatMap { (line, rowIndex) ->
val charArray = line.toCharArray()
val withIndexes = charArray.zip(charArray.indices)
val deque = ArrayDeque(withIndexes)
var buffer = ""
var start = 0
var end = 0
val numbers = mutableListOf<NumberPosition>()
while (deque.isNotEmpty()) {
val (char, index) = deque.removeFirst()
if (char.isDigit()) {
end = index
buffer += char
} else {
if (buffer.isNotEmpty()) {
numbers.add(NumberPosition(buffer.toInt(), start, end, rowIndex))
}
buffer = ""
start = index + 1
end = index + 1
}
}
if (buffer.isNotEmpty()) {
numbers.add(NumberPosition(buffer.toInt(), start, end, rowIndex))
}
numbers
}
}
private fun parseSpecialCharacters(input: List<String>): List<Symbol> {
val validSymbols = input.map { it.toCharArray() }
.map { it.zip(it.indices) }
.map { it.filter { !it.first.isDigit() }.filter { it.first != reservedSymbol } }
return validSymbols.zip(validSymbols.indices)
.flatMap { (row, rowIndex) -> row.map { Symbol(it.first, Coordinate(it.second, rowIndex)) } }
}
fun part2(input: List<String>): String {
val numbers = parseNumbers(input)
val specialCharacters = parseSpecialCharacters(input)
val gears = specialCharacters.filter { it.symbol == '*' }.associateBy { it.coordinate }
return gears.map { adjacent(it.key, numbers) }
.filter { it.size == 2 }
.map { it.map { it.number }.reduce { a, b -> a * b } }
.sum().toString()
}
private fun adjacent(it: Coordinate, numbers: List<NumberPosition>): List<NumberPosition> {
val up = Coordinate(it.x, it.y - 1)
val down = Coordinate(it.x, it.y + 1)
val left = Coordinate(it.x - 1, it.y)
val right = Coordinate(it.x + 1, it.y)
val upLeft = Coordinate(it.x - 1, it.y - 1)
val upRight = Coordinate(it.x + 1, it.y - 1)
val downLeft = Coordinate(it.x - 1, it.y + 1)
val downRight = Coordinate(it.x + 1, it.y + 1)
val candidates = listOf(up, down, left, right, upLeft, upRight, downLeft, downRight)
return numbers.filter { num -> candidates.any { it.x <= num.end && it.x >= num.start && it.y == num.row } }
}
}
| 0 | Kotlin | 0 | 1 | f689f8bbbf1a63fecf66e5e03b382becac5d0025 | 3,881 | kotlin-kringle | Apache License 2.0 |
src/twentytwo/Day10.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day10_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 13140)
val part2 = part2(testInput)
println(part2)
check(part2 ==
"""
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent())
println("---")
val input = readInputLines("Day10_input")
println(part1(input))
println(part2(input))
}
private sealed interface Operation {
object NOOP: Operation
data class ADDX(val x: Int): Operation
}
private fun List<String>.toOperations(): List<Operation> {
return this.map { it.toOperation() }
}
private fun String.toOperation(): Operation {
return when (this) {
"noop" -> Operation.NOOP
else -> Operation.ADDX(this.substringAfter("addx ").toInt())
}
}
private fun part1(input: List<String>): Int {
val cyclesToCount = listOf(20, 60, 100, 140, 180, 220)
var cycle = 0
var x = 1
val countedX = mutableListOf<Int>()
input.toOperations().forEach { operation ->
cycle++
if (cycle in cyclesToCount) countedX.add(x)
if (operation is Operation.ADDX) {
cycle++
if (cycle in cyclesToCount) countedX.add(x)
x += operation.x
}
}
val scores = countedX.mapIndexed { index, xAtSpot -> xAtSpot * cyclesToCount[index] }
return scores.sum()
}
private fun part2(input: List<String>): String {
var cycle = -1 // because crt starts at 0
var x = 1
val output = mutableListOf<Boolean>()
input.toOperations().forEach { operation ->
cycle++
output.add(crtState(cycle, x))
if (operation is Operation.ADDX) {
cycle++
output.add(crtState(cycle, x))
x += operation.x
}
}
return output
.map { if (it) "#" else "." }
.reduce { a, b -> "$a$b" }
.chunked(40)
.reduce { a, b -> "$a\n$b"}
}
private fun crtState(cycle: Int, x: Int): Boolean {
val horizontalCrtPosition = cycle % 40
return horizontalCrtPosition == x ||
horizontalCrtPosition == x - 1 ||
horizontalCrtPosition == x + 1
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 2,496 | advent-of-code-solutions | Apache License 2.0 |
src/day02/Day02.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day02
import readInput
import readTestInput
private fun String.toShape(): Shape = when (this) {
"A", "X" -> Shape.Rock
"B", "Y" -> Shape.Paper
"C", "Z" -> Shape.Scissor
else -> error(""""$this" is NOT a legal shape!""")
}
private fun String.toResult(): DuelResult = when (this) {
"X" -> DuelResult.Lose
"Y" -> DuelResult.Draw
"Z" -> DuelResult.Won
else -> error(""""$this" is NOT a legal result!""")
}
private sealed interface Shape {
val score: Int
infix fun against(other: Shape): DuelResult
object Rock : Shape {
override val score: Int = 1
override fun against(other: Shape): DuelResult = when (other) {
Paper -> DuelResult.Lose
Rock -> DuelResult.Draw
Scissor -> DuelResult.Won
}
}
object Paper : Shape {
override val score: Int = 2
override fun against(other: Shape): DuelResult = when (other) {
Paper -> DuelResult.Draw
Rock -> DuelResult.Won
Scissor -> DuelResult.Lose
}
}
object Scissor : Shape {
override val score: Int = 3
override fun against(other: Shape): DuelResult = when (other) {
Paper -> DuelResult.Won
Rock -> DuelResult.Lose
Scissor -> DuelResult.Draw
}
}
}
private sealed interface DuelResult {
val score: Int
object Won : DuelResult {
override val score: Int = 6
}
object Lose : DuelResult {
override val score: Int = 0
}
object Draw : DuelResult {
override val score: Int = 3
}
}
private fun part1(input: List<String>): Int {
return input.sumOf { game ->
val (opponent, me) = game.split(" ")
val opponentShape = opponent.toShape()
val selectedShape = me.toShape()
selectedShape.score + (selectedShape against opponentShape).score
}
}
private fun part2(input: List<String>): Int {
return input.sumOf { game ->
val (opponent, me) = game.split(" ")
val opponentShape = opponent.toShape()
val desiredResult = me.toResult()
val selectedShape = Shape::class.sealedSubclasses
.mapNotNull { it.objectInstance }
.first { shape -> shape against opponentShape == desiredResult }
selectedShape.score + desiredResult.score
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day02")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 2,662 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/pl/mrugacz95/aoc/day19/day19.kt | mrugacz95 | 317,354,321 | false | null | package pl.mrugacz95.aoc.day19
import java.lang.RuntimeException
fun Iterable<String>.cartesianProduct(other: Iterable<String>): List<String> {
return this.flatMap { lhsElem -> other.map { rhsElem -> lhsElem + rhsElem } }
}
const val debug = true
fun println(str: String) {
if (debug)
print("$str\n")
}
fun evalRule(index: Int, rules: Map<Int, String>, result: MutableMap<Int, List<String>>): List<String> {
result[index]?.let {
return it
}
val rule = rules[index] ?: throw RuntimeException("Rule definition not found: $index")
val eval = if (rule.isTerminalRule()) { // "x"
listOf(rule[1].toString())
} else {
if ("|" in rule) { // X [X] | Y [Y]
val (firstAlt, secondAlt) = rule.split(" | ")
.map { it.split(" ").map { rId -> rId.toInt() } }
.map { it.map { rIdx -> evalRule(rIdx, rules, result) } }
firstAlt.reduce { acc, i -> acc.cartesianProduct(i) } + secondAlt.reduce { acc, i -> acc.cartesianProduct(i) }
} else { // X X [X]
val evaluated = rule.split(" | ", " ")
.map { it.toInt() }
.map { evalRule(it, rules, result) }
evaluated.reduce { acc, i -> acc.cartesianProduct(i) }
}
}
result[index] = eval
return eval
}
fun String.isTerminalRule() = length == 3 && get(0) == '"' && get(2) == '"'
fun part1(rules: Map<Int, String>, messages: List<String>): Int {
val evaluated = mutableMapOf<Int, List<String>>()
for (key in rules.keys) {
evalRule(key, rules, evaluated)
}
val zeroRule = evaluated[0] ?: throw RuntimeException("Zero rule not found")
return messages.filter { msg -> msg in zeroRule }.count()
}
sealed class Rule(open val id: Int) {
abstract val length: IntRange
abstract fun match(message: List<Int>, rules: Map<Int, Rule>): Boolean
override fun equals(other: Any?): Boolean {
if(other !is Rule) return false
return other.id != this.id
}
override fun hashCode(): Int {
return id
}
}
data class Term(override val id: Int, val term: String) : Rule(id) {
override val length = 1..1
override fun match(message: List<Int>, rules: Map<Int, Rule>) = throw RuntimeException("")
}
data class RuleList(override val id: Int, val prod: List<Int>) : Rule(id) {
override val length = prod.size..prod.size
override fun match(message: List<Int>, rules: Map<Int, Rule>) = prod == message.subList(0, prod.size)
}
data class Alternative(override val id: Int, val alts: List<List<Int>>) : Rule(id) {
override val length: IntRange by lazy {
val min = alts.map { it.size }.minByOrNull { it }!!
val max = alts.map { it.size }.maxByOrNull { it }!!
min..max
}
override fun match(message: List<Int>, rules: Map<Int, Rule>): Boolean {
for (pair in alts) {
if (message.take(pair.size) == pair) {
return true
}
}
return false
}
}
val rules = mutableMapOf<Int, Rule>()
fun parseRules(unparsedRules: Map<Int, String>){
for ((rId, rule) in unparsedRules.entries.withIndex()) {
rules[rule.key] = if (rule.value.isTerminalRule()) { // "x"
Term(rId, rule.value[1].toString())
} else {
if ("|" in rule.value) { // X [X] | Y [Y]
Alternative(rId, rule.value.split(" | ")
.map { it.split(" ").map { it.toInt() } })
} else { // X X [X]
RuleList(rId, rule.value.split(" ")
.map { it.toInt() })
}
}
}
}
fun first(ruleId: Int): Set<Char> {
return when (val rule = rules[ruleId]!!) {
is Term -> return setOf(rule.term.first())
is RuleList -> return first(rule.prod.first())
is Alternative -> rule.alts.map { first(it.first()) }.reduce { acc, i -> acc.union(i) }
}
}
val determined = mutableMapOf<Int,Boolean>()
fun isDetermined(ruleId:Int): Boolean {
determined[ruleId]?.let {
return it
}
determined[ruleId] = false
val result = when(val rule = rules[ruleId]!!){
is Term -> true
is RuleList -> rule.prod.all { isDetermined(it) }
is Alternative -> rule.alts.all { prod -> prod.all { isDetermined(it) } }
}
determined[ruleId] = result
return result
}
fun isTerminal(ruleId:Int): String?{
return when(val rule = rules[ruleId]!!){
is Term -> rule.term
is RuleList -> {
val terms = rule.prod.map { isTerminal(it) }
if(terms.any { it == null }){
return null
}
terms.joinToString("")
}
is Alternative -> null
}
}
fun ruleListMatch(productions: List<Int>, message: String): Sequence<String> = sequence {
val firstProd = productions.first()
val matches = matches(firstProd, message)
if(productions.size == 1){
yieldAll(matches)
return@sequence
}
for(prodMatch in matches) {
val currentMatch = ruleListMatch( productions.drop(1), message.removePrefix(prodMatch))
for(curr in currentMatch) {
if (message.startsWith(prodMatch + curr)) {
yield(prodMatch + curr)
}
}
}
}
fun matches(ruleId: Int, message: String): Sequence<String> = sequence {
if(message.isEmpty()){
return@sequence
}
if(message.first() !in first[ruleId]!!){ // first char check
return@sequence
}
when(val rule = rules[ruleId]){
is Term -> {
if (message.startsWith(rule.term)) { // check again
yield(rule.term)
}
return@sequence
}
is RuleList -> {
val prefixMatch = ruleListMatch(rule.prod, message)
yieldAll(prefixMatch)
return@sequence
}
is Alternative -> { // return longest match
for(alt in rule.alts){
ruleListMatch(alt, message).let { someMatches ->
for (match in someMatches) {
if (message.startsWith(match)) {
yield(match)
}
}
}
}
return@sequence
}
}
}
val first = mutableMapOf<Int, Set<Char>>()
fun part2OnceAgain(unparsedRules: Map<Int, String>, messages: List<String>): Int {
parseRules(unparsedRules)
for(ruleId in rules.keys){
isDetermined(ruleId)
}
println("${determined.entries.filter { it.value }.count()}/${rules.size} rules are determined")
println("Only ${determined.entries.filterNot { it.value }.joinToString (", "){ it.key.toString() }} are not determined")
for(ruleId in rules.keys){
val term = isTerminal(ruleId)
if(term != null){
rules[ruleId] = Term(ruleId,term)
}
}
for(ruleId in rules.keys){
first[ruleId] = first(ruleId)
}
var counter = 0
for(message in messages) {
val matches = matches(0, message)
for(match in matches) {
if (match == message) {
counter += 1
}
}
}
return counter
}
fun main() {
val input = {}::class.java.getResource("/day19.in")
.readText()
.split("\n\n")
val rules = input[0]
.split("\n")
.map { rule -> rule.split(": ") }
.associateBy({ it[0].toInt() }, { it[1] })
.toMutableMap()
val messages = input[1]
.split("\n")
println("Answer part 1: ${part1(rules, messages)}")
rules[8] = "42 | 42 8"
rules[11] = "42 31 | 42 11 31"
println("Answer part 2: ${part2OnceAgain(rules, messages)}")
} | 0 | Kotlin | 0 | 1 | a2f7674a8f81f16cd693854d9f564b52ce6aaaaf | 7,790 | advent-of-code-2020 | Do What The F*ck You Want To Public License |
src/Day13.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | import kotlin.math.sign
// https://adventofcode.com/2022/day/13
fun main() {
fun part1(input: List<String>): Int {
return input
.windowed(size = 2, step = 3)
.map { (first, second) ->
PacketListItem.fromString(first) to PacketListItem.fromString(second)
}
.mapIndexed { index, (first, second) ->
if (first <= second) index + 1 else 0
}
.sum()
}
fun part2(input: List<String>): Int {
val packets = input
.filter(String::isNotEmpty)
.map(PacketListItem::fromString)
val dividers = listOf(
PacketListItem.fromString("[[2]]"),
PacketListItem.fromString("[[6]]")
)
return (packets + dividers)
.asSequence()
.sorted()
.withIndex()
.filter { (_, packet) -> packet in dividers}
.map { it.index }
.fold(1) { acc, index -> acc * (index + 1) }
}
val input = readLines("Input13")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private sealed class PacketItem {
private fun asList() = when (this) {
is PacketSingleItem -> PacketListItem(listOf(this))
is PacketListItem -> this
}
operator fun compareTo(other: PacketItem): Int =
if (this is PacketSingleItem && other is PacketSingleItem) {
this.compareTo(other)
} else {
asList().compareTo(other.asList())
}
}
private class PacketSingleItem(val value: Int): PacketItem() {
override fun toString() = value.toString()
operator fun compareTo(other: PacketSingleItem) = (value - other.value).sign
}
private class PacketListItem(
val items: List<PacketItem>
): PacketItem(), Comparable<PacketListItem> {
override fun toString() = "[${items.joinToString(",")}]"
override operator fun compareTo(other: PacketListItem): Int {
(items zip other.items).forEach { (left, right) ->
val compareToResult = left.compareTo(right)
if (compareToResult != 0) {
return compareToResult
}
}
return (items.size - other.items.size).sign
}
companion object {
fun fromString(str: String) = fromCharDeque(ArrayDeque(str.toList()))
private fun fromCharDeque(charDeque: ArrayDeque<Char>): PacketListItem {
val items = mutableListOf<PacketItem>()
if (charDeque.removeFirstOrNull() != '[') error("List should start with '['")
while(charDeque.isNotEmpty()) {
when (charDeque.first()) {
'[' -> items.add(fromCharDeque(charDeque))
in '0'..'9' -> {
var number = charDeque.removeFirst().digitToInt()
while (charDeque.first().isDigit()) {
number = number * 10 + charDeque.removeFirst().digitToInt()
}
items.add(PacketSingleItem(number))
}
']' -> {
charDeque.removeFirst()
break
}
else -> charDeque.removeFirst()
}
}
return PacketListItem(items)
}
}
}
| 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 3,371 | 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.