day11 task 2

This commit is contained in:
Johannes
2019-12-12 11:40:05 +01:00
parent 009d1b8f86
commit 8849191a6b

View File

@@ -10,6 +10,7 @@ pub fn run() {
.map(|(i, s)| (i, s.parse::<i128>().unwrap())) .map(|(i, s)| (i, s.parse::<i128>().unwrap()))
.collect(); .collect();
task1(ram.clone()); task1(ram.clone());
task2(ram.clone());
} }
fn task1(ram: RAM) { fn task1(ram: RAM) {
@@ -52,3 +53,54 @@ fn task1(ram: RAM) {
} }
println!("Task 1: {} positions were painted", painted_positions.len()); println!("Task 1: {} positions were painted", painted_positions.len());
} }
fn task2(ram: RAM) {
let directions: HashMap<_, _> =
vec![('^', (0, -1)), ('v', (0, 1)), ('<', (-1, 0)), ('>', (1, 0))]
.into_iter()
.collect();
let turns: HashMap<_, _> = vec![
(('^', 0), '<'),
(('^', 1), '>'),
(('v', 0), '>'),
(('v', 1), '<'),
(('<', 0), 'v'),
(('<', 1), '^'),
(('>', 0), '^'),
(('>', 1), 'v'),
]
.into_iter()
.collect();
let mut colors: HashMap<(i32, i32), i128> = HashMap::new();
colors.insert((0, 0), 1);
let mut painted_positions: HashSet<(i32, i32)> = HashSet::new();
let get = |colors: &HashMap<_, _>, (x, y)| **colors.get(&(x, y)).get_or_insert(&0);
let turn = |(c, d)| turns.get(&(c, d)).unwrap();
let mov = |(x0, y0), (x1, y1)| (x0 + x1, y0 + y1);
let mut done = false;
let mut computer = IntCodeComputer::new(vec![], ram);
let mut pos = (0, 0);
let mut dir = '^';
while !done {
computer.set_input(&[get(&colors, pos)]);
computer.clear_output();
done = computer.run_until_input_empty();
let color = computer.get_output()[0];
let turn_indicator = computer.get_output()[1];
colors.insert(pos, color);
painted_positions.insert(pos);
dir = *turn((dir, turn_indicator));
pos = mov(pos, *directions.get(&dir).unwrap());
}
let xmin = painted_positions.iter().min_by_key(|it| it.0).unwrap().0;
let xmax = painted_positions.iter().max_by_key(|it| it.0).unwrap().0;
let ymin = painted_positions.iter().min_by_key(|it| it.1).unwrap().1;
let ymax = painted_positions.iter().max_by_key(|it| it.1).unwrap().1;
(ymin..=ymax).into_iter().for_each(|y| {
(xmin..=xmax).into_iter().for_each(|x| {
print!("{}", if get(&colors, (x, y)) == 1 { '#' } else { ' ' });
});
println!("")
})
}