Add day 3 part 2 solution

This commit is contained in:
Wesley Moore 2017-12-24 16:36:08 +11:00
parent 67dcde80c5
commit be7a6b76b3
2 changed files with 77 additions and 0 deletions

View file

@ -33,3 +33,24 @@ Your puzzle input is 289326.
42 21 22 23 24 25 26
43 44 45 46 47 48 49
--- Part Two ---
As a stress test on the system, the programs here clear the grid and then store the value 1 in square 1. Then, in the same allocation order as shown above, they store the sum of the values in all adjacent squares, including diagonals.
So, the first few squares' values are chosen as follows:
Square 1 starts with the value 1.
Square 2 has only one adjacent filled square (with value 1), so it also stores 1.
Square 3 has both of the above squares as neighbors and stores the sum of their values, 2.
Square 4 has all three of the aforementioned squares as neighbors and stores the sum of their values, 4.
Square 5 only has the first and fourth squares as neighbors, so it gets the value 5.
Once a square is written, its value does not change. Therefore, the first few squares would receive the following values:
147 142 133 122 59
304 5 4 2 57
330 10 1 1 54
351 11 23 25 26
362 747 806---> ...
What is the first value written that is larger than your puzzle input?

View file

@ -1,5 +1,8 @@
use std::collections::HashMap;
fn main() {
println!("{}", manhattan_distance(289326));
println!("{}", stress_test(289326));
}
fn spiral_to(index: usize) -> (isize, isize) {
@ -27,7 +30,55 @@ fn spiral_to(index: usize) -> (isize, isize) {
edge += 1;
delta *= -1;
}
}
fn sum_neighbors(x: isize, y: isize, data: &HashMap<(isize, isize), usize>) -> usize {
let mut sum = 0;
for dx in -1..2 {
for dy in -1..2 {
if dx == 0 && dy == 0 { continue }
if let Some(value) = data.get(&(x + dx, y + dy)) {
sum += value;
}
}
}
sum
}
fn stress_test(input: usize) -> usize {
if input == 1 { return 2 }
let mut data = HashMap::new();
data.insert((0, 0), 1);
let mut x = 0isize;
let mut y = 0isize;
let mut edge = 1;
let mut delta = 1isize;
loop {
// Horizontal
for _i in 0..edge {
x += delta;
let value = sum_neighbors(x, y, &data);
if value > input { return value }
data.insert((x, y), value);
}
// Vertical
for _i in 0..edge {
y += delta;
let value = sum_neighbors(x, y, &data);
if value > input { return value }
data.insert((x, y), value);
}
edge += 1;
delta *= -1;
}
}
fn manhattan_distance(index: usize) -> usize {
@ -103,3 +154,8 @@ fn test_example11() {
fn test_example12() {
assert_eq!(manhattan_distance(37), 6);
}
#[test]
fn test_example1_part2() {
assert_eq!(stress_test(23), 25);
}