-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rs
73 lines (69 loc) · 1.98 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::collections::HashMap;
use std::fs;
fn get_input(fp: &str) -> Vec<Vec<(char, isize)>> {
fs::read_to_string(fp)
.expect("Cannot read file")
.trim_end()
.split('\n')
.map(|x| {
x.split(',')
.map(|y| (y.chars().nth(0).unwrap(), y[1..].parse().unwrap()))
.collect()
})
.collect()
}
fn fill_points(instructions: &[(char, isize)]) -> HashMap<(isize, isize), isize> {
let mut point: (isize, isize) = (0, 0);
let mut points = HashMap::new();
let mut step = 1;
let mut npoint = point;
for x in instructions.iter() {
let direction: (isize, isize);
match x.0 {
'R' => direction = (0, 1),
'L' => direction = (0, -1),
'U' => direction = (1, 0),
'D' => direction = (-1, 0),
_ => continue,
}
for i in 1..=x.1 {
npoint = (point.0 + i * direction.0, point.1 + i * direction.1);
points.entry(npoint).or_insert(step);
step += 1;
}
point = npoint;
}
points
}
fn part_one(
intersection: &[(isize,isize)],
) -> isize {
intersection
.iter()
.map(|(x, y)| x.abs() + y.abs())
.min_by_key(|&x| x)
.unwrap()
}
fn part_two(
intersection: &[(isize,isize)],
points1: &HashMap<(isize, isize), isize>,
points2: &HashMap<(isize, isize), isize>,
) -> isize {
intersection
.iter()
.map(|k| points1.get(k).unwrap() + points2.get(k).unwrap())
.min_by_key(|&x| x)
.unwrap()
}
fn main() {
let input = get_input("../input.txt");
let points1 = fill_points(&input[0]);
let points2 = fill_points(&input[1]);
let intersection: Vec<(isize, isize)> = points1
.keys()
.filter(|k| points2.contains_key(k))
.copied()
.collect();
println!("Part one: {}", part_one(&intersection));
println!("Part two: {:?}", part_two(&intersection,&points1, &points2));
}