summaryrefslogtreecommitdiff
path: root/2018/src/bin/day_11.rs
blob: 0e458a3877310bf1c67484e97fa3b8c1353bd0a7 (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
60
61
62
63
64
65
66
extern crate advent_of_code_2018;
use advent_of_code_2018::*;

use std::error::Error;
use std::i32;

// cargo watch -cs "cargo run --release --bin day_11"

fn main() -> Result<(), Box<Error>> {
    let input = 1723;

    println!("Input: {:?}", input);

    let powers = precompute_powers(input);

    let power_per_size = (1..300).map(|size| {
        (1..302-size).map(|left| {
            (1..302-size).map(|top| {
                (power_for_block(left, top, size, &powers), (left, top, size))
            }).max_by_key(|(p, _)| *p).unwrap()
        }).max_by_key(|(p, _)| *p).unwrap()
    }).collect::<Vec<_>>();

    let (max_power_at_size_3, coordinate_at_size_3) = power_per_size[2]; // index from 0 vs 1
    debug!(max_power_at_size_3);
    debug!(coordinate_at_size_3);

    let (max_power, coordinate) = power_per_size.iter().max_by_key(|(p, _)| p).unwrap();
    
    debug!(max_power);
    debug!(coordinate);

    Ok(())
}

fn power_for_block(left: i32, top: i32, size: i32, powers: &[[i32;300];300]) -> i32 {
    (left..left+size).map(|x| {
        (top..top+size).map(|y| {
            powers[x as usize - 1][y as usize - 1]
        }).sum::<i32>()
    }).sum()
}

fn precompute_powers(input: i32) -> [[i32;300];300] {
    let mut powers: [[i32;300];300] = [[0;300];300];
    for x in 1..301 {
        for y in 1..301 {
            powers[x as usize - 1][y as usize - 1] = power_from_coordinates(x, y, input);
        }
    }
    powers
}

fn power_from_coordinates(x: i32, y: i32, input: i32) -> i32 {
    let rack_id = x + 10;
    ((((rack_id * y) + input) * rack_id / 100) % 10) - 5
}


#[test]
fn power_from_coord_example() {
    assert_eq!(power_from_coordinates(3, 5, 8), 4);
    assert_eq!(power_from_coordinates(122, 79, 57), -5);
    assert_eq!(power_from_coordinates(217,196, 39), 0);
    assert_eq!(power_from_coordinates(101, 153, 71), 4);
}