year2015/
day01.rs

1use utils::prelude::*;
2
3/// Counting brackets.
4#[derive(Clone, Debug)]
5pub struct Day01 {
6    directions: Vec<i32>,
7}
8
9impl Day01 {
10    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
11        Ok(Self {
12            directions: input
13                .chars()
14                .map(|c| match c {
15                    '(' => Ok(1),
16                    ')' => Ok(-1),
17                    _ => Err(InputError::new(input, c, "expected bracket")),
18                })
19                .collect::<Result<Vec<i32>, InputError>>()?,
20        })
21    }
22
23    #[must_use]
24    pub fn part1(&self) -> i32 {
25        self.directions.iter().sum()
26    }
27
28    #[must_use]
29    pub fn part2(&self) -> usize {
30        self.directions
31            .iter()
32            .enumerate()
33            .scan(0, |floor, (i, x)| {
34                *floor += x;
35                Some((i + 1, *floor)) // Character positions are 1-indexed in the puzzle
36            })
37            .find(|&(_, floor)| floor == -1)
38            .expect("floor -1 not reached")
39            .0
40    }
41}
42
43examples!(Day01 -> (i32, usize) [
44    {input: "(())", part1: 0},
45    {input: "()()", part1: 0},
46    {input: "(((", part1: 3},
47    {input: "(()(()(", part1: 3},
48    {input: "))(((((", part1: 3},
49    {input: "())", part1: -1},
50    {input: "))(", part1: -1},
51    {input: ")))", part1: -3},
52    {input: ")())())", part1: -3},
53    {input: ")", part2: 1},
54    {input: "()())", part2: 5},
55]);