-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
65 lines (56 loc) · 1.53 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
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
use itertools::Itertools;
pub fn main() {
let data = include_str!("input.txt");
println!("Part 1: {}", part_one::<8>(data));
println!("Part 2: {}", part_two::<8>(data));
}
fn part_one<const N: usize>(data: &str) -> String {
(0..N)
.into_iter()
.map(|i| most_common::<N>(data, i))
.collect::<String>()
}
fn part_two<const N: usize>(data: &str) -> String {
(0..N)
.into_iter()
.map(|i| least_common::<N>(data, i))
.collect::<String>()
}
// TODO: Lot of duplication, can we pass in a closure and only use one copy of this function?
fn most_common<const N: usize>(data: &str, offset: usize) -> char {
data.chars()
.skip(offset)
.step_by(N + 1)
.sorted_unstable()
.dedup_with_count()
.sorted_unstable_by_key(|&(c, _)| std::cmp::Reverse(c))
.map(|(_, s)| s)
.next()
.unwrap()
}
fn least_common<const N: usize>(data: &str, offset: usize) -> char {
data.chars()
.skip(offset)
.step_by(N + 1)
.sorted_unstable()
.dedup_with_count()
.sorted_unstable_by_key(|&(c, _)| c)
.map(|(_, s)| s)
.next()
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one() {
let data = include_str!("test.txt");
assert_eq!("easter", part_one::<6>(data));
}
#[test]
fn two() {
let data = include_str!("test.txt");
assert_eq!("advent", part_two::<6>(data));
}
}