-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.rs
116 lines (97 loc) · 2.84 KB
/
lib.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
extern crate core;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
pub fn fn1(input: &str) -> i32 {
let lines: Vec<_> = input.lines().collect();
let mut grid = Grid::new();
let mut blocks = Vec::new();
for line in lines.iter() {
let split = line.split(",").collect::<Vec<_>>();
let x = split[0].parse::<i32>().unwrap();
let y = split[1].parse::<i32>().unwrap();
let z = split[2].parse::<i32>().unwrap();
grid.add(x, y, z);
blocks.push(Block { x, y, z })
}
let mut count = 0;
for block in blocks.iter() {
count += grid.is_empty(block.x - 1, block.y, block.z)
+ grid.is_empty(block.x + 1, block.y, block.z)
+ grid.is_empty(block.x, block.y - 1, block.z)
+ grid.is_empty(block.x, block.y + 1, block.z)
+ grid.is_empty(block.x, block.y, block.z - 1)
+ grid.is_empty(block.x, block.y, block.z + 1)
}
count
}
struct Block {
x: i32,
y: i32,
z: i32,
}
struct Grid {
grid: HashMap<i32, HashMap<i32, HashMap<i32, bool>>>,
}
impl Grid {
fn new() -> Self {
Grid {
grid: HashMap::new(),
}
}
fn add(&mut self, x: i32, y: i32, z: i32) {
let m = self.grid.entry(x).or_insert(HashMap::new());
let m = m.entry(y).or_insert(HashMap::new());
m.insert(z, true);
}
fn is_empty(&mut self, x: i32, y: i32, z: i32) -> i32 {
if let Entry::Occupied(v) = self.grid.entry(x) {
let m = v.into_mut();
if let Entry::Occupied(v) = m.entry(y) {
let m = v.into_mut();
if let Entry::Occupied(_) = m.entry(z) {
return 0;
}
}
}
1
}
}
pub fn fn2(input: &str) -> i32 {
let lines: Vec<_> = input.lines().collect();
let mut grid = Grid::new();
let mut blocks = Vec::new();
for line in lines.iter() {
let split = line.split(",").collect::<Vec<_>>();
let x = split[0].parse::<i32>().unwrap();
let y = split[1].parse::<i32>().unwrap();
let z = split[2].parse::<i32>().unwrap();
grid.add(x, y, z);
blocks.push(Block { x, y, z })
}
1
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_fn1_unit() {
let s = fs::read_to_string("test.txt").unwrap();
assert_eq!(fn1(s.as_str()), 64);
}
#[test]
fn test_fn1_input() {
let s = fs::read_to_string("input.txt").unwrap();
assert_eq!(fn1(s.as_str()), 3454);
}
#[test]
fn test_fn2_unit() {
let s = fs::read_to_string("test.txt").unwrap();
assert_eq!(fn2(s.as_str()), 58);
}
#[test]
fn test_fn2_input() {
let s = fs::read_to_string("input.txt").unwrap();
assert_eq!(fn2(s.as_str()), 1);
}
}