Created
December 5, 2020 16:27
-
-
Save ThomasdenH/c6d73c820b0e68e6d0f41779943c44a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use aoc_runner_derive::aoc; | |
use std::convert::TryInto; | |
const TOTAL_SIZE: usize = 10; | |
const LINE_SIZE: usize = TOTAL_SIZE + 1; | |
struct Input<'a>(&'a [u8]); | |
impl<'a> Iterator for Input<'a> { | |
type Item = BinarySpacePartitioning; | |
fn next(&mut self) -> Option<BinarySpacePartitioning> { | |
if self.0.len() >= LINE_SIZE { | |
let res = Some(BinarySpacePartitioning( | |
self.0[..TOTAL_SIZE].try_into().unwrap(), | |
)); | |
self.0 = &self.0[LINE_SIZE..]; | |
res | |
} else if self.0.len() >= TOTAL_SIZE { | |
let res = Some(BinarySpacePartitioning( | |
self.0[..TOTAL_SIZE].try_into().unwrap(), | |
)); | |
self.0 = &[]; | |
res | |
} else { | |
None | |
} | |
} | |
} | |
struct BinarySpacePartitioning([u8; TOTAL_SIZE]); | |
impl BinarySpacePartitioning { | |
fn seat_id(&self) -> usize { | |
self.0 | |
.iter() | |
.zip((0..TOTAL_SIZE).rev().map(|i| 1 << i)) | |
.filter_map(|(&val, i)| Some(i).filter(|_| is_r_or_b(val))) | |
.fold(0, |acc, x| acc | x) | |
} | |
} | |
const MASK: u8 = 0b0000100; | |
fn is_r_or_b(u: u8) -> bool { | |
(u & MASK) == 0 | |
} | |
#[aoc(day5, part1)] | |
fn part_01(input: &[u8]) -> usize { | |
Input(input).map(|bsp| bsp.seat_id()).max().unwrap() | |
} | |
#[aoc(day5, part2)] | |
fn part_02(input: &[u8]) -> usize { | |
let (max, min, sum) = Input(input) | |
.map(|bsp| bsp.seat_id()) | |
.fold((0, usize::MAX, 0), |(acc_max, acc_min, acc_sum), id| { | |
(acc_max.max(id), acc_min.min(id), acc_sum + id) | |
}); | |
(min..=max).sum::<usize>() - sum | |
} | |
#[test] | |
fn test_mask() { | |
assert_eq!(increase_mask(b'B'), true); | |
assert_eq!(increase_mask(b'R'), true); | |
assert_eq!(increase_mask(b'F'), false); | |
assert_eq!(increase_mask(b'L'), false); | |
} | |
#[test] | |
fn test_seat_ids() { | |
assert_eq!(BinarySpacePartitioning(*b"BFFFBBFRRR").seat_id(), 567); | |
assert_eq!(BinarySpacePartitioning(*b"FFFBBBFRRR").seat_id(), 119); | |
assert_eq!(BinarySpacePartitioning(*b"BBFFBBFRLL").seat_id(), 820); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment