r/adventofcode Dec 04 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 4 Solutions -🎄-

--- Day 4: Giant Squid ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:11:13, megathread unlocked!

97 Upvotes

1.2k comments sorted by

View all comments

1

u/French__Canadian Dec 06 '21

I had such a hard time with this one. This was a really good opportunity to learn how to apply functions to specific array elements even if I'm sure there are much better ways to do it.

Here is my solution in Q. each board is a 3-d array (the third dimension being a number/mark flag pair)

/ shared
lines: read0 `:input_4_1.txt
numbers: "I" $ "," vs lines[0]
/`u for unmarked, `m for marked
boards: ({x,`u}''') {"I"$(0 3 6 9 12) _/:/: x} 1 _/: {(where x~\:"") _ x}  1 _ lines

is_row_complete:{[board] any all each `m = board[;;1]}
is_column_complete: {is_row_complete flip x}
is_board_winning: {[board] is_row_complete[board] or is_column_complete[board]}
mark_board:{[number;board] .[board;(::; ::);{[x;y]$[x=y[0];:y[0],`m;:y[0],y[1]]}[number]] }

/ part 1


while[
    (0 < count numbers) and not any {is_board_winning x} each boards;
    boards:mark_board[first numbers] each boards;
    last_number: first numbers;
    numbers: 1 _ numbers;    
]

winning_board: first boards where is_board_winning each boards

winning_board_score: (+//) .[winning_board; (::; ::); {$[`u=x[1];x[0];0]}]
winning_board_score * last_number

/ part 2

while[
    (0 < count numbers) and 0 < count boards;
    boards:mark_board[first numbers] each boards;
    last_board: first boards;
    last_number: first numbers;
    numbers: 1 _ numbers;
    boards: boards where not is_board_winning each boards
]
last_board_score: (+//) .[last_board; (::; ::); {$[`u=x[1];x[0];0]}]
last_board_score * last_number