Skip to content

Instantly share code, notes, and snippets.

@JCBurnside
Created December 5, 2020 17:47
Show Gist options
  • Save JCBurnside/ce87142370035c6255d4506c6b25210c to your computer and use it in GitHub Desktop.
Save JCBurnside/ce87142370035c6255d4506c6b25210c to your computer and use it in GitHub Desktop.
aoc2020 day5
use itertools::Itertools;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn map_to_bool_array(s: &str) -> [bool; 10] {
let mut output = [false; 10];
for (i, c) in s.chars().enumerate() {
output[i] = match c {
'B' | 'R' => true,
_ => false,
}
}
output
}
fn bool_to_int(b: bool) -> u32 {
match b {
true => 1,
false => 0,
}
}
fn map_bool_array_to_u32(arr: [bool; 10]) -> u32 {
arr.iter()
.rev()
.enumerate()
.fold(0, |sum, (i, d)| sum + (bool_to_int(*d) << i))
}
fn part1(data: &[String]) -> u32 {
let seats: Vec<u32> = data
.iter()
.map(|s| map_to_bool_array(s.as_str()))
.map(map_bool_array_to_u32)
.collect();
*seats.iter().max().unwrap()
}
fn part2(data: &[String]) -> u32 {
let mut seats: Vec<u32> = data
.iter()
.map(String::as_str)
.map(map_to_bool_array)
.map(map_bool_array_to_u32)
.collect();
seats.sort();
let my_seat = seats
.iter()
.tuple_windows()
.filter(|(x, y)| *y - *x > 1)
.collect_vec();
my_seat.first().unwrap().0 + 1
}
fn main() -> anyhow::Result<()> {
let data: Vec<String> = BufReader::new(File::open("Data.txt")?)
.lines()
.map(Result::unwrap)
.collect();
println!("Highest ID is {}", part1(&data));
println!("My id is {}", part2(&data));
Ok(())
}
#[cfg(test)]
mod tests {
use crate::map_bool_array_to_u32;
use super::map_to_bool_array;
use test_case::test_case;
#[test_case("BFFFBBFRRR", 567u32;"EXAMPLE 1")]
#[test_case("FFFBBBFRRR", 119u32;"EXAMPLE 2")]
#[test_case("BBFFBBFRLL", 820u32;"EXAMPLE 3")]
fn test_p1(s: &str, expected_id: u32) {
let seat = map_to_bool_array(s);
let seat = map_bool_array_to_u32(seat);
assert_eq!(expected_id, seat);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment