generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06.rs
67 lines (55 loc) · 1.73 KB
/
06.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
pub fn part_one(input: &str) -> Option<usize> {
solve(input, 4)
}
pub fn part_two(input: &str) -> Option<usize> {
solve(input, 14)
}
fn solve(input: &str, count: usize) -> Option<usize> {
let bytes = input.as_bytes();
let max = bytes.len() - count;
let mut i = 0;
while i < max {
let jump = calculate_forward_skip(&bytes[i..i + count]);
if jump == 0 {
return Some(i + count);
}
i += jump;
}
None
}
fn calculate_forward_skip(bytes: &[u8]) -> usize {
let mut i = bytes.len();
while i != 1 {
let v = bytes[i - 1];
if let Some(p) = bytes[0..i - 1].iter().position(|x| *x == v) {
return p + 1;
}
i -= 1;
}
0
}
fn main() {
let input = &aoc::read_file("inputs", 6);
aoc::solve!(1, part_one, input);
aoc::solve!(2, part_two, input);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
assert_eq!(part_one(&"mjqjpqmgbljsphdztnvjfqwrcgsmlb"), Some(7));
assert_eq!(part_one(&"bvwbjplbgvbhsrlpgdmjqwftvncz"), Some(5));
assert_eq!(part_one(&"nppdvjthqldpwncqszvftbrmjlhg"), Some(6));
assert_eq!(part_one(&"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"), Some(10));
assert_eq!(part_one(&"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"), Some(11));
}
#[test]
fn test_part_two() {
assert_eq!(part_two(&"mjqjpqmgbljsphdztnvjfqwrcgsmlb"), Some(19));
assert_eq!(part_two(&"bvwbjplbgvbhsrlpgdmjqwftvncz"), Some(23));
assert_eq!(part_two(&"nppdvjthqldpwncqszvftbrmjlhg"), Some(23));
assert_eq!(part_two(&"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"), Some(29));
assert_eq!(part_two(&"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"), Some(26));
}
}