, -1), 0) | ((-1, 0), 1) => (-1, 0),
((0, 1), 1) | ((1, 0), 2) | ((0, -1), 3) | ((-1, 0), 0) => (0, 1),
((0, 1), 3) | ((1, 0), 0) | ((0, -1), 1) | ((-1, 0), 2) => (0, -1),
_ => panic!(“invalid direction or angle!”),
}
impl Day11 {
fn print_map(grid: &HashMap<(i64, i64), bool>) {
let min_x = grid.keys().min_by_key(|x| x.0).unwrap().0;
let min_y = grid.keys().min_by_key(|x| x.1).unwrap().1;
let max_x = grid.keys().max_by_key(|x| x.0).unwrap().0;
let max_y = grid.keys().max_by_key(|x| x.1).unwrap().1;
for y in min_y..=max_y {
for x in min_x..=max_x {
let value = *grid.get(&(x, y)).unwrap_or(&false);
print!(
“{}”,
if value {
‘X’
} else {
‘ ‘
}
);
}
println!();
}
}
fn run.program(
&mut self,
start_color: bool,
print: bool,
) -> HashMap<(i64, i64), bool> {
let mut current_pos = (0, 0);
let mut current_direction = (0, 1);
let mut painted_squares = HashSet::new();
let mut grid = HashMap::new();
grid.insert(current_pos, start_color);
let mut idx: usize = 0;
let mut computer = IntComputer::new(self.program.to_vec());
while computer.status() != Status::Halted {
computer.run_program_for_output(Some(idx));
let new_color = computer.last_output() == 1;
if !painted_squares.contains(¤t_pos) {
painted_squares.insert(current_pos);
}
grid.insert(current_pos, new_color);
let angle = computer.last_output();
current_direction = get_dir(current_direction, angle);
let dx = current_direction.0;
let dy = current_direction.1;
current_pos.0 += dx;
current_pos.1 += dy;
idx = match grid.get(¤t_pos) {
Some(value) => {
if *value {
1
} else {
0
}
}
None => 0,
};
if print {
println!(“{:?}”, grid);
Self::print_map(&grid);
std::thread::sleep(std::time::Duration::from_millis(200));
clear_terminal();
}
}
grid
}
impl Challenge for Day11 {
fn part_1(&mut self) -> i32 {
let mut grid = self.run.program(false, false);
grid.keys().len() as i32
}
fn part_2(&mut self) -> i32 {
let mut grid = self.run.program(true, false);
let min_x = grid.keys().min_by_key(|x| x.0).unwrap().0;
let min_y = grid.keys().min_by_key(|x| x.1).unwrap().1;
let max_x = grid.keys().max_by_key(|x| x.0).unwrap().0;
let max_y = grid.keys().max_by_key(|x| x.1).unwrap().1;
println!(
“min_x: {}, max_x: {}, min_y: {}, max_y: {}”,
min_x, max_x, min_y, max_y
);
for y in min_y..=max_y {
for x in (min_x..=max_x).rev() {
let value = *grid.get(&(x, y)).unwrap_or(&false);
print!(
“{}”,
if value {
‘X’
} else {
‘ ‘
}
);
}
println!();
}
42
}
#[allow(dead_code)]
fn solve() {
let mut day = Day11::new();
print_results(&day);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_part1() {
let mut d = Day11::new();
assert_eq!(d.part_1(), 1972);
}
#[test]
fn run_part2() {
let mut d = Day11::new();
assert_eq!(d.part_2(), 42);
}
fn clear_terminal() {
print!(“{}[2J”, 27 as char);
std::io::stdout()
.flush()
.expect(“Failed to write to stdout”);