From ca60384d831d1208227b3538ca121ebc4624b0f2 Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Mon, 20 Dec 2021 16:56:51 +0300 Subject: 2021, day10: done --- 2021/day10/src/main.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 2021/day10/src/main.rs (limited to '2021/day10/src/main.rs') diff --git a/2021/day10/src/main.rs b/2021/day10/src/main.rs new file mode 100644 index 0000000..dcb44a8 --- /dev/null +++ b/2021/day10/src/main.rs @@ -0,0 +1,65 @@ +use std::collections::HashMap; +use std::env; +use std::fs::File; +use std::io::{BufRead, BufReader}; + +fn main() { + let reader = open_file(); + let points = HashMap::from([(')', 3), (']', 57), ('}', 1197), ('>', 25137)]); + let comp_points = HashMap::from([(')', 1), (']', 2), ('}', 3), ('>', 4)]); + let pairs = HashMap::from([('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')]); + let opening = vec!['(', '[', '{', '<']; + let closing = vec![')', ']', '}', '>']; + let mut final_scores = Vec::new(); + + let mut score = 0; + + for line in reader.lines() { + let mut stack: Vec = Vec::new(); + let mut flag = false; + if let Ok(ln) = line { + for char in ln.chars() { + if opening.contains(&char) { + stack.push(char); + } else if closing.contains(&char) { + let t = stack.pop().unwrap(); + if char == *pairs.get(&t).unwrap() { + } else { + score += points.get(&char).unwrap(); + flag = true; + break; + } + } + } + if !flag { + let mut score: u64 = 0; + stack.reverse(); + for c in &stack { + score *= 5; + score += comp_points.get(pairs.get(c).unwrap()).unwrap(); + } + final_scores.push(score); + } + } + } + + final_scores.sort_unstable(); + let idx = final_scores.len() / 2; + + println!("part 1: {}", score); + println!("part 2: {}", final_scores[idx]); +} + +fn open_file() -> BufReader { + let args: Vec = env::args().collect(); + + if args.len() != 2 { + eprintln!("Usage: {} ", args[0]); + std::process::exit(1); + } + + let filename = &args[1]; + + let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename)); + BufReader::new(file) +} -- cgit v1.2.3-70-g09d2