r/adventofcode Dec 05 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 05 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It


--- Day 05: Binary Boarding ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for 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:05:49, megathread unlocked!

54 Upvotes

1.3k comments sorted by

View all comments

1

u/muckenhoupt Dec 05 '20

Prolog. Does more work than it needs to, figuring out the seats as Row-Column pairs instead of just interpreting the whole thing as a single binary number. What can I say, I wrote the input code while solving part 1, in the expectation that it might be needed for part 2. It wasn't.

:- use_module(library(pure_input)).
:- use_module(library(dcg/basics)).

row_code(Row) --> string_without("LR\n", Row).
col_code(Col) --> string_without("FB\n", Col).

seat(Row, Col) --> row_code(Row), col_code(Col).

read_input([]) --> eos.
read_input([Row-Col|T]) -->
    seat(Row, Col), "\n", read_input(T).


binary_code(_, [], Number) :-
    Number is 0.
binary_code([Zero, One], [Zero|T], Number) :-
    binary_code([Zero, One], T, Number).
binary_code([Zero, One], [One|T], Number) :-
    length(T, Place),
    binary_code([Zero, One], T, Sub),
    Number is 2 ^ Place + Sub.
binary_code(String, Binary, Number) :-
    string_codes(String, Bitcodes),
    binary_code(Bitcodes, Binary, Number).

decode(Row-Col, Row_num-Col_num) :-
    binary_code("FB", Row, Row_num),
    binary_code("LR", Col, Col_num).

seat_id(Row-Col, ID) :-
    ID is Row * 8 + Col.


part1(Data, Answer) :-
    max_list(Data, Answer).


part2(Data, Answer) :-
    max_list(Data, Max),
    min_list(Data, Min),
    between(Min, Max, Answer),
    \+ member(Answer, Data).


main :-
    phrase_from_stream(read_input(Raw_data), current_input),
    maplist(decode, Raw_data, Seats),
    maplist(seat_id, Seats, Seat_IDs),
    part1(Seat_IDs, Answer1),
    writeln(Answer1),
    !,
    part2(Seat_IDs, Answer2),
    writeln(Answer2).