diff options
author | Santo Cariotti <santo@dcariotti.me> | 2021-12-08 14:33:45 +0100 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2021-12-08 14:33:45 +0100 |
commit | 888fe73d71bee5d2f23c09522bce090fcd77e976 (patch) | |
tree | 07fab98dfd5d94a924c073a8b8c30181bfa451fe /day4/src | |
parent | 55138770a6057e854ed8d7ae999433ab08d264d7 (diff) |
Add day4
Diffstat (limited to 'day4/src')
-rw-r--r-- | day4/src/main.rs | 103 |
1 files changed, 103 insertions, 0 deletions
diff --git a/day4/src/main.rs b/day4/src/main.rs new file mode 100644 index 0000000..aed66ec --- /dev/null +++ b/day4/src/main.rs @@ -0,0 +1,103 @@ +use std::fs::File; +use std::io::{BufRead, BufReader}; + +fn main() -> std::io::Result<()> { + let file = File::open("input.txt")?; + let reader = BufReader::new(file); + let mut lines = reader.lines(); + + let mut inputs: Vec<_> = lines + .next() + .unwrap() + .unwrap() + .trim() + .split(',') + .map(|x| x.parse::<u32>().unwrap()) + .collect::<Vec<u32>>(); + + let mut grids: Vec<Vec<u32>> = vec![]; + let mut n: usize = 0; + + lines.next(); // Ignore the first empty line + while let Some(line) = lines.next() { + let mut line = line.unwrap(); + grids.push(Vec::with_capacity(5 * 5)); + + for _ in 0..5 { + grids[n].extend( + line.trim() + .split(' ') + .filter(|x| !x.is_empty()) + .map(|x| x.parse::<u32>().unwrap()) + .collect::<Vec<u32>>(), + ); + line = match lines.next() { + Some(x) => x.unwrap(), + None => "".to_string(), + }; + } + n += 1; + } + + let mut values = Vec::<u32>::new(); + + for _ in 0..4 { + values.push(inputs.remove(0)); + } + + let mut winner: i8 = -1; + for input in inputs { + if winner >= 0 { + break; + } + values.push(input); + for i in 0..grids.len() { + // Search by rows + for j in [0, 5, 10, 15, 20] { + let mut n = 0; + for k in 0..5 { + let x = grids[i][j + k]; + if values.iter().any(|&i| i == x) { + n += 1; + } + } + if n == 5 { + winner = i as i8; + } + } + + // Search by cols + if winner >= 0 { + for j in 0..5 { + let mut n = 0; + for k in [0, 5, 10, 15, 20] { + let x = grids[i][j + k]; + if values.iter().any(|&i| i == x) { + n += 1; + } + } + if n == 5 { + winner = i as i8; + } + } + } + + if winner >= 0 { + break; + } + } + } + + let mut sum = 0; + for x in &grids[winner as usize] { + if values.iter().any(|&i| i == *x) { + continue; + } + + sum += x; + } + + println!("{}", sum * values.pop().unwrap()); + + Ok(()) +} |