summaryrefslogtreecommitdiff
path: root/11/src/part-2.rs
blob: e79e3bface8af521bf37399ddb03c3b02ec0d280 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
mod stuff;

use crate::stuff::{is_galaxy, read_helper, cumulative_sum_expansion, distance, Position};


fn main() {
    let mut stdin = std::io::stdin().lock();

    let mut buf: Vec<u8> = Vec::new();

    let mut galaxies: Vec<Position> = Vec::new();
    
    let num_bytes = read_helper(&mut stdin, &mut buf, b'\n').expect("IO error");
    if num_bytes == 0 { panic!("Malformed input"); }
    let mut col_empty_mask: Vec<bool> = Vec::from_iter(std::iter::repeat(true).take(buf.len()));
    let mut row_empty_mask: Vec<bool> = Vec::new();
    loop {
        let mut row_empty: bool = true;
        let i = row_empty_mask.len();
        for (j, & c) in (& buf).into_iter().enumerate() {
            if is_galaxy(c) {
                col_empty_mask[j] = false;
                row_empty = false;
                galaxies.push([i, j]);
            }
        }
        row_empty_mask.push(row_empty);

        let num_bytes = read_helper(&mut stdin, &mut buf, b'\n').expect("IO error");
        if num_bytes == 0 { break; }
    }

    let cumulative_row_sum: Vec<usize> = cumulative_sum_expansion(& row_empty_mask, 1_000_000);
    let cumulative_col_sum: Vec<usize> = cumulative_sum_expansion(& col_empty_mask, 1_000_000);

    let mut res: usize = 0;
    for (i, pos_1) in (& galaxies).into_iter().enumerate() {
        for (_, pos_2) in (& galaxies).into_iter().enumerate().skip(i) {
            res += distance(& cumulative_row_sum, & cumulative_col_sum, pos_1, pos_2);
        }
    }

    println!("{}", res);
}