-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
65 lines (53 loc) · 1.52 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
pub fn main() {
let data = include_str!("input.txt");
println!("Part 1: {}", part_one(data));
println!("Part 2: {}", part_two(data));
}
fn part_one(data: &str) -> u64 {
data.lines()
.map(range_parts)
.map(|(a, b)| (str_to_range(a), str_to_range(b)))
.map(contained)
.fold(0, |acc, v| if v { acc + 1 } else { acc })
}
fn part_two(data: &str) -> u64 {
data.lines()
.map(range_parts)
.map(|(a, b)| (str_to_range(a), str_to_range(b)))
.map(overlap)
.fold(0, |acc, v| if v { acc + 1 } else { acc })
}
fn range_parts(line: &str) -> (&str, &str) {
let mut parts = line.split(',');
(parts.next().unwrap(), parts.next().unwrap())
}
fn str_to_range(input: &str) -> (u64, u64) {
let mut x = input.split('-').map(|v| v.parse::<u64>().unwrap());
(x.next().unwrap(), x.next().unwrap())
}
fn contained((a, b): ((u64, u64), (u64, u64))) -> bool {
contains(a, b) || contains(b, a)
}
fn contains(a: (u64, u64), b: (u64, u64)) -> bool {
a.0 <= b.0 && a.1 >= b.1
}
fn overlap((a, b): ((u64, u64), (u64, u64))) -> bool {
overlap_one(a, b) || overlap_one(b, a)
}
fn overlap_one(a: (u64, u64), b: (u64, u64)) -> bool {
a.1 >= b.0 && a.0 < b.1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one() {
let data = include_str!("test.txt").trim_end_matches('\n');
assert_eq!(2, part_one(data));
}
#[test]
fn two() {
let data = include_str!("test.txt");
assert_eq!(4, part_two(data));
}
}