summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.toml1
-rw-r--r--src/bin/day_1.rs25
2 files changed, 11 insertions, 15 deletions
diff --git a/Cargo.toml b/Cargo.toml
index a723369..c58efea 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,3 +4,4 @@ version = "0.1.0"
authors = ["Justin Worthe <justin@worthe-it.co.za>"]
[dependencies]
+im-rc = "12.2.0" \ No newline at end of file
diff --git a/src/bin/day_1.rs b/src/bin/day_1.rs
index 9f54c70..56ae0f7 100644
--- a/src/bin/day_1.rs
+++ b/src/bin/day_1.rs
@@ -1,10 +1,12 @@
extern crate advent_of_code_2018;
use advent_of_code_2018::*;
+extern crate im_rc;
+
use std::error::Error;
use std::path::PathBuf;
-use std::collections::HashSet;
+use im_rc::HashSet;
// cargo watch -cs "cargo run --bin day_1"
@@ -17,21 +19,14 @@ fn main() -> Result<(), Box<Error>> {
let sum: i32 = input_ints.iter().sum();
println!("Sum: {}", sum);
- let mut seen = HashSet::new();
- let mut acc = 0;
- let mut repeat_found = false;
- while !repeat_found {
- for i in &input_ints {
- if seen.contains(&acc) {
- repeat_found = true;
- break;
- } else {
- seen.insert(acc);
- }
- acc += i;
+ let first_repeat = input_ints.iter().cycle().try_fold((0, HashSet::new()), |(acc, seen), &i| {
+ if seen.contains(&acc) {
+ Err(acc)
+ } else {
+ Ok((acc + i, seen.update(acc)))
}
- }
- println!("First repeat: {}", acc);
+ }).err().unwrap();
+ println!("First repeat: {}", first_repeat);
Ok(())
}