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) }