Post

AoC - "Trebuchet?!"

My solution to Advent of Code 2023 Day 1

See the challenge

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package adventOfCode.y2023.d01

import adventOfCode.lib.Solver

class Solution : Solver {
    override fun part1(input: String): Int {
        return solve(input, Regex("\\d"))
    }

    override fun part2(input: String): Int {
        return solve(input, Regex("(?=(\\d|one|two|three|four|five|six|seven|eight|nine))"))
    }

    private fun solve(input: String, regex: Regex): Int {
        return input.lines().filter { it.isNotBlank() }.sumOf { line ->
            val matches = regex.findAll(line).toList()

            // Takes into account whether the regex is wrapped in a group or not
            val first = matches.first().groupValues.getOrElse(1) { matches.first().groupValues[0] }
            val last = matches.last().groupValues.getOrElse(1) { matches.last().groupValues[0] }
            convertMatch(first) * 10 + convertMatch(last)
        }
    }

    private fun convertMatch(match: String): Int {
        return when (match) {
            "one" -> 1
            "two" -> 2
            "three" -> 3
            "four" -> 4
            "five" -> 5
            "six" -> 6
            "seven" -> 7
            "eight" -> 8
            "nine" -> 9
            else -> match.toInt()
        }
    }
}

This post is licensed under CC BY 4.0 by the author.