From: Grégory Burri Date: Thu, 12 Dec 2019 07:34:23 +0000 (+0100) Subject: A cleaner solution for day 10 X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=cc6ee64cafb39df422d3db44a3b57b453d68e319;p=advent_of_code_2019.git A cleaner solution for day 10 --- diff --git a/src/day10.rs b/src/day10.rs index 6b0af5b..c22ddba 100644 --- a/src/day10.rs +++ b/src/day10.rs @@ -55,23 +55,19 @@ pub fn location_nth_vaporized_asteroid(pos: (i32, i32), map: &[(i32, i32)], n: u } } - let mut sorted_angles: Vec = asteroids.keys().copied().collect(); - sorted_angles.sort(); - - asteroids.values_mut().for_each(|lineup_asteroids| lineup_asteroids.sort_by(|(_, l1), (_, l2)| l1.cmp(l2))); + // Sort everything by angle and by distance. + let mut sorted_asteroids: Vec<(&i64, &mut Vec<((i32, i32), i64)>)> = asteroids.iter_mut().collect(); + sorted_asteroids.sort_by(|(a1, _), (a2, _)| a1.cmp(a2)); + for (_, lineup_asteroids) in sorted_asteroids.iter_mut() { + lineup_asteroids.sort_by(|(_, l1), (_, l2)| l1.cmp(l2)) + } let mut i = 1; loop { - for angle in &sorted_angles { - if let Some (lineup_asteroids) = asteroids.get_mut(angle) { - let ((x, y), _) = lineup_asteroids.remove(0); - if i == n { - return (x, y) - } else if lineup_asteroids.is_empty() { - asteroids.remove(angle); - } - i += 1; - } + for (_, lineup_asteroids) in sorted_asteroids.iter_mut() { + let ((x, y), _) = lineup_asteroids.remove(0); + if i == n { return (x, y) } + i += 1; } } } diff --git a/src/day11.rs b/src/day11.rs index cb3c154..2320722 100644 --- a/src/day11.rs +++ b/src/day11.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use super::intcode; enum NextCommand { - ColorToPaint, + Paint, Turn } @@ -16,7 +16,7 @@ struct Robot { impl Robot { fn new() -> Self { Robot { - next_command: NextCommand::ColorToPaint, + next_command: NextCommand::Paint, current_pos: (0, 0), current_dir: 0, panels: HashMap::new() @@ -32,7 +32,7 @@ impl intcode::IO for Robot { fn write(&mut self, value: i64) { self.next_command = match self.next_command { - NextCommand::ColorToPaint => { self.panels.insert(self.current_pos, value); NextCommand::Turn }, + NextCommand::Paint => { self.panels.insert(self.current_pos, value); NextCommand::Turn }, NextCommand::Turn => { self.current_dir = (self.current_dir + if value == 0 /* Turn left. */ { 3 } else /* Turn right. */ { 1 }) % 4; let (x, y) = self.current_pos; @@ -43,7 +43,7 @@ impl intcode::IO for Robot { 2 => (x , y - 1), 3 | _ => (x - 1, y ) }; - NextCommand::ColorToPaint + NextCommand::Paint } } } diff --git a/src/main.rs b/src/main.rs index 18d560e..2d8398f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -98,7 +98,7 @@ fn format_micros(t: u128) -> String { fn do_day(days: &[fn() -> String], day: usize) { let now = Instant::now(); - println!("Result of day {}: {} (time: {})", day, days[day - 1](), format_micros(now.elapsed().as_micros())); + println!("Result of day {:02}: {} (time: {})", day, days[day - 1](), format_micros(now.elapsed().as_micros())); } fn main() {