summaryrefslogtreecommitdiff
path: root/2018/src/day11.rs
blob: 0be5e6183b44d7f5749cd93c25db84ad8b1d551b (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use std::io;
use std::io::BufRead;

fn power(x: i32, y: i32, serial: i32) -> i32 {
    (y * (x + 10) + serial) * (x + 10) / 100 % 10 - 5
}

pub fn main<T: BufRead>(reader: T) -> io::Result<(String, String)> {
    let serial = reader.lines().next().unwrap().unwrap().parse::<i32>().unwrap();

    let grid = {
        let mut grid = [[0; 300]; 300];
        for y in 0..300 {
            for x in 0..300 {
                grid[y][x] = power(x as i32, y as i32, serial);
            }
        }
        grid
    };

    let mut maxval = i32::min_value();
    let mut maxat = (0, 0, 0);
    let mut maxval3 = i32::min_value();
    let mut maxat3 = (0, 0);

    let mut prevs = [[0; 300]; 300];
    let mut prevs_h = [[0; 300]; 300];
    let mut prevs_v = [[0; 300]; 300];

    for s in 1..301 {
        for y in 0..301-s {
            for x in 0..301-s {
                let lt = prevs[y][x];
                let right = prevs_v[y][x+s-1];
                let bottom = prevs_h[y+s-1][x];
                let rb = grid[y+s-1][x+s-1];
                let tot = lt + right + bottom + rb;

                if tot > maxval {
                    maxval = tot;
                    maxat = (x, y, s);
                }
                if s == 3 && tot > maxval3 {
                    maxval3 = tot;
                    maxat3 = (x, y);
                }

                prevs[y][x] = tot;
                prevs_h[y+s-1][x] = bottom + rb;
                prevs_v[y][x+s-1] = right + rb;
            }
        }
    }

    let part1 = format!("{},{}", maxat3.0, maxat3.1);
    let part2 = format!("{},{},{}", maxat.0, maxat.1, maxat.2);

    Ok((part1, part2))
}