Skip to content

Commit

Permalink
Day 3: Gear Ratios
Browse files Browse the repository at this point in the history
  • Loading branch information
ephemient committed Dec 3, 2023
1 parent 89449ab commit 11480a0
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.github.ephemient.aoc2023.exe

import com.github.ephemient.aoc2023.Day3
import kotlinx.benchmark.Benchmark
import kotlinx.benchmark.Scope
import kotlinx.benchmark.Setup
import kotlinx.benchmark.State

@State(Scope.Benchmark)
class Day3Bench {
private lateinit var input: String

@Setup
fun setup() {
input = getDayInput(3)
}

@Benchmark
fun part1() = Day3(input).part1()

@Benchmark
fun part2() = Day3(input).part2()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.github.ephemient.aoc2023

class Day3(input: String) {
private val parts: Map<Pair<Int, Int>, List<Int>> = mutableMapOf<Pair<Int, Int>, MutableList<Int>>().apply {
val lines = input.trimEnd().lines()
for ((y, line) in lines.withIndex()) {
for (match in NUMBER.findAll(line)) {
val number = match.value.toInt()
for (y2 in (y - 1).coerceAtLeast(0)..(y + 1).coerceAtMost(lines.lastIndex)) {
val line2 = lines[y2]
val x0 = match.range.first - 1
val x1 = match.range.last + 1
for (x in x0.coerceAtLeast(0)..x1.coerceAtMost(line2.lastIndex)) {
if (line2[x].isSymbol()) {
getOrPut(x to y2) { mutableListOf() } += number
}
}
}
}
}
}

fun part1(): Int = parts.values.sumOf { it.sum() }

fun part2(): Int = parts.values.sumOf { if (it.size == 2) it[0] * it[1] else 0 }

companion object {
private val NUMBER = """\d+""".toRegex()

private fun Char.isSymbol(): Boolean = this != '.' && !isWhitespace() && !isDigit()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.github.ephemient.aoc2023
val days = listOf(
Day(1, ::Day1, Day1::part1, Day1::part2),
Day(2, ::Day2, Day2::part1, Day2::part2),
Day(3, ::Day3, Day3::part1, Day3::part2),
)

data class Day(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.github.ephemient.aoc2023

import kotlin.test.Test
import kotlin.test.assertEquals

class Day3Test {
@Test
fun part1() {
assertEquals(4361, Day3(example).part1())
}

@Test
fun part2() {
assertEquals(467835, Day3(example).part2())
}

companion object {
private val example =
"""
|467..114..
|...*......
|..35..633.
|......#...
|617*......
|.....+.58.
|..592.....
|......755.
|...$.*....
|.664.598..
|""".trimMargin()
}
}

0 comments on commit 11480a0

Please sign in to comment.