-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.rs
90 lines (76 loc) · 2.09 KB
/
day3.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
// vi: set shiftwidth=4 tabstop=4 expandtab:
use common::input::check_answer;
use common::input::get_answers;
use common::input::get_file_content;
use std::time::Instant;
const INPUT_FILEPATH: &str = "../resources/year2016_day3_input.txt";
const ANSWERS_FILEPATH: &str = "../resources/year2016_day3_answer.txt";
type Int = u32;
type InputContent = Vec<Vec<Int>>;
fn parse_integer_list(str: &str) -> Vec<Int> {
str.split(' ')
.filter(|s| !s.is_empty())
.map(|s| s.parse::<u32>().unwrap())
.collect()
}
fn get_input_from_str(string: &str) -> InputContent {
string.lines().map(parse_integer_list).collect()
}
fn is_triangle(nbs: &[Int]) -> bool {
let mut sorted = nbs.to_owned();
sorted.sort_unstable();
if let [a, b, c] = &*sorted {
if a + b > *c {
return true;
}
}
false
}
fn part1(arg: &InputContent) -> usize {
arg.iter().filter(|nbs| is_triangle(nbs)).count()
}
fn transpose(v: &InputContent) -> InputContent {
assert!(!v.is_empty());
let len = v[0].len();
(0..len)
.map(|i| v.iter().map(|row| row[i]).collect())
.collect()
}
fn part2(arg: &InputContent) -> usize {
transpose(arg)
.iter()
.map(|col| col.chunks_exact(3).filter(|nbs| is_triangle(nbs)).count())
.sum()
}
fn main() {
let before = Instant::now();
let data = get_input_from_str(&get_file_content(INPUT_FILEPATH));
let (ans, ans2) = get_answers(ANSWERS_FILEPATH);
let solved = true;
let res = part1(&data);
check_answer(&res.to_string(), ans, solved);
let res2 = part2(&data);
check_answer(&res2.to_string(), ans2, solved);
println!("Elapsed time: {:.2?}", before.elapsed());
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE: &str = "5 10 25
5 10 20
2 3 4";
const EXAMPLE2: &str = "101 301 501
102 302 502
103 303 503
201 401 601
202 402 602
203 403 603";
#[test]
fn test_part1() {
assert_eq!(part1(&get_input_from_str(EXAMPLE)), 1);
}
#[test]
fn test_part2() {
assert_eq!(part2(&get_input_from_str(EXAMPLE2)), 6);
}
}