summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJustin Worthe <justin@worthe-it.co.za>2018-12-01 09:20:06 +0200
committerJustin Worthe <justin@worthe-it.co.za>2018-12-01 09:20:06 +0200
commit8ca1d096ff846511fcbd9a538b5785651b13675c (patch)
treed90c4c69fa49f8f491a483b37b664bb277da9d57 /src
parent2ae69db72b55374864bdbe3f88b5859e0ace9fe2 (diff)
More functional take on day 1
Diffstat (limited to 'src')
-rw-r--r--src/bin/day_1.rs25
1 files changed, 10 insertions, 15 deletions
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(())
}