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

  • @[email protected]
    cake
    link
    fedilink
    English
    3
    edit-2
    2 years 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;
        }
    
        
    }
    
    • Ryan
      link
      fedilink
      English
      12 years ago

      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.

  • AtegonOPM
    link
    fedilink
    3
    edit-2
    2 years 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

  • @[email protected]
    link
    fedilink
    32 years ago

    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)
    }
    
  • @[email protected]
    link
    fedilink
    22 years ago

    Python

    Questions and feedback welcome!

    import collections
    
    from .solver import Solver
    
    class Day02(Solver):
      def __init__(self):
        super().__init__(2)
        self.games = []
    
      def presolve(self, input: str):
        lines = input.rstrip().split('\n')
        for line in lines:
          draws = line.split(': ')[1].split('; ')
          draws = [draw.split(', ') for draw in draws]
          self.games.append(draws)
    
      def solve_first_star(self):
        game_id = 0
        total = 0
        for game in self.games:
          game_id += 1
          is_good = True
          for draw in game:
            for item in draw:
              count, colour = item.split(' ')
              if (colour == 'red' and int(count) > 12 or  # pylint: disable=too-many-boolean-expressions
                    colour == 'blue' and int(count) > 14 or
                    colour == 'green' and int(count) > 13):
                is_good = False
          if is_good:
            total += game_id
        return total
    
      def solve_second_star(self):
        total = 0
        for game in self.games:
          minimums = collections.defaultdict(lambda: 0)
          for draw in game:
            for item in draw:
              count, colour = item.split(' ')
              minimums[colour] = max(minimums[colour], int(count))
          power = minimums['red'] * minimums['blue'] * minimums['green']
          total += power
        return total
    
  • @[email protected]
    link
    fedilink
    22 years ago

    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,))
    
  • @[email protected]
    link
    fedilink
    English
    12 years ago

    [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.

    Solution
    structure Draw (α : Type) where
      red : α
      green : α
      blue : α
      deriving Repr
    
    structure Game where
      id : Nat
      draw : List $ Draw Nat
      deriving Repr
    
    def parse (input : String) : Option $ List Game :=
      let lines := input.splitTrim (. == '\n')
      let lines := lines.filter (not ∘ String.isEmpty)
      let parse_single_line : (String → Option Game):= λ (l : String) ↦ do
        let parse_id := λ (s : String) ↦ do
          let rest ← if s.startsWith "Game " then some (s.drop 5) else none
          rest.toNat?
        let parse_draw := λ (s : String) ↦ do
          let s := s.splitTrim (· == ',')
          let findAndRemoveTail := λ (s : String) (t : String) ↦
            if s.endsWith t then
              some $ String.dropRight s (t.length)
            else
              none
          let update_draw_parse := λ (pd : Option (Draw (Option String))) (c : String) ↦ do
            let old ← pd
            let red := findAndRemoveTail c " red"
            let green := findAndRemoveTail c " green"
            let blue := findAndRemoveTail c " blue"
            match red, green, blue with
            | some red, none, none => match old.red with
              | none => some $ {old with red := some red}
              | some _ => none
            | none, some green, none => match old.green with
              | none => some $ {old with green := some green}
              | some _ => none
            | none, none, some blue => match old.blue with
              | none => some $ {old with blue := some blue}
              | some _ => none
            | _, _, _  => none
          let parsed_draw ← s.foldl update_draw_parse (some $ Draw.mk none none none)
          let parsed_draw := {
            red := String.toNat? <$> parsed_draw.red,
            green := String.toNat? <$> parsed_draw.green,
            blue := String.toNat? <$> parsed_draw.blue : Draw _}
          let extractOrFail := λ (s : Option $ Option Nat) ↦ match s with
            | none => some 0
            | some none => none
            | some $ some x => some x
          let red ← extractOrFail parsed_draw.red
          let green ← extractOrFail parsed_draw.green
          let blue ← extractOrFail parsed_draw.blue
          pure { red := red, blue := blue, green := green : Draw _}
        let parse_draws := λ s ↦ List.mapM parse_draw $ s.splitTrim (· == ';')
        let (id, draw) ← match l.splitTrim (· == ':') with
        | [l, r] => Option.zip (parse_id l) (parse_draws r)
        | _ => none
        pure { id := id, draw := draw}
      lines.mapM parse_single_line
    
    def part1 (games : List Game) : Nat :=
      let draw_possible := λ g ↦ g.red ≤ 12 && g.green ≤ 13 && g.blue ≤ 14
      let possible := flip List.all draw_possible
      let possible_games := games.filter (possible ∘ Game.draw)
      possible_games.map Game.id |> List.foldl Nat.add 0
    
    def part2 (games : List Game) : Nat :=
      let powerOfGame := λ (g : Game) ↦
        let minReq := λ (c : Draw Nat → Nat) ↦
          g.draw.map c |> List.maximum? |> flip Option.getD 0
        minReq Draw.red * minReq Draw.green * minReq Draw.blue
      let powers := games.map powerOfGame
      powers.foldl Nat.add 0
    
  • Amy
    link
    fedilink
    2
    edit-2
    2 years ago

    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
    
  • bugsmith
    link
    fedilink
    3
    edit-2
    2 years ago

    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 🦀 :

    use std::{
        env, fs,
        io::{self, BufRead, BufReader},
    };
    
    #[derive(Debug)]
    struct Sample {
        r: u32,
        g: u32,
        b: u32,
    }
    
    fn split_cube_set(set: &amp;[&amp;str], colour: &amp;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&lt;()> {
        let args: Vec = env::args().collect();
        let filename = &amp;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&lt;_> = 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&lt;_> = set.split(',').collect();
                    let r = split_cube_set(&amp;set_split, "red").unwrap_or(0);
                    let g = split_cube_set(&amp;set_split, "green").unwrap_or(0);
                    let b = split_cube_set(&amp;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 &amp;samples {
                if !(sample.r &lt;= max_r &amp;&amp; sample.g &lt;= max_g &amp;&amp; sample.b &lt;= 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(())
    }
    
  • janAkali
    link
    fedilink
    English
    3
    edit-2
    2 years ago

    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 &lt;= MaxSet.red and
        it.green &lt;= MaxSet.green and
        it.blue &lt;= 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 &amp;"Part 1: The sum of valid game IDs equals {part1}."
      echo &amp;"Part 2: The sum of the sets' powers equals {part2}."
    
      • janAkali
        link
        fedilink
        English
        12 years ago

        Have you joined the community?

        Yep, but it is a bit quiet in there.

        Good solution. I like your parsing with scanf. The only reason I didn’t use it myself - is that I found out about std/strscans literally yesterday.

        • cacheson
          link
          fedilink
          22 years ago

          I actually just learned about scanf while writing this. Only ended up using it in the one spot, since split worked well enough for the other bits. I really wanted to be able to use python-style unpacking, but in nim it only works for tuples. At least without writing macros, which I still haven’t been able to wrap my head around.

      • CommunityLinkFixerBotB
        link
        fedilink
        English
        12 years ago

        Hi there! Looks like you linked to a Lemmy community using a URL instead of its name, which doesn’t work well for people on different instances. Try fixing it like this: [email protected]

  • @[email protected]
    link
    fedilink
    12 years ago

    [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"] &lt;= 12 &amp;&amp; max["green"] &lt;= 13 &amp;&amp; max["blue"] &lt;= 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] &lt; number)
                    max[color] = number;
            }
        }
        conter += max.Values.Aggregate(1, (total, value) => total *  value );
    
    }
    Console.WriteLine(conter);
    
  • @[email protected]
    link
    fedilink
    4
    edit-2
    2 years ago

    Factor on github:

    note: lemmy mangles the less-than-or-equals sign in the possible? function

    USING: arrays assocs io.encodings.utf8 io.files kernel math
    math.parser math.vectors prettyprint regexp sequences splitting
    ;
    IN: aoc-2023.day02
    
    : 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&lt;= [ ] all?
    ;
    
    : part1 ( -- )
      "input.txt" utf8 file-lines
      [ line>known-rgb 2array ] map
      [ last { 12 13 14 } possible? ] filter
      [ first ] map-sum .
    ;
    
    : part2 ( -- )
      "input.txt" utf8 file-lines
      [ line>known-rgb nip product ] map-sum .
    ;
    
  • @[email protected]
    link
    fedilink
    102 years ago

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