MATL Advent of Code

December 3, 2024

Part 1

Solution (34 bytes): '(?<=mul\()\d+,\d+(?=\))'XX"@gUpvs

Online Demo

Explanation

This approach uses a regular expression to locate all mul(#,#) occurrences in the input string and uses look-ahead and look-behind assertions and capture groups to extract only the #,# part which we can then parse into a numeric array in MATL and perform multiplication and subsequent addition.

                               % Implicitly grab input as a string literal
'(?<=mul\()\d+,\d+(?=\))'      % Regular expression to match the numeric parts of mul(#,#)
XX                             % Perform regular expression matching
"                              % For each match (e.g. "3,4")
  @gU                          % Convert the match to a numeric array (e.g. [3, 4])
  p                            % Take the product of elements in the array
  v                            % Vertically concatenate the entire stack
  s                            % Sum the stack
                               % Implicitly display the result

Part 2

Solution (68 bytes): '(do\(\)|^).*?(don''t\(\)|$)'XX"@g'(?<=mul\()\d+,\d+(?=\))'XX"@gUpvs

Online Demo

Explanation

The solution first uses a regex to extract all parts of the string that are between a do() (or the beginning of the input) and a don't() (or the end of the input) in a non-greedy way. Then each matching string is feed through the same algorithm as Part 1 to extract the contents of mul(#,#) blocks and perform the multiplication and subsequent addition.

This solution could have been much shorter if I spent more time combining the regular expressions into one.

                                 % Implicitly grab input as a string literal
'(do\(\)|^).*?(don''t\(\)|$)'    % Regular expression to match do()...don't() groups
XX                               % Perform regular expression to extract parts to consider further
"                                % For each match
  @g                             % Convert to a string array
  '(?<=mul\()\d+,\d+(?=\))'      % Regular expression to match the #,# in mul(#,#) blocks
  XX                             % Perform the regular expression match
  "                              % For each match (e.g. "3,4")
    @gU                          % Convert the match to a numeric array (e.g. [3, 4])
    p                            % Take the product of elements in the array
    v                            % Vertically concatenate the entire stack
    s                            % Sum the stack
                                 % Implicitly display the result