diff options
Diffstat (limited to '05/src/part-2.rs')
-rw-r--r-- | 05/src/part-2.rs | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/05/src/part-2.rs b/05/src/part-2.rs new file mode 100644 index 0000000..0a742c9 --- /dev/null +++ b/05/src/part-2.rs @@ -0,0 +1,74 @@ +use std::cmp::{max, min}; +use std::collections::{HashMap}; +use std::io::{BufRead}; + +fn parse(s: & str) -> [u64; 4] { + let mut halves = s.split(" -> "); + let half_1 = halves.next().unwrap().split(','); + let half_2 = halves.next().unwrap().split(','); + let mut it = half_1.chain(half_2); + + let mut ret: [u64; 4] = [0; 4]; + ret[0] = it.next().expect("Malformed input").parse().expect("Malformed input"); + ret[1] = it.next().expect("Malformed input").parse().expect("Malformed input"); + ret[2] = it.next().expect("Malformed input").parse().expect("Malformed input"); + ret[3] = it.next().expect("Malformed input").parse().expect("Malformed input"); + + ret +} + +fn print_small_diagram(coverage: & HashMap<(u64, u64), u64>) { + for y in 0..20 { + for x in 0..20 { + let &n = coverage.get(&(x, y)).unwrap_or(&0); + if n == 0 { print!("."); } + else { print!("{}", n); } + } + println!(""); + } +} + +pub fn main() { + let mut stdin = std::io::stdin(); + let mut handle = stdin.lock(); + + let mut coverage: HashMap<(u64, u64), u64> = HashMap::new(); + + for l in handle.lines() { + let line = parse(& l.unwrap()); + + let (dx, dy) = (max(line[2], line[0]) - min(line[2], line[0]), max(line[3], line[1]) - min(line[3], line[1])); + + if dx == 0 { // Vertical + let x = line[0]; + let start_y = min(line[1], line[3]); + let stop_y = max(line[1], line[3]); + for y in start_y..stop_y+1 { + let &n = coverage.get(&(x, y)).unwrap_or(&0); + coverage.insert((x, y), n + 1); + } + } + else if dy == 0 { // Horizonal + let y = line[1]; + let start_x = min(line[0], line[2]); + let stop_x = max(line[0], line[2]); + for x in start_x..stop_x+1 { + let &n = coverage.get(&(x, y)).unwrap_or(&0); + coverage.insert((x, y), n + 1); + } + } + else if dx == dy { // Diagonal + let start_x = line[0]; + let start_y = line[1]; + for d in 0..dx+1 { + let x = if line[0] <= line[2] { start_x + d } else { start_x - d }; + let y = if line[1] <= line[3] { start_y + d } else { start_y - d }; + let &n = coverage.get(&(x, y)).unwrap_or(&0); + coverage.insert((x, y), n + 1); + } + } + } + + let n: usize = coverage.into_iter().map(|(k, v)| v).filter(|&count| count >= 2).count(); + println!("{}", n); +} |