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
pub fn part1(matrix: &[Vec<u32>]) -> u32 {
matrix.iter().map(Vec::as_slice).map(range).sum()
}
pub fn part2(matrix: &mut [Vec<u32>]) -> u32 {
matrix.iter_mut().map(multiples).sum()
}
pub fn range(row: &[u32]) -> u32 {
let max = row.iter().max().unwrap();
let min = row.iter().min().unwrap();
max - min
}
pub fn read_matrix(input: &str) -> Vec<Vec<u32>> {
use std::str::FromStr;
input
.lines()
.filter(|l| !l.trim().is_empty())
.map(|l| {
l.split_whitespace()
.filter_map(|s| u32::from_str(s).ok())
.collect()
}).collect()
}
pub fn multiples(row: &mut Vec<u32>) -> u32 {
row.sort();
for i in 0..row.len() {
for j in i + 1..row.len() {
if row[j] % row[i] == 0 {
return row[j] / row[i];
}
}
}
unreachable!()
}
#[test]
fn examples() {
let one = r"
5 1 9 5
7 5 3
2 4 6 8
";
let two = r"
5 9 2 8
9 4 7 3
3 8 6 5
";
assert_eq!(part1(&read_matrix(one)), 18);
assert_eq!(part2(&mut read_matrix(two)), 9);
}
#[test]
fn solution() {
let mut digits = read_matrix(include_str!("input/2"));
assert_eq!(part1(&digits), 32020);
assert_eq!(part2(&mut digits), 236);
}