Skip to content

Instantly share code, notes, and snippets.

@heinrisch
Created December 4, 2023 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heinrisch/d5dd4c34f92cc1bcbd56fe7813222026 to your computer and use it in GitHub Desktop.
Save heinrisch/d5dd4c34f92cc1bcbd56fe7813222026 to your computer and use it in GitHub Desktop.
Advent of Code 2023 Day 3
import java.awt.Point
import java.io.File
fun main() {
data class Digit(val p: Point, val value: Char)
// List of digits is a number (always in right order because of parsing order)
fun List<Digit>.value(): Long = this.map { it.value }.joinToString("").toLong()
val matrix = File("input/day3.txt").readLines()
val width = matrix[0].length
val height = matrix.size
// All points in the matrix
val allPoints = (0..<height).flatMap { y ->
(0..<width).map { x ->
Point(x, y)
}
}
// Get on character from the matrix, if out of bounds return '.'
fun check(x: Int, y: Int): Char {
return if (x < 0 || x >= width || y < 0 || y >= height) '.'
else matrix[y][x]
}
// All points surrounding one point
fun around(p: Point): List<Point> = (-1..1).map { x ->
(-1..1).map { y -> Point(p.x + x, p.y + y) }
}.flatten()
// ALl points surrounding one number
fun List<Digit>.around(): List<Point> = map { around(it.p) }.flatten()
fun Char.isSymbol(): Boolean = !(this == '.' || this.isDigit())
// Find all numbers and store
var cNumber = mutableListOf<Digit>()
val allNumbers = mutableListOf<List<Digit>>()
allPoints.forEach { p ->
if (matrix[p.y][p.x].isDigit()) {
cNumber.add(Digit(Point(p.x, p.y), matrix[p.y][p.x]))
} else {
allNumbers.add(cNumber.toList())
cNumber = mutableListOf()
}
}
var sum = 0L
allNumbers.forEach { nums ->
if (nums.around().any { check(it.x, it.y).isSymbol() }) {
sum += nums.value()
}
}
println(sum)
var bigSum = 0L
allPoints.forEach { p ->
if (matrix[p.y][p.x] == '*') {
val matches = allNumbers.filter { nums ->
nums.around().contains(p)
}
if (matches.size == 2) {
val (a, b) = matches
bigSum += a.value() * b.value()
}
}
}
println(bigSum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment