MATL Advent of Code

December 1, 2024

Part 1

Solution (5 bytes): S!d|s

Online Demo

Explanation

This solution sorts each column of the input so that each row is the pair that should be compared as stated in the challenge. We can then compute the diff between the two columns, take the absolute difference and sum the result

       % Implicitly grab the input as a multi-dimensional array
S      % Sort the column in ascending order
!      % Transpose the array so the pairs are down the columns
d|     % Compute the element-wise absolute difference between the two rows
s      % Sum the result
       % Implicitly display the result

Part 2

Solution (10 bytes): !Z}yw!=s*s

Online Demo

Explanation

        % Implicitly grab the input as a 2D array
!Zy}    % Split the two columns into two items on the stack
y       % Duplicate the top of the stack
w       % Swap the top two stack elements
!=      % Broadcasted 2D matrix where it is 1 where the first column is equal to
        % any value in the second and zero otherwise
s       % Sum down the columns to count the number of matches
*       % Point-wise multiply this by the original first column
s       % Sum the resulting products
        % Implicitly display the result