use std::cmp::{max, min}; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let reader = open_file(); let mut coords: HashMap<(i32, i32), i32> = HashMap::new(); for line in reader.lines() { if let Ok(line) = line { let vents = line.split(" -> ").collect::>(); let first = vents[0].split(",").collect::>(); let second = vents[1].split(",").collect::>(); let first: Vec = first.into_iter().map(|s| s.parse().unwrap()).collect(); let second: Vec = second.into_iter().map(|s| s.parse().unwrap()).collect(); let xstep: i32; let ystep: i32; let start_x = min(first[0], second[0]); let end_x = max(first[0], second[0]); let start_y = min(first[1], second[1]); let end_y = max(first[1], second[1]); let distance = max(end_x - start_x, end_y - start_y); if first[0] > second[0] { xstep = -1; } else if first[0] < second[0] { xstep = 1; } else { xstep = 0; } if first[1] > second[1] { ystep = -1; } else if first[1] < second[1] { ystep = 1; } else { ystep = 0; } for step in 0..=distance { let counter = coords .entry((first[0] + step * xstep, first[1] + step * ystep)) .or_insert(0); *counter += 1; } } } // println!("coords: {:?}", coords); // visualize(&coords); let result = coords.iter().filter(|(_, &y)| y >= 2).count(); println!("{}", result); } fn visualize(map: &HashMap<(i32, i32), i32>) { let start_x = map.iter().map(|((x, _), _)| x).min().unwrap(); let start_y = map.iter().map(|((_, y), _)| y).min().unwrap(); let end_x = map.iter().map(|((x, _), _)| x).max().unwrap(); let end_y = map.iter().map(|((_, y), _)| y).max().unwrap(); println!("start_x: {}", start_x); println!("start_y: {}", start_y); println!("end_x: {}", end_x); println!("end_y: {}", end_y); for y in *start_y..=*end_y { for x in *start_x..=*end_x { if let Some(val) = map.get(&(x, y)) { print!("{}", val); } else { print!(".") } } println!(""); } } 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) }