aboutsummaryrefslogtreecommitdiff
path: root/day2/src/main.rs
blob: 2acc32d9ba95563764fa0768c0399a3ae7593135 (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use std::{env, fs, num::ParseIntError, ops::Range, str::FromStr};

#[derive(Debug, Clone, Copy)]
struct IDRange(u64, u64);

#[derive(Debug)]
struct ParseIDRangeError;

impl From<ParseIntError> for ParseIDRangeError {
    fn from(_: ParseIntError) -> Self {
        Self
    }
}

impl FromStr for IDRange {
    type Err = ParseIDRangeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (start, end) = s.split_once('-').ok_or(ParseIDRangeError)?;
        Ok(Self(start.parse()?, end.parse()?))
    }
}

struct IDRangeIntoIter {
    range: IDRange,
    cur: u64,
}

impl Iterator for IDRangeIntoIter {
    type Item = ID;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cur <= self.range.1 {
            let id = ID(self.cur);
            self.cur += 1;
            Some(id)
        } else {
            None
        }
    }
}

impl IntoIterator for IDRange {
    type Item = ID;

    type IntoIter = IDRangeIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        Self::IntoIter {
            cur: self.0,
            range: self,
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
struct ID(u64);

impl ID {
    fn is_invalid_simple(&self) -> bool {
        let s = self.0.to_string();
        s.len() % 2 == 0 && {
            let (a, b) = s.split_at(s.len() / 2);
            a == b
        }
    }

    fn is_invalid(&self) -> bool {
        let s = self.0.to_string();

        if s.len() <= 1 {
            return false;
        }

        let chars: Vec<char> = s.chars().collect();

        let mut i = 1;
        let mut j = 0;

        loop {
            if i == chars.len() - 1 {
                return chars[i] == chars[j] && chars.len() % (i - j) == 0;
            }

            if chars[i] == chars[j] {
                j += 1;
            } else {
                j = 0;
            }

            i += 1;
        }
    }
}

#[derive(Debug)]
enum Error {
    BadArgument,
    BadRange(String),
}

impl From<std::io::Error> for Error {
    fn from(_: std::io::Error) -> Self {
        Self::BadArgument
    }
}

fn main() -> Result<(), Error> {
    let x: Range<u32> = 0..99;
    let mut args = env::args();
    let input_path = args.nth(1).ok_or_else(|| Error::BadArgument)?;
    let input = fs::read_to_string(input_path)?;

    let ranges: Vec<IDRange> = input
        .split_whitespace()
        .flat_map(|s| s.split(','))
        .filter(|s| s.len() != 0)
        .map(|s| s.parse().map_err(|_| Error::BadRange(s.into())))
        .collect::<Result<_, _>>()?;

    let result_simple: u64 = ranges
        .iter()
        .flat_map(|range| {
            range
                .into_iter()
                .filter(ID::is_invalid_simple)
                .map(|id| id.0)
        })
        .sum();

    let result: u64 = ranges
        .iter()
        .flat_map(|range| range.into_iter().filter(ID::is_invalid).map(|id| id.0))
        .sum();

    println!("Result (simple): {}", result_simple);
    println!("Result: {}", result);

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_id_range() -> Result<(), ParseIDRangeError> {
        let range: IDRange = "99-100".parse()?;
        assert_eq!(range.0, 99);
        assert_eq!(range.1, 100);
        Ok(())
    }

    #[test]
    fn id_range_into_iter() {
        let range = IDRange(2, 4);
        let ids: Vec<ID> = range.into_iter().collect();
        assert_eq!(ids, vec![ID(2), ID(3), ID(4)]);
    }

    #[test]
    fn id_is_invalid_simple() {
        assert!(!ID(0).is_invalid_simple());
        assert!(!ID(1).is_invalid_simple());
        assert!(!ID(2).is_invalid_simple());
        assert!(!ID(10).is_invalid_simple());
        assert!(!ID(12).is_invalid_simple());
        assert!(!ID(21).is_invalid_simple());

        assert!(ID(11).is_invalid_simple());
        assert!(ID(5555).is_invalid_simple());
    }

    #[test]
    fn id_is_invalid() {
        assert!(!ID(1).is_invalid());
        assert!(!ID(12).is_invalid());
        assert!(!ID(121).is_invalid());
        assert!(!ID(1214).is_invalid());
        assert!(!ID(123121).is_invalid());

        assert!(ID(11).is_invalid());
        assert!(ID(1212).is_invalid());
        assert!(ID(111).is_invalid());
        assert!(ID(123123).is_invalid());
        assert!(ID(121212).is_invalid());
        assert!(ID(1010).is_invalid());
    }
}