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

  • 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);}
    
  • 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

  •  Nighed   ( @Nighed@sffa.community ) 
    link
    fedilink
    English
    3
    edit-2
    7 months ago

    Done in C# Input parsing done with a mixture of splits and Regex (no idea why everyone hates it?) capture groups.

    I have overbuilt for both days, but not tripped on any of the ‘traps’ in the input data - generally expecting the input to be worse than it is… too used to actual data from users

    Input Parsing (common)

    public class Day2RoundInput { private Regex gameNumRegex = new Regex(“[a-z]* ([0-9]*)”, RegexOptions.IgnoreCase);

        public Day2RoundInput(string gameString)
        {
            var colonSplit = gameString.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries);
            var match = gameNumRegex.Match(colonSplit[0].Trim());
            var gameNumberString = match.Groups[1].Value;
            GameNumber = int.Parse(gameNumberString.Trim());
    
            HandfulsOfCubes = new List();
            var roundsSplit = colonSplit[1].Trim().Split(';', StringSplitOptions.RemoveEmptyEntries);
            foreach (var round in roundsSplit)
            {
                HandfulsOfCubes.Add(new HandfulCubes(round));
            }
        }
        public int GameNumber { get; set; }
    
        public List HandfulsOfCubes { get; set; }
    
        public class HandfulCubes
        {
            private Regex colourRegex = new Regex("([0-9]*) (red|green|blue)");
    
            public HandfulCubes(string roundString)
            {
                var colourCounts = roundString.Split(',', StringSplitOptions.RemoveEmptyEntries);
                foreach (var colour in colourCounts)
                {
                    var matches = colourRegex.Matches(colour.Trim());
    
                    foreach (Match match in matches)
                    {
                        var captureOne = match.Groups[1];
    
                        var count = int.Parse(captureOne.Value.Trim());
    
                        var captureTwo = match.Groups[2];
    
                        switch (captureTwo.Value.Trim().ToLower())
                        {
                            case "red":
                                RedCount = count;
                                break;
                            case "green":
                                GreenCount = count;
                                break;
                            case "blue":
                                BlueCount = count;
                                break;
                            default: throw new Exception("uh oh");
                        }
                    }
                }
            }
    
            public int RedCount { get; set; }
            public int GreenCount { get; set; }
            public int BlueCount { get; set; }
        }
    
    }
    
    Task1

    internal class Day2Task1:IRunnable { public void Run() { var inputs = GetInputs();

            var maxAllowedRed = 12;
            var maxAllowedGreen = 13;
            var maxAllowedBlue = 14;
    
            var allowedGameIdSum = 0;
    
            foreach ( var game in inputs ) { 
                var maxRed = game.HandfulsOfCubes.Select(h => h.RedCount).Max();
                var maxGreen = game.HandfulsOfCubes.Select(h => h.GreenCount).Max();
                var maxBlue = game.HandfulsOfCubes.Select(h => h.BlueCount).Max();
    
                if ( maxRed <= maxAllowedRed && maxGreen <= maxAllowedGreen && maxBlue <= maxAllowedBlue) 
                {
                    allowedGameIdSum += game.GameNumber;
                    Console.WriteLine("Game:" + game.GameNumber + " allowed");
                }
                else
                {
                    Console.WriteLine("Game:" + game.GameNumber + "not allowed");
                }
            }
    
            Console.WriteLine("Sum:" + allowedGameIdSum.ToString());
    
        }
    
        private List GetInputs()
        {
            List inputs = new List();
    
            var textLines = File.ReadAllLines("Days/Two/Day2Input.txt");
    
            foreach (var line in textLines)
            {
                inputs.Add(new Day2RoundInput(line));
            }
    
            return inputs;
        }
    
        
    }
    
    Task2

    internal class Day2Task2:IRunnable { public void Run() { var inputs = GetInputs();

            var result = 0;
    
            foreach ( var game in inputs ) {
                var maxRed = game.HandfulsOfCubes.Select(h => h.RedCount).Max();
                var maxGreen = game.HandfulsOfCubes.Select(h => h.GreenCount).Max();
                var maxBlue = game.HandfulsOfCubes.Select(h => h.BlueCount).Max();
    
                var power = maxRed*maxGreen*maxBlue;
                Console.WriteLine("Game:" + game.GameNumber + " Result:" + power.ToString());
    
                result += power;
            }
    
            Console.WriteLine("Day2 Task2 Result:" + result.ToString());
    
        }
    
        private List GetInputs()
        {
            List inputs = new List();
    
            var textLines = File.ReadAllLines("Days/Two/Day2Input.txt");
            //var textLines = File.ReadAllLines("Days/Two/Day2ExampleInput.txt");
    
            foreach (var line in textLines)
            {
                inputs.Add(new Day2RoundInput(line));
            }
    
            return inputs;
        }
    
        
    }
    
  • 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
    
      • 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 🤔

  • Did mine in Odin. Found this day’s to be super easy, most of the challenge was just parsing.

    package day2
    
    import "core:fmt"
    import "core:strings"
    import "core:strconv"
    import "core:unicode"
    
    Round :: struct {
        red: int,
        green: int,
        blue: int,
    }
    
    parse_round :: proc(s: string) -> Round {
        ret: Round
    
        rest := s
        for {
            nextNumAt := strings.index_proc(rest, unicode.is_digit)
            if nextNumAt == -1 do break
            rest = rest[nextNumAt:]
    
            numlen: int
            num, ok := strconv.parse_int(rest, 10, &numlen)
            rest = rest[numlen+len(" "):]
    
            if rest[:3] == "red" {
                ret.red = num
            } else if rest[:4] == "blue" {
                ret.blue = num
            } else if rest[:5] == "green" {
                ret.green = num
            }
        }
    
        return ret
    }
    
    Game :: struct {
        id: int,
        rounds: [dynamic]Round,
    }
    
    parse_game :: proc(s: string) -> Game {
        ret: Game
    
        rest := s[len("Game "):]
    
        idOk: bool
        idLen: int
        ret.id, idOk = strconv.parse_int(rest, 10, &idLen)
        rest = rest[idLen+len(": "):]
    
        for len(rest) > 0 {
            endOfRound := strings.index_rune(rest, ';')
            if endOfRound == -1 do endOfRound = len(rest)
    
            append(&ret.rounds, parse_round(rest[:endOfRound]))
            rest = rest[min(endOfRound+1, len(rest)):]
        }
    
        return ret
    }
    
    is_game_possible :: proc(game: Game) -> bool {
        for round in game.rounds {
            if round.red   > 12 ||
               round.green > 13 ||
               round.blue  > 14 {
                return false
            }
        }
        return true
    }
    
    p1 :: proc(input: []string) {
        totalIds := 0
    
        for line in input {
            game := parse_game(line)
            defer delete(game.rounds)
    
            if is_game_possible(game) do totalIds += game.id
        }
    
        fmt.println(totalIds)
    }
    
    p2 :: proc(input: []string) {
        totalPower := 0
    
        for line in input {
            game := parse_game(line)
            defer delete(game.rounds)
    
            minRed   := 0
            minGreen := 0
            minBlue  := 0
            for round in game.rounds {
                minRed   = max(minRed  , round.red  )
                minGreen = max(minGreen, round.green)
                minBlue  = max(minBlue , round.blue )
            }
    
            totalPower += minRed * minGreen * minBlue
        }
    
        fmt.println(totalPower)
    }
    
  •  Andy   ( @Andy@programming.dev ) 
    link
    fedilink
    2
    edit-2
    6 months ago

    Factor on github (with comments and imports):

    : known-color ( color-phrases regexp -- n )
      all-matching-subseqs [ 0 ] [
        [ split-words first string>number ] map-supremum
      ] if-empty
    ;
    
    : line>known-rgb ( str -- game-id known-rgb )
      ": " split1 [ split-words last string>number ] dip
      R/ \d+ red/ R/ \d+ green/ R/ \d+ blue/
      [ known-color ] tri-curry@ tri 3array
    ;
    
    : possible? ( known-rgb test-rgb -- ? )
      v<= [ ] all?
    ;
    
    : part1 ( -- )
      "vocab:aoc-2023/day02/input.txt" utf8 file-lines
      [ line>known-rgb 2array ]
      [ last { 12 13 14 } possible? ] map-filter
      [ first ] map-sum .
    ;
    
    : part2 ( -- )
      "vocab:aoc-2023/day02/input.txt" utf8 file-lines
      [ line>known-rgb nip product ] map-sum .
    ;
    
  •  Ategon   ( @Ategon@programming.dev ) OP
    link
    fedilink
    2
    edit-2
    7 months ago

    Rust (Rank 7421/6311) (Time after start 00:32:27/00:35:35)

    Extremely easy part 2 today, I would say easier than part 1 but they share the same sort of framework

    Code Block

    (Note lemmy removed some characters, code link shows them all)

    use std::fs;
    
    fn part1(input: String) -> i32 {
        const RED: i32 = 12;
        const GREEN: i32 = 13;
        const BLUE: i32 = 14;
    
        let mut sum = 0;
    
        for line in input.lines() {
            let [id, content] = line.split(": ").collect::>()[0..2] else { continue };
            let id = id.split(" ").collect::>()[1].parse::().unwrap();
    
            let marbles = content.split("; ").map(|x| { x.split(", ").collect::>() }).collect::>>();
            let mut valid = true;
    
            for selection in marbles {
                for marble in selection {
                    let marble_split = marble.split(" ").collect::>();
                    let marble_amount = marble_split[0].parse::().unwrap();
                    let marble_color = marble_split[1];
    
                    if marble_color == "red" && marble_amount > RED {
                        valid = false;
                        break;
                    }
    
                    if marble_color == "green" && marble_amount > GREEN {
                        valid = false;
                        break;
                    }
    
                    if marble_color == "blue" && marble_amount > BLUE {
                        valid = false;
                        break;
                    }
                }
            }
    
            if !valid {
                continue;
            }
    
            sum += id;
        }
    
        return sum;
    }
    
    fn part2(input: String) -> i32 {
        let mut sum = 0;
    
        for line in input.lines() {
            let [id, content] = line.split(": ").collect::>()[0..2] else { continue };
            let id = id.split(" ").collect::>()[1].parse::().unwrap();
    
            let marbles = content.split("; ").map(|x| { x.split(", ").collect::>() }).collect::>>();
            
            let mut red = 0;
            let mut green = 0;
            let mut blue = 0;
    
            for selection in marbles {
                for marble in selection {
                    let marble_split = marble.split(" ").collect::>();
                    let marble_amount = marble_split[0].parse::().unwrap();
                    let marble_color = marble_split[1];
    
                    if marble_color == "red" && marble_amount > red {
                        red = marble_amount;
                    }
    
                    if marble_color == "green" && marble_amount > green {
                        green = marble_amount;
                    }
    
                    if marble_color == "blue" && marble_amount > blue {
                        blue = marble_amount;
                    }
                }
            }
    
            sum += red * green * blue;
        }
    
        return sum;
    }
    
    fn main() {
        let input = fs::read_to_string("data/input.txt").unwrap();
    
        println!("{}", part1(input.clone()));
        println!("{}", part2(input.clone()));
    }
    

    Code Link

  • String parsing! Always fun in C!

    https://github.com/sjmulder/aoc/blob/master/2023/c/day02.c

    int main(int argc, char **argv)
    {
    	char ln[256], *sr,*srd,*s;
    	int p1=0,p2=0, id, r,g,b;
    
    	for (id=1; (sr = fgets(ln, sizeof(ln), stdin)); id++) {
    		strsep(&sr, ":");
    		r = g = b = 0;
    
    		while ((srd = strsep(&sr, ";")))
    		while ((s = strsep(&srd, ",")))
    			if (strchr(s, 'd')) r = MAX(r, atoi(s)); else
    			if (strchr(s, 'g')) g = MAX(g, atoi(s)); else
    			if (strchr(s, 'b')) b = MAX(b, atoi(s));
    	
    		p1 += (r <= 12 && g <= 13 && b <= 14) * id;
    		p2 += r * g * b;
    	}
    
    	printf("%d %d\n", p1, p2);
    	return 0;
    }
    
  • Mostly an input parsing problem this time, but it was fun to use Hares tokenizer functions:

    lua
    -- SPDX-FileCopyrightText: 2023 Jummit
    --
    -- SPDX-License-Identifier: GPL-3.0-or-later
    
    local colors = {"blue", "red", "green"}
    local available = {red = 12, blue = 14, green = 13}
    local possible = 0
    local id = 0
    local min = 0
    
    for game in io.open("2.input"):lines() do
      id = id + 1
      game = game:gsub("Game %d+: ", "").."; "
      local max = {red = 0, blue = 0, green = 0}
      for show in game:gmatch(".-; ") do
        for _, color in ipairs(colors) do
          local num = tonumber(show:match("(%d+) "..color))
          if num then
            max[color] = math.max(max[color], num)
          end
        end
      end
      min = min + max.red * max.blue * max.green
      local thisPossible = true
      for _, color in ipairs(colors) do
        if max[color] > available[color] then
          thisPossible = false
          break
        end
      end
      if thisPossible then
        possible = possible + id
      end
    end
    
    print(possible)
    print(min)
    
    hare
    // SPDX-FileCopyrightText: 2023 Jummit
    //
    // SPDX-License-Identifier: GPL-3.0-or-later
    
    use strconv;
    use types;
    use strings;
    use io;
    use bufio;
    use os;
    use fmt;
    
    const available: []uint = [12, 13, 14];
    
    fn color_id(color: str) const uint = {
    	switch (color) {
    	case "red" => return 0;
    	case "green" => return 1;
    	case "blue" => return 2;
    	case => abort();
    	};
    };
    
    export fn main() void = {
    	const file = os::open("2.input")!;
    	defer io::close(file)!;
    	const scan = bufio::newscanner(file, types::SIZE_MAX);
    	let possible: uint = 0;
    	let min: uint = 0;
    
    	for (let id = 1u; true; id += 1) {
    		const line = match(bufio::scan_line(&scan)!) {
    		case io::EOF =>
    			break;
    		case let line: const str =>
    			yield strings::sub(
    					line,
    					strings::index(line, ": ") as size + 2,
    					strings::end);
    		};
    		let max: []uint = [0, 0, 0];
    		let tok = strings::rtokenize(line, "; ");
    		for (true) {
    			const show = match(strings::next_token(&tok)) {
    			case void =>
    				break;
    			case let show: str =>
    				yield show;
    			};
    			const pairs = strings::tokenize(show, ", ");
    			for (true) {
    				const pair: (str, str) = match(strings::next_token(&pairs)) {
    				case void =>
    					break;
    				case let pair: str =>
    					let tok = strings::tokenize(pair, " ");
    					yield (
    						strings::next_token(&tok) as str,
    						strings::next_token(&tok) as str
    					);
    				};
    				let color = color_id(pair.1);
    				let amount = strconv::stou(pair.0)!;
    				if (amount > max[color]) max[color] = amount;
    			};
    		};
    		if (max[0] <= available[0] && max[1] <= available[1] && max[2] <= available[2]) {
    			fmt::printfln("{}", id)!;
    			possible += id;
    		};
    		min += max[0] * max[1] * max[2];
    	};
    	
    	fmt::printfln("{}", possible)!;
    	fmt::printfln("{}", min)!;
    };
    
  • Was pretty simple in Python with a regex to get the game number, and then the count of color. for part 2 instead of returning true/false whether the game is valid, you just max the count per color. No traps like in the first one, that I’ve seen, so it was surprisingly easy

    def process_game(line: str):
        game_id = int(re.findall(r'game (\d+)*', line)[0])
    
        colon_idx = line.index(":")
        draws = line[colon_idx+1:].split(";")
        # print(draws)
        
        if is_game_valid(draws):
            # print("Game %d is possible"%game_id)
            return game_id
        return 0
    
                
    def is_game_valid(draws: list):
        for draw in draws:
            red = get_nr_of_in_draw(draw, 'red')
            if red > MAX_RED:
                return False
            
            green = get_nr_of_in_draw(draw, 'green')
            if green > MAX_GREEN:
                return False
            
            blue = get_nr_of_in_draw(draw, 'blue')
            if blue > MAX_BLUE:
                return False    
        return True
            
                
    def get_nr_of_in_draw(draw: str, color: str):
        if color in draw:
            nr = re.findall(r'(\d+) '+color, draw)
            return int(nr[0])
        return 0
    
    
    # f = open("input.txt", "r")
    f = open("input_real.txt", "r")
    lines = f.readlines()
    sum = 0
    for line in lines:
        sum += process_game(line.strip().lower())
    print("Answer: %d"%sum)