-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_11.rs
91 lines (81 loc) · 2.29 KB
/
day_11.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//! https://adventofcode.com/2017/day/11
//! https://adventofcode.com/2017/day/11/input
use std::{fs::read_to_string, time::Instant};
enum Direction {
N,
S,
Ne,
Sw,
Nw,
Se,
}
impl Direction {
fn to_coord(&self) -> (isize, isize, isize) {
match self {
Direction::N => (0, 1, -1),
Direction::Ne => (-1, 1, 0),
Direction::Se => (-1, 0, 1),
Direction::S => (0, -1, 1),
Direction::Sw => (1, -1, 0),
Direction::Nw => (1, 0, -1),
}
}
}
impl From<&str> for Direction {
fn from(string: &str) -> Self {
match string {
"n" => Self::N,
"ne" => Self::Ne,
"nw" => Self::Nw,
"s" => Self::S,
"se" => Self::Se,
"sw" => Self::Sw,
_ => panic!("Invalid direction: {}", string),
}
}
}
fn parse(input: &str) -> Vec<Direction> {
input.split(',').map(Direction::from).collect()
}
pub mod part1 {
use super::{parse, Direction};
pub fn solve(input: &str) -> usize {
let directions = parse(input);
let (mut x, mut y, mut z) = (0, 0, 0);
for (dx, dy, dz) in directions.iter().map(Direction::to_coord) {
x += dx;
y += dy;
z += dz;
}
(x.unsigned_abs() + y.unsigned_abs() + z.unsigned_abs()) / 2
}
}
pub mod part2 {
use super::{parse, Direction};
pub fn solve(input: &str) -> usize {
let directions = parse(input);
let (mut x, mut y, mut z) = (0, 0, 0);
let mut max_distance = 0;
for (dx, dy, dz) in directions.iter().map(Direction::to_coord) {
x += dx;
y += dy;
z += dz;
max_distance = max_distance.max((x.abs() + y.abs() + z.abs()) / 2)
}
max_distance as usize
}
}
pub fn main(test: bool) {
let test_input = "ne,ne,sw,sw".to_owned();
let puzzle_input = if test {
test_input
} else {
read_to_string("../inputs/2017/day_11_input.txt").unwrap()
};
let start = Instant::now();
println!("{}", part1::solve(&puzzle_input));
println!("Run in {:?}", start.elapsed());
let start = Instant::now();
println!("{}", part2::solve(&puzzle_input));
println!("Run in {:?}", start.elapsed());
}