-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path12a.rs
124 lines (112 loc) · 2.95 KB
/
12a.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone)]
struct Coord {
x: i32,
y: i32,
z: i32,
}
#[derive(Debug, Copy, Clone)]
struct Moon {
pos: Coord,
vel: Coord,
}
impl Moon {
fn pot(&self) -> i32 {
self.pos.x.abs() + self.pos.y.abs() + self.pos.z.abs()
}
fn kin(&self) -> i32 {
self.vel.x.abs() + self.vel.y.abs() + self.vel.z.abs()
}
fn total(&self) -> i32 {
self.pot() * self.kin()
}
}
fn apply_gravity(moons: &mut [Moon]) {
for i in 0..moons.len() {
for j in 0..moons.len() {
if i == j {
continue;
}
match moons[i].pos.x.cmp(&moons[j].pos.x) {
Ordering::Less => moons[i].vel.x += 1,
Ordering::Greater => moons[i].vel.x -= 1,
Ordering::Equal => (),
}
match moons[i].pos.y.cmp(&moons[j].pos.y) {
Ordering::Less => moons[i].vel.y += 1,
Ordering::Greater => moons[i].vel.y -= 1,
Ordering::Equal => (),
}
match moons[i].pos.z.cmp(&moons[j].pos.z) {
Ordering::Less => moons[i].vel.z += 1,
Ordering::Greater => moons[i].vel.z -= 1,
Ordering::Equal => (),
}
}
}
}
fn apply_velocity(moons: &mut [Moon]) {
for m in moons {
m.pos.x += m.vel.x;
m.pos.y += m.vel.y;
m.pos.z += m.vel.z;
}
}
fn simulate(moons: &mut [Moon], nsteps: usize) -> i32 {
for _ in 0..nsteps {
apply_gravity(moons);
apply_velocity(moons);
}
moons.iter().map(Moon::total).sum()
}
fn match_const<'a>(s: &'a str, prefix: &str) -> &'a str {
assert!(s.starts_with(prefix));
&s[prefix.len()..]
}
fn match_ws<'a>(s: &'a str) -> &'a str {
for (ind, c) in s.char_indices() {
if !c.is_ascii_whitespace() {
return &s[ind..];
}
}
return "";
}
fn match_num(s: &str) -> (i32, &str) {
let mut end_num = 0;
for (ind, c) in s.char_indices() {
end_num = ind;
if ind == 0 && c == '+' || c == '-' {
continue;
}
if !c.is_ascii_digit() {
break;
}
}
(s[..end_num].parse().unwrap(), &s[end_num..])
}
fn read_coord(s: &str) -> (Coord, &str) {
let s = match_const(s, "<x=");
let (x, s) = match_num(s);
let s = match_const(s, ", y=");
let (y, s) = match_num(s);
let s = match_const(s, ", z=");
let (z, s) = match_num(s);
let s = match_const(s, ">");
let s = match_ws(s);
(Coord { x, y, z }, s)
}
fn read_moons(mut s: &str) -> Vec<Moon> {
let mut moons = vec![];
let zero = Coord { x: 0, y: 0, z: 0 };
while s.len() != 0 {
let (pos, rest) = read_coord(s);
moons.push(Moon { pos, vel: zero });
s = rest;
}
moons
}
fn main() {
let input = include_str!("12.input");
let mut moons = read_moons(input);
print!("{}", simulate(&mut moons, 1000));
}