Skip Navigation

🦌 - 2023 DAY 2 SOLUTIONS -🦌

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

41 comments
  • 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.

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

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

  • 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

     rust
        
    #[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()
        }
    }
    
      
  • 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
    
      
  • 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 .
    ;
    
      
  • This was mostly straightforward... basically just parsing input. Here are my condensed solutions in Python

    GitHub Repo

  • I had some time, so here's a terrible solution in Uiua (Run it here) :

     
        
    Lim ← [14 13 12]
    {"Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green"
     "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue"
     "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red"
     "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red"
     "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green"}
    
    LtoDec ← ∧(+ ×10:) :0
    StoDec ← LtoDec▽≥0. ▽≤9. -@0
    FilterMax! ← /↥≡(StoDec⊢↙ ¯1)⊔⊏⊚≡(/×^1⊢).⊔
    # Build 'map' of draws for each game
    ∵(□≡(∵(⬚@\s↙2 ⊔) ⇌) ↯¯1_2 ↘ 2⊜□≠@\s . ⊔)
    # Only need the max for each colour
    ≡(⊂⊂⊃⊃(FilterMax!(="bl")) (FilterMax!(="gr")) (FilterMax!(="re")))
    # part 1 - Compare against limits, and sum game numbers
    /+▽:+1⇡⧻. ≡(/×≤0-Lim).
    # part 2 - Multiply the maxes in each game and then sum.
    /+/×⍉:
    
      
  • My (awful) Python solves. Much easier than day 1's, although I did run into an issue with trimming whitespace characters with my approach (Game 96 wouldn't flag properly).

  • 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

     py
        
    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)
    
      
  • Mostly an input parsing problem this time, but it was fun to use Hares tokenizer functions:

  • 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

  • Late as always, as I'm on UK time and can't work on these until late evening.

    Part 01 and Part 02 in Rust 🦀 :

     rust
        
    use std::{
        env, fs,
        io::{self, BufRead, BufReader},
    };
    
    #[derive(Debug)]
    struct Sample {
        r: u32,
        g: u32,
        b: u32,
    }
    
    fn split_cube_set(set: &[&str], colour: &str) -> Option {
        match set.iter().find(|x| x.ends_with(colour)) {
            Some(item) => item
                .trim()
                .split(' ')
                .next()
                .expect("Found item is present")
                .parse::()
                .ok(),
            None => None,
        }
    }
    
    fn main() -> io::Result<()> {
        let args: Vec = env::args().collect();
        let filename = &args[1];
        let file = fs::File::open(filename)?;
        let reader = BufReader::new(file);
        let mut valid_game_ids_sum = 0;
        let mut game_power_sum = 0;
        let max_r = 12;
        let max_g = 13;
        let max_b = 14;
        for line_result in reader.lines() {
            let mut valid_game = true;
            let line = line_result.unwrap();
            let line_split: Vec<_> = line.split(':').collect();
            let game_id = line_split[0]
                .split(' ')
                .collect::>()
                .last()
                .expect("item exists")
                .parse::()
                .expect("is a number");
            let rest = line_split[1];
            let cube_sets = rest.split(';');
            let samples: Vec = cube_sets
                .map(|set| {
                    let set_split: Vec<_> = set.split(',').collect();
                    let r = split_cube_set(&set_split, "red").unwrap_or(0);
                    let g = split_cube_set(&set_split, "green").unwrap_or(0);
                    let b = split_cube_set(&set_split, "blue").unwrap_or(0);
                    Sample { r, g, b }
                })
                .collect();
            let mut highest_r = 0;
            let mut highest_g = 0;
            let mut highest_b = 0;
            for sample in &samples {
                if !(sample.r <= max_r && sample.g <= max_g && sample.b <= max_b) {
                    valid_game = false;
                }
                highest_r = u32::max(highest_r, sample.r);
                highest_g = u32::max(highest_g, sample.g);
                highest_b = u32::max(highest_b, sample.b);
            }
            if valid_game {
                valid_game_ids_sum += game_id;
            }
            game_power_sum += highest_r * highest_g * highest_b;
        }
        println!("Sum of game ids: {valid_game_ids_sum}");
        println!("Sum of game powers: {game_power_sum}");
        Ok(())
    }
    
      
  • Today in Zig

    Spent most of the time running down annoying typos in the tokenizer.

  • A solution in Nim language. Pretty straightforward code. Most logic is just parsing input + a bit of functional utils: allIt checks if all items in a list within limits to check if game is possible and mapIt collects red, green, blue cubes from each set of game.

    https://codeberg.org/Archargelod/aoc23-nim/src/branch/master/day_02/solution.nim

     
        
    import std/[strutils, strformat, sequtils]
    
    type AOCSolution[T] = tuple[part1: T, part2: T]
    
    type
      GameSet = object
        red, green, blue: int
      Game = object
        id: int
        sets: seq[GameSet]
    
    const MaxSet = GameSet(red: 12, green: 13, blue: 14)
    
    func parseGame(input: string): Game =
      result.id = input.split({':', ' '})[1].parseInt()
      let sets = input.split(": ")[1].split("; ").mapIt(it.split(", "))
      for gSet in sets:
        var gs = GameSet()
        for pair in gSet:
          let
            pair = pair.split()
            cCount = pair[0].parseInt
            cName = pair[1]
    
          case cName:
          of "red":
            gs.red = cCount
          of "green":
            gs.green = cCount
          of "blue":
            gs.blue = cCount
    
        result.sets.add gs
    
    func isPossible(g: Game): bool =
      g.sets.allIt(
        it.red <= MaxSet.red and
        it.green <= MaxSet.green and
        it.blue <= MaxSet.blue
      )
    
    
    func solve(lines: seq[string]): AOCSolution[int]=
      for line in lines:
        let game = line.parseGame()
    
        block p1:
          if game.isPossible():
            result.part1 += game.id
    
        block p2:
          let
            minRed = game.sets.mapIt(it.red).max()
            minGreen = game.sets.mapIt(it.green).max()
            minBlue = game.sets.mapIt(it.blue).max()
    
          result.part2 += minRed * minGreen * minBlue
    
    
    when isMainModule:
      let input = readFile("./input.txt").strip()
      let (part1, part2) = solve(input.splitLines())
    
      echo &"Part 1: The sum of valid game IDs equals {part1}."
      echo &"Part 2: The sum of the sets' powers equals {part2}."
    
      
  • String parsing! Always fun in C!

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

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

  • Dart solution

    Quite straightforward, though there's a sneaky trap in the test data for those of us who don't read the rules carefully enough.

    Read, run and edit this solution in your browser: https://dartpad.dev/?id=203b3f0a9a1ad7a51daf14a1aeb6cf67

     
        
    parseLine(String s) {
      var game = s.split(': ');
      var num = int.parse(game.first.split(' ').last);
      var rounds = game.last.split('; ');
      var cubes = [
        for (var (e) in rounds)
          {
            for (var ee in e.split(', '))
              ee.split(' ').last: int.parse(ee.split(' ').first)
          }
      ];
      return MapEntry(num, cubes);
    }
    
    /// collects the max of the counts from both maps.
    Map merge2(Map a, Map b) => {
          for (var k in {...a.keys, ...b.keys}) k: max(a[k] ?? 0, b[k] ?? 0)
        };
    
    var limit = {"red": 12, "green": 13, "blue": 14};
    
    bool isGood(Map test) =>
        limit.entries.every((e) => (test[e.key] ?? 0) <= e.value);
    
    part1(List lines) => lines
        .map(parseLine)
        .where((e) => e.value.every(isGood))
        .map((e) => e.key)
        .sum;
    
    part2(List lines) => lines
        .map(parseLine)
        .map((e) => e.value.reduce(merge2))
        .map((e) => e.values.reduce((s, t) => s * t))
        .sum;
    
      
  • crystal

    (commented parts are for part 1)

     crystal
        
    input = File.read("input.txt").lines
    
    limits = {"red"=> 12, "green"=> 13, "blue"=> 14}
    # possibles = [] of Int32
    powers = [] of Int32
    
    input.each do |line|
        game = line.split(":")
        id = game[0].split()[1].to_i
        possible = true
        min = {"red"=> 0, "green"=> 0, "blue"=> 0}
        
        draws = game[1].split(";", &.split(",") do |cube|
            cubeinfo = cube.split
            num = cubeinfo[0].to_i
            
            min[cubeinfo[1]] = num if num > min[cubeinfo[1]] 
            
            # unless num <= limits[cubeinfo[1]]
            # 	possible = false
            # 	break
            # end 
        end )
        
        powers.push(min.values.product)
        # possibles.push(id) if possible
    end
    # puts possibles.sum
    puts powers.sum
    
      
    • Man I really need to learn Crystal. I love the ruby syntax and it's supposed to be really fast right?

      • Yeah, it's still a very small language, not much community or tooling, but a pleasure to use. In practice it'll hit half the speeds of low level languages like rust and C, but with way less effort.

  • My solution in python

     
        
    input="""Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
    Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
    Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
    Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
    Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green"""
    
    def parse(line):
        data={}
        data['game']=int(line[5:line.index(':')])
        data['hands']=[]
        for str in line[line.index(':')+1:].split(';'):
            h={'red':0,'green':0,'blue':0}
            for str2 in str.split(','):
                tmp=str2.strip(' ').split(' ')
                h[tmp[1]]=int(tmp[0])
            data['hands'].append(h)
    
        data['max_red']=max([x['red'] for x in data['hands']])
        data['max_green']=max([x['green'] for x in data['hands']])
        data['max_blue']=max([x['blue'] for x in data['hands']])
        data['power']=data['max_red']*data['max_green']*data['max_blue']
        data['possible'] = True
        if data['max_red'] > 12:
            data['possible'] = False
        if data['max_green'] > 13:
            data['possible'] = False
        if data['max_blue'] > 14:
            data['possible'] = False
    
    
        return data
    def loadFile(path):
        with open(path,'r') as f:
            return f.read()
    
    if __name__ == '__main__':
        input=loadFile('day2_input')
        res=[]
        total=0
        power_sum=0
        for row in input.split('\n'):
            data=parse(row)
            if data['possible']:
                total=total+data['game']
            power_sum=power_sum+data['power']
        print('total: %s, power: %s ' % (total,power_sum,))
    
      
  • Haskell

    A rather opaque parser, but much shorter than I could manage with Parsec.

     
        
    import Data.Bifunctor
    import Data.List.Split
    import Data.Map.Strict (Map)
    import qualified Data.Map.Strict as Map
    import Data.Tuple
    
    readGame :: String -> (Int, [Map String Int])
    readGame = bimap (read . drop 5) (map readPull . splitOn "; " . drop 2) . break (== ':')
      where
        readPull = Map.fromList . map (swap . bimap read tail . break (== ' ')) . splitOn ", "
    
    possibleWith limit = and . Map.intersectionWith (>=) limit
    
    main = do
      games <- map (fmap (Map.unionsWith max) . readGame) . lines <$> readFile "input02"
      let limit = Map.fromList [("red", 12), ("green", 13), ("blue", 14)]
      print $ sum $ map fst $ filter (possibleWith limit . snd) games
      print $ sum $ map (product . snd) games
    
      
  • I'm a bit late to the party for day 2. Here's my answer:

     
        
    use std::rc::Rc;
    
    use crate::utils::read_lines;
    
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum Cube {
        Red(usize),
        Green(usize),
        Blue(usize),
    }
    
    #[derive(Clone, Copy, PartialEq, Eq)]
    struct Bag {
        pub red: usize,
        pub green: usize,
        pub blue: usize,
    }
    
    fn parse_num<'a, I>(mut group: I) -> usize
    where
        I: Iterator,
    {
        group
            .next()
            .expect("Should be number")
            .parse::()
            .expect("Should be number")
    }
    
    fn process_lines() -> impl Iterator> {
        read_lines("src/day_2/input.txt")
            .expect("Could not read file")
            .map(|line| {
                let line = line.expect("Should be line");
                (&line[(line.find(':').unwrap() + 1)..])
                    .split(';')
                    .flat_map(|section| section.split(","))
                    .map(|group| {
                        let mut group = group.trim().split(' ');
    
                        match group.next_back().expect("Should be color") {
                            "red" => Cube::Red(parse_num(group)),
                            "green" => Cube::Green(parse_num(group)),
                            "blue" => Cube::Blue(parse_num(group)),
                            c @ _ => panic!("Color {c} not recognized"),
                        }
                    })
                    .collect::>()
            })
            .into_iter()
    }
    
    pub fn solution_1() {
        let bag = Bag {
            red: 12,
            green: 13,
            blue: 14,
        };
        let sum: usize = process_lines()
            .enumerate()
            .map(|(i, line)| {
                let is_possible = line.iter().all(|cube| match cube {
                    Cube::Red(c) => *c <= bag.red,
                    Cube::Green(c) => *c <= bag.green,
                    Cube::Blue(c) => *c <= bag.blue,
                });
    
                if is_possible {
                    i + 1
                } else {
                    0
                }
            })
            .sum();
    
        println!("{sum}");
    }
    
    pub fn solution_2() {
        let powersum: usize = process_lines()
            .map(|line| {
                let bag = line.iter().fold(
                    Bag {
                        red: 0,
                        blue: 0,
                        green: 0,
                    },
                    |mut bag, cube| {
                        match *cube {
                            Cube::Red(n) => {
                                if n > bag.red {
                                    bag.red = n;
                                }
                            }
                            Cube::Green(n) => {
                                if n > bag.green {
                                    bag.green = n;
                                }
                            }
                            Cube::Blue(n) => {
                                if n > bag.blue {
                                    bag.blue = n;
                                }
                            }
                        }
    
                        bag
                    },
                );
    
                bag.red * bag.blue * bag.green
            })
            .sum();
    
        println!("{powersum}");
    }
    
      
  • [LANGUAGE: C#]

    Part 1:

     
            var list = new List((await File.ReadAllLinesAsync(@".\Day 2\PuzzleInput.txt")));
        int conter = 0;
        foreach (var line in list)
        {
            string[] split = line.Split(":");
            int game = Int32.Parse( split[0].Split(" ")[1]);
            string[] bagContents = split[1].Split(";");
            var max = new Dictionary() { { "red", 0 }, { "green", 0 }, { "blue", 0 } };
            foreach (var content in bagContents)
            {
                string pattern = @"(\d+) (\w+)";
                MatchCollection matches = Regex.Matches(content, pattern);
        
                foreach (Match match in matches)
                {
                    int number = Int32.Parse(match.Groups[1].Value);
                    string color = match.Groups[2].Value;
                    max[color] = (max[color] >= number)? max[color] : number;
                }
            }
            conter += (max["red"] <= 12 && max["green"] <= 13 && max["blue"] <= 14) ? game : 0;
    
        }
        Console.WriteLine(conter);
    
    
    
      

    Part 2:

     
            var list = new List((await File.ReadAllLinesAsync(@".\Day 2\PuzzleInput.txt")));
    
        int conter = 0;
        foreach (var line in list)
        {
            string[] split = line.Split(":");
            int game = Int32.Parse(split[0].Split(" ")[1]);
            string[] bagContents = split[1].Split(";");
                var max = new Dictionary();
            foreach (var content in bagContents)
            {
                string pattern = @"(\d+) (\w+)";
    
                MatchCollection matches = Regex.Matches(content, pattern);
    
                foreach (Match match in matches)
                {
                    int number = Int32.Parse(match.Groups[1].Value);
                    string color = match.Groups[2].Value;
                    if (!max.ContainsKey(color))
                        max[color] = number;
                    else if(max[color] < number)
                        max[color] = number;
                }
            }
            conter += max.Values.Aggregate(1, (total, value) => total *  value );
    
        }
        Console.WriteLine(conter);
      
    • It was confusing. It took me 3 tries to write the parser. The first time I didn’t realize there were multiple observations per game and the second time for some reason I was convinced the color came first.

  • [Language: Lean4]

    I'll only post the actual parsing and solution. I have written some helpers which are in other files, as is the main function. For the full code, please see my github repo.

  • Just getting started with Rust, part 1 took a long time. Really amazed when I saw part 2, just needed to add 2 lines and was done due to the approach I had taken. Feedback more than welcome!

     rust
        
    use std::{
        cmp, fs,
        io::{BufRead, BufReader},
    };
    
    fn main() {
        cube_conundrum_complete();
    }
    
    fn cube_conundrum_complete() {
        // Load the data file
        let filename = "./data/input_data/day_2_cubes.txt";
        let file = match fs::File::open(filename) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("Error opening file: {}", e);
                return;
            }
        };
        let reader = BufReader::new(file);
    
        // iniatiate final results
        let mut total = 0;
        let mut total_power = 0;
    
        // loop over the games in the file
        for _line in reader.lines() {
            // Handle the data and extract game number and maximum number of cubes per color
            let (game_number, max_green, max_red, max_blue) = cube_conundrum_data_input(_line.unwrap());
    
            // Calculate the power for the day 2 result
            total_power += max_green * max_red * max_blue;
    
            //Calculate if the game was possible with the given number of cubes
            let result = cube_conundrum_game_possible(game_number, max_green, max_red, max_blue);
            total += result;
        }
    
        // print the final results
        println!("total part 1: {}", total);
        println!("total part 2: {}", total_power);
    }
    
    fn cube_conundrum_data_input(game_input: String) -> (i32, i32, i32, i32) {
        // Split the game number from the draws
        let (game_part, data_part) = game_input.split_once(":").unwrap();
    
        // Select the number of the round and parse into an integer
        let game_number: i32 = game_part
            .split_once(" ")
            .unwrap()
            .1
            .parse::()
            .expect("could not parse gamenumber to integer");
    
        // Split the data part into a vector both split on , and ; cause we only care about he maximum per color
        let parts: Vec<&str> = data_part
            .split(|c| c == ',' || c == ';')
            .map(|part| part.trim())
            .collect();
    
        // Set the intial values for the maximum per color to 0
        let (mut max_green, mut max_red, mut max_blue) = (0, 0, 0);
    
        // Loop over the different draws split them into color and nubmer of cubes, update maximum number of cubes
        for part in parts.iter() {
            let (nr_cubes_text, color) = part.split_once(" ").unwrap();
            let nr_cubes = nr_cubes_text
                .parse::()
                .expect("could not parse to integer");
            match color {
                "green" => max_green = cmp::max(max_green, nr_cubes),
                "red" => max_red = cmp::max(max_red, nr_cubes),
                "blue" => max_blue = cmp::max(max_blue, nr_cubes),
                _ => println!("unknown color: {}", color),
            };
        }
    
        return (game_number, max_green, max_red, max_blue);
    }
    
    fn cube_conundrum_game_possible(
        game_number: i32,
        max_green: i32,
        max_red: i32,
        max_blue: i32,
    ) -> i32 {
        // Compare the number of seen cubes per game with the proposed number. Return the game number if it was possible, otherwise 0
        let (comparison_red, comparison_green, comparison_blue) = (12, 13, 14);
        if max_green > comparison_green || max_red > comparison_red || max_blue > comparison_blue {
            return 0;
        };
        game_number
    }
    
      
41 comments