From 3919f90cfbfbba26c8e39f979280649f5e08aea8 Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Fri, 10 Dec 2021 19:54:14 +0300 Subject: 2021, day4: done, please don't look at this --- 2021/day4/src/main.rs | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 2021/day4/src/main.rs (limited to '2021/day4/src/main.rs') diff --git a/2021/day4/src/main.rs b/2021/day4/src/main.rs new file mode 100644 index 0000000..4b6150f --- /dev/null +++ b/2021/day4/src/main.rs @@ -0,0 +1,99 @@ +use std::env; +use std::fs::File; +use std::io::{BufRead, BufReader}; + +fn main() { + let args: Vec = env::args().collect(); + + if args.len() != 2 { + eprintln!("Usage: {} filename", args[0]); + std::process::exit(1); + } + + let filename = &args[1]; + + let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename)); + let reader = BufReader::new(file); + + let mut fd = reader.lines(); + let mut called_numbers: Vec = Vec::new(); + + if let Ok(called_nums) = fd.next().unwrap() { + called_numbers = called_nums.split(",").map(|x| x.parse().unwrap()).collect(); + } + + fd.next(); /* Skip the empty line */ + + let mut boards: Vec<(Vec<(i32, bool)>, bool)> = Vec::new(); + + 'outer: loop { + let mut miniboard: Vec<(i32, bool)> = Vec::new(); + for _ in 0..5 { + /* New Board */ + if let Some(maybe_line) = fd.next() { + if let Ok(line) = maybe_line { + for (a, b) in line + .split_whitespace() + .map(|x| x.parse().unwrap()) + .zip([false].iter().cycle()) + { + miniboard.push((a, *b)); + } + } + } else { + break 'outer; + } + } + boards.push((miniboard.clone(), false)); + fd.next(); /* Skip the empty line */ + } + + for bingo in called_numbers { + for (board, _) in boards.iter_mut() { + for (num, mark) in board.iter_mut() { + if *num == bingo { + *mark = true; + } + } + } + + let mut count; + for (board, won) in boards.iter_mut() { + for row in 0..5 { + count = 0; + for i in row * 5..(row * 5) + 5 { + if board[i].1 { + count += 1; + } + } + if count == 5 { + *won = true; + } + } + + for column in 0..5 { + count = 0; + for i in (0..5).map(|x| 5 * x + column) { + if board[i].1 { + count += 1; + } + } + if count == 5 { + *won = true; + } + } + } + if boards.len() == 1 { + let mut score: i32 = 0; + if let Some(board) = boards.get(0) { + for (winnynum, marked) in board.0.iter() { + if !marked { + score += winnynum; + } + } + println!("score: {}", score * bingo); + } + } + boards.retain(|x| !x.1); + } +} -- cgit v1.2.3-70-g09d2