diff options
Diffstat (limited to 'day02')
| -rw-r--r-- | day02/.gitignore | 3 | ||||
| -rw-r--r-- | day02/Cargo.lock | 7 | ||||
| -rw-r--r-- | day02/Cargo.toml | 6 | ||||
| -rw-r--r-- | day02/src/main.rs | 70 |
4 files changed, 86 insertions, 0 deletions
diff --git a/day02/.gitignore b/day02/.gitignore new file mode 100644 index 0000000..9cd70c0 --- /dev/null +++ b/day02/.gitignore @@ -0,0 +1,3 @@ +/target +/input.txt +/example*.txt
\ No newline at end of file diff --git a/day02/Cargo.lock b/day02/Cargo.lock new file mode 100644 index 0000000..2762917 --- /dev/null +++ b/day02/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "day02" +version = "0.1.0" diff --git a/day02/Cargo.toml b/day02/Cargo.toml new file mode 100644 index 0000000..3304419 --- /dev/null +++ b/day02/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day02" +version = "0.1.0" +edition = "2024" + +[dependencies] 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); +} |
