use std::collections::HashMap; use std::env::args; use std::fs::File; use std::hash::Hash; use std::io::BufRead; use std::io::BufReader; fn load_data() -> Vec<[i32; 4]> { let path = args().nth(1).unwrap(); let file = File::open(path).unwrap(); let mut points: Vec<[i32; 4]> = vec![]; for line in BufReader::new(file).lines() { let l = line.unwrap(); let point: Vec = l .split(" -> ") .map(|pair| pair.split(",")) .flatten() .map(|s| s.parse::().unwrap()) .collect(); assert_eq!(point.len(), 4); points.push([point[0], point[1], point[2], point[3]]); } return points; } fn increment(map: &mut HashMap, key: T) { let i = match map.get(&key) { Some(v) => *v, None => 0, }; map.insert(key, i + 1); } fn step(a: i32, b: i32) -> i32 { if a < b { return 1; } else if a > b { return -1; } else { return 0; } } fn main() { let points = load_data(); let mut map = HashMap::new(); for point in points { let dx = step(point[0], point[2]); let dy = step(point[1], point[3]); let mut x = point[0]; let mut y = point[1]; increment(&mut map, (x, y)); while x != point[2] || y != point[3] { x += dx; y += dy; increment(&mut map, (x, y)); } } for y in 0..10 { for x in 0..10 { let c = match map.get(&(x, y)) { Some(c) => c.to_string(), None => ".".to_string(), }; print!("{}", c); } print!("\n"); } let n = map.values().filter(|k| **k >= 2).count(); print!("{}\n", n); }