From 8ca1d096ff846511fcbd9a538b5785651b13675c Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Sat, 1 Dec 2018 09:20:06 +0200 Subject: More functional take on day 1 --- Cargo.toml | 1 + src/bin/day_1.rs | 25 ++++++++++--------------- 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 "] [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> { 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(()) } -- cgit v1.2.3