Day 2: Cube Conundrum


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 6 minutes

10 points

Found a C per-char solution, that is, no lines, splitting, lookahead, etc. It wasn’t even necessary to keep match lengths for the color names because they all have unique characters, e.g. ‘b’ only occurs in “blue” so then you can attribute the count to that color.

int main()
{
	int p1=0,p2=0, id=1,num=0, r=0,g=0,b=0, c;

	while ((c = getchar()) != EOF)
		if (c==',' || c==';' || c==':') num = 0; else
		if (c>='0' && c<='9') num = num*10 + c-'0'; else
		if (c=='d') r = MAX(r, num); else
		if (c=='g') g = MAX(g, num); else
		if (c=='b') b = MAX(b, num); else
		if (c=='\n') {
			p1 += (r<=12 && g<=13 && b<=14) * id;
			p2 += r*g*b;
			r=g=b=0; id++;
		}

	printf("%d %d\n", p1, p2);
	return 0;
}

Golfed:

c,p,P,i,n,r,g,b;main(){while(~
(c=getchar()))c==44|c==58|59==
c?n=0:c>47&c<58?n=n*10+c-48:98
==c?b=b>n?b:n:c=='d'?r=r>n?r:n
:c=='g'?g=g>n?g:n:10==c?p+=++i
*(r<13&g<14&b<15),P+=r*g*b,r=g
=b=0:0;printf("%d %d\n",p,P);}
permalink
report
reply
6 points

Rust

Pretty straightforward this time, the bulk of the work was clearly in parsing the input.

permalink
report
reply
5 points

Not too tricky today. Part 2 wasn’t as big of a curveball as yesterday thankfully. I don’t think it’s the cleanest code I’ve ever written, but hey - the whole point of this is to get better at Rust, so I’ll definitely be learning as I go, and coming back at the end to clean a lot of these up. I think for this one I’d like to look into a parsing crate like nom to clean up all the spliting and unwrapping in the two from() methods.

https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day02.rs

#[derive(Debug)]
struct Hand {
    blue: usize,
    green: usize,
    red: usize,
}

impl Hand {
    fn from(input: &str) -> Hand {
        let mut hand = Hand {
            blue: 0,
            green: 0,
            red: 0,
        };

        for color in input.split(", ") {
            let color = color.split_once(' ').unwrap();
            match color.1 {
                "blue" => hand.blue = color.0.parse::().unwrap(),
                "green" => hand.green = color.0.parse::().unwrap(),
                "red" => hand.red = color.0.parse::().unwrap(),
                _ => unreachable!("malformed input"),
            }
        }

        hand
    }
}

#[derive(Debug)]
struct Game {
    id: usize,
    hands: Vec,
}

impl Game {
    fn from(input: &str) -> Game {
        let (id, hands) = input.split_once(": ").unwrap();
        let id = id.split_once(" ").unwrap().1.parse::().unwrap();
        let hands = hands.split("; ").map(Hand::from).collect();
        Game { id, hands }
    }
}

pub struct Day02;

impl Solver for Day02 {
    fn star_one(&self, input: &str) -> String {
        input
            .lines()
            .map(Game::from)
            .filter(|game| {
                game.hands
                    .iter()
                    .all(|hand| hand.blue <= 14 && hand.green <= 13 && hand.red <= 12)
            })
            .map(|game| game.id)
            .sum::()
            .to_string()
    }

    fn star_two(&self, input: &str) -> String {
        input
            .lines()
            .map(Game::from)
            .map(|game| {
                let max_blue = game.hands.iter().map(|hand| hand.blue).max().unwrap();
                let max_green = game.hands.iter().map(|hand| hand.green).max().unwrap();
                let max_red = game.hands.iter().map(|hand| hand.red).max().unwrap();

                max_blue * max_green * max_red
            })
            .sum::()
            .to_string()
    }
}
permalink
report
reply
4 points
*

Ruby

https://github.com/snowe2010/advent-of-code/blob/master/ruby_aoc/2023/day02/day02.rb

Second part was soooo much easier today than yesterday. Helps I solved it exactly how he wanted you to solve it I think.

I’m going to work on some code golf now.

Golfed P2 down to 133 characters:

p g.map{_1.sub!(/.*:/,'')
m=Hash.new(0)
_1.split(?;){|r|r.split(?,){|a|b,c=a.split
m[c]=[m[c],b.to_i].max}}
m.values.reduce(&:*)}.sum
permalink
report
reply
1 point

That’s a nice golf! Clever use of the hash and nice compact reduce. I got my C both-parts solution down to 210 but it’s not half as nice.

permalink
report
parent
reply
1 point

Thanks! Your C solution includes main, whereas I do some stuff to parse the lines before hand. I think it would only be 1 extra character if I wrote it to parse the input manually, but I just care for ease of use with these AoC problems so I don’t like counting that, makes it harder to read for me lol. Your solution is really inventive. I was looking for something like that, but didn’t ever get to your conclusion. I wonder if that would be longer in my solution or shorter 🤔

permalink
report
parent
reply
4 points
*

This was mostly straightforward… basically just parsing input. Here are my condensed solutions in Python

Part 1
Game = dict[str, int]

RED_MAX   = 12
GREEN_MAX = 13
BLUE_MAX  = 14

def read_game(stream=sys.stdin) -> Game:
    try:
        game_string, cubes_string = stream.readline().split(':')
    except ValueError:
        return {}

    game: Game = defaultdict(int)
    game['id'] = int(game_string.split()[-1])

    for cubes in cubes_string.split(';'):
        for cube in cubes.split(','):
            count, color = cube.split()
            game[color] = max(game[color], int(count))

    return game

def read_games(stream=sys.stdin) -> Iterator[Game]:
    while game := read_game(stream):
        yield game

def is_valid_game(game: Game) -> bool:
    return all([
        game['red']   <= RED_MAX,
        game['green'] <= GREEN_MAX,
        game['blue']  <= BLUE_MAX,
    ])

def main(stream=sys.stdin) -> None:
    valid_games = filter(is_valid_game, read_games(stream))
    sum_of_ids  = sum(game['id'] for game in valid_games)
    print(sum_of_ids)
Part 2

For the second part, the main parsing remainded the same. I just had to change what I did with the games I read.

def power(game: Game) -> int:
    return game['red'] * game['green'] * game['blue']

def main(stream=sys.stdin) -> None:
    sum_of_sets = sum(power(game) for game in read_games(stream))
    print(sum_of_sets)

GitHub Repo

permalink
report
reply

Advent Of Code

!advent_of_code@programming.dev

Create post

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
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

Rules/Guidelines

  • Follow the programming.dev instance rules
  • Keep all content related to advent of code in some way
  • If what youre posting relates to a day, put in brackets the year and then day number in front of the post title (e.g. [2023 Day 10])
  • When an event is running, keep solutions in the solution megathread to avoid the community getting spammed with posts

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

Community stats

  • 1

    Monthly active users

  • 76

    Posts

  • 778

    Comments