Skip to main content

advent_of_code/year2017/
day01.rs

1use crate::input::Input;
2
3pub fn solve(input: &Input) -> Result<u32, String> {
4    let index_offset_computer = if input.is_part_one() {
5        |_| 1
6    } else {
7        |len| len / 2
8    };
9
10    let digits: Vec<u32> = input
11        .text
12        .chars()
13        .map(|c| c.to_digit(10).ok_or("Invalid input - not all digits"))
14        .collect::<Result<_, _>>()?;
15    if digits.len() > 10_000 {
16        return Err("Invalid input - too long".to_string());
17    }
18    Ok(digits
19        .iter()
20        .enumerate()
21        .map(|(index, &digit)| {
22            if digit == digits[(index + index_offset_computer(digits.len())) % digits.len()] {
23                digit
24            } else {
25                0
26            }
27        })
28        .sum())
29}
30
31#[test]
32fn tests() {
33    test_part_one!("1122" => 3);
34    test_part_one!("1111" => 4);
35    test_part_one!("1234" => 0);
36    test_part_one!("91212129" => 9);
37
38    test_part_two!("1212" => 6);
39    test_part_two!("1221" => 0);
40    test_part_two!("123425" => 4);
41    test_part_two!("123123" => 12);
42    test_part_two!("12131415" => 4);
43
44    let input = include_str!("day01_input.txt");
45    test_part_one!(input => 1029);
46    test_part_two!(input => 1220);
47}