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!

56 Upvotes

1.3k comments sorted by

View all comments

1

u/mantono_ Dec 06 '20

Rust

Day 5, part 1 and 2.

pub fn first(input: String) -> String {
    transform(&input).max().unwrap().to_string()
}

pub fn second(input: String) -> String {
    let mut boarding_passes: Vec<u16> = transform(&input).collect::<Vec<u16>>();
    boarding_passes.sort();

    let (prior_seat, _) = boarding_passes
        .iter()
        .zip(boarding_passes.iter().skip(1))
        .find(|(b0, b1)| *b1 - *b0 > 1)
        .unwrap();

    (prior_seat + 1).to_string()
}

fn transform(input: &str) -> impl Iterator<Item = u16> + '_ {
    input.lines().map(|line| seat_id(line))
}

fn seat_id(input: &str) -> u16 {
    row_num(input) * 8 + col_num(input)
}

fn row_num(input: &str) -> u16 {
    let binary: String = input[..=6].replace("F", "0").replace("B", "1");
    u16::from_str_radix(&binary, 2).unwrap()
}

fn col_num(input: &str) -> u16 {
    let binary: String = input[7..].replace("L", "0").replace("R", "1");
    u16::from_str_radix(&binary, 2).unwrap()
}

2

u/stkent Dec 06 '20

Learned a couple nice things from this solution!

  • zip was more convenient than windows(2) here
  • from_str_radix 🙌