mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Implementation day 5
This commit is contained in:
54
2020/src/day05.rs
Normal file
54
2020/src/day05.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::Read;
|
||||
|
||||
use crate::Solution;
|
||||
|
||||
fn seat_id(boarding_pass: &str) -> u32 {
|
||||
boarding_pass
|
||||
.chars()
|
||||
.fold(0, |b, c| (b << 1) | ((c == 'B' || c == 'R') as u32))
|
||||
}
|
||||
|
||||
fn seat_iter<'a>(input: &'a mut dyn Read) -> impl Iterator<Item = u32> + 'a {
|
||||
BufReader::new(input).lines().map(|s| seat_id(&s.unwrap()))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Day05;
|
||||
|
||||
impl Solution for Day05 {
|
||||
fn part1(&mut self, input: &mut dyn Read) -> String {
|
||||
seat_iter(input).max().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn part2(&mut self, input: &mut dyn Read) -> String {
|
||||
let mut taken = [false; 0x3ff];
|
||||
|
||||
for seat_id in seat_iter(input) {
|
||||
taken[seat_id as usize] = true;
|
||||
}
|
||||
|
||||
let pattern = [true, false, true];
|
||||
|
||||
for (i, window) in taken.windows(3).enumerate() {
|
||||
if window == pattern {
|
||||
return (i + 1).to_string();
|
||||
}
|
||||
}
|
||||
|
||||
panic!("No seat found!");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_seat_id() {
|
||||
assert_eq!(567, seat_id("BFFFBBFRRR"));
|
||||
assert_eq!(119, seat_id("FFFBBBFRRR"));
|
||||
assert_eq!(820, seat_id("BBFFBBFRLL"));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ mod day01;
|
||||
mod day02;
|
||||
mod day03;
|
||||
mod day04;
|
||||
mod day05;
|
||||
|
||||
pub trait Solution {
|
||||
fn part1(&mut self, input: &mut dyn Read) -> String;
|
||||
@@ -20,6 +21,7 @@ pub fn get_implementation(day: usize) -> Box<dyn Solution> {
|
||||
2 => Box::new(day02::Day02::default()),
|
||||
3 => Box::new(day03::Day03::default()),
|
||||
4 => Box::new(day04::Day04::default()),
|
||||
5 => Box::new(day05::Day05::default()),
|
||||
_ => panic!("Unsupported day {}", day),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user