-
Notifications
You must be signed in to change notification settings - Fork 1
/
6a.rs
75 lines (67 loc) · 1.65 KB
/
6a.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
use std::io;
use std::io::prelude::*;
use std::error::Error;
use std::collections::HashMap;
#[derive(Debug)]
struct Body {
name: String,
orbiting: String
}
#[derive(Debug)]
struct Map {
bodies: Vec<Body>,
by_name: HashMap<String, usize>,
}
impl Map {
fn read(input: impl BufRead) -> io::Result<Map> {
let mut bodies = vec![];
let mut by_name = HashMap::new();
for line in input.lines() {
let line = line?;
let mut tokiter = line.split(")");
let orbitee = tokiter.next().unwrap();
let orbiter = tokiter.next().unwrap().trim();
by_name.insert(orbiter.to_owned(), bodies.len());
bodies.push(Body {
name: orbiter.to_owned(),
orbiting: orbitee.to_owned()
});
}
Ok(Map { bodies, by_name })
}
fn find_body(&self, name: &str) -> Option<&Body> {
self.by_name.get(name).map(|&ind| &self.bodies[ind])
}
fn count_orbits_of(&self, body: &Body) -> usize {
if let Some(orbitee) = self.find_body(&body.orbiting) {
1 + self.count_orbits_of(orbitee)
}
else {
assert!(body.orbiting == "COM");
1
}
}
fn count_all_orbits(&self) -> usize {
self.bodies.iter().map(|b| self.count_orbits_of(b)).sum()
}
}
fn run_tests() {
let map = Map::read(&b"COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L"[..]).unwrap();
assert_eq!(map.count_all_orbits(), 42);
}
fn main() -> Result<(), Box<dyn Error>> {
run_tests();
let map = Map::read(io::stdin().lock())?;
println!("{:?}", map.count_all_orbits());
Ok(())
}