diff options
Diffstat (limited to 'day02/src/main.rs')
| -rw-r--r-- | day02/src/main.rs | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/day02/src/main.rs b/day02/src/main.rs new file mode 100644 index 0000000..ce21752 --- /dev/null +++ b/day02/src/main.rs @@ -0,0 +1,70 @@ +use std::io; + +struct Range { + start: i64, + end: i64, +} + +impl Range { + fn new<'a>(mut iter: impl DoubleEndedIterator<Item = &'a str>) -> Self { + let start = iter.next().unwrap().parse::<i64>().unwrap(); + let end = iter.next().unwrap().parse::<i64>().unwrap(); + Self { start, end } + } +} + +fn is_invalid(value: i64) -> bool { + let tmp = value.to_string(); + /* + if tmp.len() % 2 != 0 { + return false + } + let (a, b) = tmp.split_at(tmp.len() / 2); + return a == b; + */ + for x in 1..=tmp.len() / 2 { + if tmp.len() % x != 0 { + continue; + } + let (first, rest) = tmp.split_at(x); + let mut rest2 = rest; + let mut all_match = true; + for _ in 0..tmp.len() / x - 1 { + match rest2.strip_prefix(first) { + Some(value) => rest2 = value, + None => { + all_match = false; + break; + } + }; + } + if all_match { + return true; + } + } + false +} + +fn invalid(range: &Range) -> i64 { + let mut total = 0; + for i in range.start..=range.end { + if is_invalid(i) { + total += i; + } + } + total +} + +fn main() { + let mut buffer = String::new(); + io::stdin().read_line(&mut buffer).unwrap(); + let mut total = 0; + for range in buffer + .trim_end() + .split(',') + .map(|x| Range::new(x.split('-'))) + { + total += invalid(&range); + } + println!("Invalid: {}", total); +} |
