Advent of Code - Day 2: Cube Conundrum


2023-12-02-generated.png

You’re launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island floating in the sky. You gently land in a fluffy pile of leaves. It’s quite cold, but you don’t see much snow. An Elf runs over to greet you.

-- Day 2 - Advent of Code 2023

Solution in Java

Full source can be found: in GitHub

Part 1

The first step for today is the parsing of the input string into Game instances. To do this I created a record representing a single game and a parsing method createGame that processes a single line of the input.

 1record Game(int number, int green, int red, int blue) {}
 2
 3private Game createGame(String line) {  
 4    String[] parts = line.split(":");  
 5  
 6    var red = 0;  
 7    var green = 0;  
 8    var blue = 0;  
 9    var number = Integer.parseInt(parts[0].substring(5));  
10    for (var segment : parts[1].split(";")) {  
11        for (var color : segment.split(",")) {  
12            var colorParts = color.trim().split(" ");  
13            var count = Integer.parseInt(colorParts[0]);  
14            var colorName = colorParts[1];  
15            switch (colorName) {  
16                case "green" -> green = Math.max(green, count);  
17                case "red" -> red = Math.max(red, count);  
18                case "blue" -> blue = Math.max(blue, count);  
19            }  
20        }  
21    }  
22  
23    return new Game(number, green, red, blue);  
24}

Then for the solution of part 1 all that is left is streaming over the Game instances filtering anything where green is lower then 13, red is less then 12 and blue is less then 14.

1public void part1() {  
2    var answer = inputLoader.splitOnNewLine()  
3            .map(this::createGame)  
4            .filter(game -> game.green() <= 13 && game.red() <= 12 && game.blue() <= 14)  
5            .mapToInt(Game::number)  
6            .sum();  
7    validator.part1(answer);  
8}

Part 2

For the second part of today only a very small adjustment is needed to get the product of green, red and blue.

1public void part2() {  
2    var answer = inputLoader.splitOnNewLine()  
3            .map(this::createGame)  
4            .mapToInt(game -> game.red() * game.green() * game.blue())
5            .sum();  
6    validator.part2(answer);  
7}

See also