}
}
- let mut sorted_angles: Vec<i64> = 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;
}
}
}
use super::intcode;\r
\r
enum NextCommand {\r
- ColorToPaint,\r
+ Paint,\r
Turn\r
}\r
\r
impl Robot {\r
fn new() -> Self {\r
Robot {\r
- next_command: NextCommand::ColorToPaint,\r
+ next_command: NextCommand::Paint,\r
current_pos: (0, 0),\r
current_dir: 0,\r
panels: HashMap::new()\r
fn write(&mut self, value: i64) {\r
self.next_command =\r
match self.next_command {\r
- NextCommand::ColorToPaint => { self.panels.insert(self.current_pos, value); NextCommand::Turn },\r
+ NextCommand::Paint => { self.panels.insert(self.current_pos, value); NextCommand::Turn },\r
NextCommand::Turn => {\r
self.current_dir = (self.current_dir + if value == 0 /* Turn left. */ { 3 } else /* Turn right. */ { 1 }) % 4;\r
let (x, y) = self.current_pos;\r
2 => (x , y - 1),\r
3 | _ => (x - 1, y )\r
};\r
- NextCommand::ColorToPaint\r
+ NextCommand::Paint\r
}\r
}\r
}\r
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() {