70 lines
1.7 KiB
Rust
70 lines
1.7 KiB
Rust
use std::error::Error;
|
|
use std::fs::File;
|
|
use std::io::{self, BufRead};
|
|
use std::vec::Vec;
|
|
|
|
fn upper_half(half: (u32, u32)) -> (u32, u32) {
|
|
let (low, high) = half;
|
|
|
|
if low == high {
|
|
(low, high)
|
|
} else if high - low == 1 {
|
|
(high, high)
|
|
} else {
|
|
(low + (high - low) / 2 + high % 2, high)
|
|
}
|
|
}
|
|
|
|
fn lower_half(half: (u32, u32)) -> (u32, u32) {
|
|
let (low, high) = half;
|
|
|
|
if low == high {
|
|
(low, high)
|
|
} else if high - low == 1 {
|
|
(low, low)
|
|
} else {
|
|
(low, high - (high - low) / 2 - high % 2)
|
|
}
|
|
}
|
|
|
|
fn partition(rows: (u32, u32), cols: (u32, u32), location: &str) -> ((u32, u32), (u32, u32)) {
|
|
if location == "" {
|
|
return (rows, cols);
|
|
}
|
|
|
|
let head = location.chars().nth(0).unwrap();
|
|
let tail = &location[1..];
|
|
|
|
match head {
|
|
'F' => partition(lower_half(rows), cols, tail),
|
|
'B' => partition(upper_half(rows), cols, tail),
|
|
'L' => partition(rows, lower_half(cols), tail),
|
|
'R' => partition(rows, upper_half(cols), tail),
|
|
_ => panic!("Unkown location part: {}", head),
|
|
}
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let file = File::open("inputs/day5.txt")?;
|
|
let lines = io::BufReader::new(file).lines().map(|l| l.unwrap());
|
|
|
|
let mut seat_ids: Vec<u32> = lines
|
|
.map(|loc| partition((0, 127), (0, 7), &loc))
|
|
.map(|((r, _), (c, _))| r * 8 + c)
|
|
.collect();
|
|
|
|
seat_ids.sort();
|
|
let max = seat_ids.iter().last().unwrap();
|
|
|
|
println!("MaxID: {}", max);
|
|
|
|
for pair in seat_ids.windows(2) {
|
|
if pair[1] != pair[0] + 1 {
|
|
println!("Missing ID: {}", pair[0] + 1);
|
|
break;
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|