Add day 3 part 2 in Rust
This commit is contained in:
parent
8b6f5708e5
commit
53dad7ee15
|
@ -1,4 +1,4 @@
|
|||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufRead};
|
||||
|
||||
struct Movement {
|
||||
|
@ -15,7 +15,8 @@ impl Movement {
|
|||
}
|
||||
}
|
||||
|
||||
fn make_step(x: &mut i32, y: &mut i32, dir: char) {
|
||||
fn make_step(x: &mut i32, y: &mut i32, steps: &mut i32, dir: char) {
|
||||
*steps += 1;
|
||||
match dir {
|
||||
'U' => *y += 1,
|
||||
'D' => *y -= 1,
|
||||
|
@ -33,24 +34,33 @@ pub fn main() {
|
|||
.collect::<Vec<_>>()
|
||||
});
|
||||
let (first_wire, second_wire) = (input.next().unwrap(), input.next().unwrap());
|
||||
let mut first_wire_positions = HashSet::new();
|
||||
let (mut x, mut y) = (0, 0);
|
||||
let mut first_wire_positions = HashMap::new();
|
||||
let (mut x, mut y, mut steps) = (0, 0, 0);
|
||||
for m in first_wire {
|
||||
for _ in 0..m.distance {
|
||||
make_step(&mut x, &mut y, m.direction);
|
||||
first_wire_positions.insert((x, y));
|
||||
make_step(&mut x, &mut y, &mut steps, m.direction);
|
||||
first_wire_positions.insert((x, y), steps);
|
||||
}
|
||||
}
|
||||
x = 0;
|
||||
y = 0;
|
||||
steps = 0;
|
||||
let mut intersections = HashMap::new();
|
||||
for m in second_wire {
|
||||
for _ in 0..m.distance {
|
||||
make_step(&mut x, &mut y, m.direction);
|
||||
if first_wire_positions.contains(&(x, y)) {
|
||||
intersections.insert((x, y), 0);
|
||||
}
|
||||
make_step(&mut x, &mut y, &mut steps, m.direction);
|
||||
first_wire_positions
|
||||
.get(&(x, y))
|
||||
.map(|s| intersections.insert((x, y), s + steps));
|
||||
}
|
||||
}
|
||||
println!("Part 1: {}", intersections.keys().map(|(x, y)| x.abs() + y.abs()).min().unwrap());
|
||||
println!(
|
||||
"Part 1: {}",
|
||||
intersections
|
||||
.keys()
|
||||
.map(|(x, y)| x.abs() + y.abs())
|
||||
.min()
|
||||
.unwrap()
|
||||
);
|
||||
println!("Part 2: {}", intersections.values().min().unwrap());
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user