day19 part 2

This commit is contained in:
2022-10-01 22:43:37 +02:00
parent 3992bf2e58
commit 3c72884fac

View File

@@ -1,24 +1,75 @@
use std::collections::HashMap;
use super::day05::{IntCodeComputer, RAM}; use super::day05::{IntCodeComputer, RAM};
use itertools::Itertools; use itertools::Itertools;
pub fn run() { pub fn run() {
let program = super::day05::load_ram("input/day19.txt"); let program = super::day05::load_ram("input/day19.txt");
part1(program, 50); //part1(&program, 50);
part2(&program); // 8151016 too high
} }
fn part1(program: RAM, max: i128) { fn part1(program: &RAM, max: i128) {
let result = (0..max) let result = (0..max)
.flat_map(|x| { .flat_map(|x| {
(0..max) (0..max)
.map(|y| { .map(|y| {
let mut computer = IntCodeComputer::new(vec![x, y], program.clone()); read_coordinate(program, x, y)
computer.run_until_end();
*computer.get_output().first().unwrap()
}) })
.collect_vec() .collect_vec()
}) })
.filter(|v| *v == 1) .filter(|v| *v)
.count(); .count();
println!("{result}"); println!("{result}");
} }
const W: i128 = 100;
const MAX_PERIMETER: i128 = 1_000_000_000;
fn part2(program: &RAM) {
let mut map: HashMap<(i128, i128), bool> = HashMap::new();
(0..W)
.for_each(|x| {
(0..W)
.for_each(|y| {
map.insert((x, y), read_coordinate(program, x, y));
})
});
for starts in 0..=MAX_PERIMETER {
println!("checking perimeter {starts}");
extend_horizon(program, &mut map, starts);
check_all_squares_at(&map, starts);
}
}
fn check_all_squares_at(map: &HashMap<(i128, i128), bool>, starts: i128) {
(0..=starts).for_each(|i| {
check_fits(map, i, starts);
check_fits(map, starts, i);
});
}
fn check_fits(map: &HashMap<(i128, i128), bool>, x: i128, y: i128) {
let ul = map[&(x, y)];
let ur = map[&(x + W - 1, y)];
let ll = map[&(x, y + W - 1)];
let lr = map[&(x + W, y + W - 1)];
if ul && ur && ll && lr {
let result = x * 10_000 + y;
panic!("found it! starts at {x},{y} -> {}", result);
}
}
fn extend_horizon(program: &RAM, map: &mut HashMap<(i128, i128), bool>, starts: i128) {
(0..=W + starts).for_each(|i| {
let j = W + starts;
map.insert((j, i), read_coordinate(program, j, i));
map.insert((i, j), read_coordinate(program, i, j));
});
}
fn read_coordinate(program: &RAM, x: i128, y: i128) -> bool {
let mut computer = IntCodeComputer::new(vec![x, y], program.clone());
computer.run_until_end();
*computer.get_output().first().unwrap() == 1
}