Skip to content

Commit 18c77ab

Browse files
committed
Cleaner more functional code
1 parent b932101 commit 18c77ab

File tree

1 file changed

+23
-40
lines changed

1 file changed

+23
-40
lines changed

src/year2017/day04.rs

Lines changed: 23 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,50 +20,33 @@ pub fn parse(input: &str) -> Input<'_> {
2020
input.lines().collect()
2121
}
2222

23-
pub fn part1(input: &Input<'_>) -> u32 {
24-
let mut result = 0;
23+
pub fn part1(input: &Input<'_>) -> usize {
2524
let mut seen = FastSet::new();
26-
27-
for line in input {
28-
result += 1;
29-
30-
for token in line.split_ascii_whitespace() {
31-
// Insert returns `false` if the value is already in the set.
32-
if !seen.insert(token.as_bytes()) {
33-
result -= 1;
34-
break;
35-
}
36-
}
37-
38-
seen.clear();
39-
}
40-
41-
result
25+
input
26+
.iter()
27+
.filter(|line| {
28+
seen.clear();
29+
line.split_ascii_whitespace().all(|token| seen.insert(token.as_bytes()))
30+
})
31+
.count()
4232
}
4333

44-
pub fn part2(input: &Input<'_>) -> u32 {
45-
let mut result = 0;
46-
let mut seen = FastSet::new();
47-
48-
for line in input {
49-
result += 1;
50-
51-
for token in line.split_ascii_whitespace() {
52-
// Calculate the frequency of each letter, as anagrams will have the same values.
53-
let mut freq = [0_u8; 26];
54-
55-
for b in token.bytes() {
56-
freq[(b - b'a') as usize] += 1;
57-
}
58-
59-
if !seen.insert(freq) {
60-
result -= 1;
61-
break;
62-
}
34+
pub fn part2(input: &Input<'_>) -> usize {
35+
// Calculate the frequency of each letter as anagrams will have the same values.
36+
fn convert(token: &str) -> [u8; 26] {
37+
let mut freq = [0; 26];
38+
for b in token.bytes() {
39+
freq[(b - b'a') as usize] += 1;
6340
}
64-
65-
seen.clear();
41+
freq
6642
}
6743

68-
result
44+
let mut seen = FastSet::new();
45+
input
46+
.iter()
47+
.filter(|line| {
48+
seen.clear();
49+
line.split_ascii_whitespace().all(|token| seen.insert(convert(token)))
50+
})
51+
.count()
6952
}

0 commit comments

Comments
 (0)