From a0509342aeefc219963f21de694a2aaa9d3796b7 Mon Sep 17 00:00:00 2001 From: Johannes Date: Sat, 1 Dec 2018 18:19:07 +0100 Subject: [PATCH] day01-2 use scan with tuple expansion The previous problem with this was, that I tried returning "Some((Ref, _))" from the lambda. That caused the compiler to complain about the lifetime of the `current` value, since I tried passing on the Ref instead of the encapsulated value. --- src/tasks/day01.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/tasks/day01.rs b/src/tasks/day01.rs index f70747c..de58329 100644 --- a/src/tasks/day01.rs +++ b/src/tasks/day01.rs @@ -7,26 +7,23 @@ pub fn task1() { .map(|line| line.parse::().unwrap()) .sum(); - println!("Result: {}", frequency); + println!("Part 1: {}", frequency); } pub fn task2() { - let contents = utils::read_file("input/day01.txt"); - - let seen: HashSet = vec![0].into_iter().collect(); - let start_state = (seen, 0); - let final_state = contents + let start_state = (vec![0].into_iter().collect::>(), 0); + let final_state = utils::read_file("input/day01.txt") .lines() .map(|line| line.parse::().unwrap()) .cycle() - .scan(start_state, |state, freq_change| { - state.1 += freq_change; - if state.0.insert(state.1) { - Some((state.1, false)) + .scan(start_state, |(set, current), freq_change| { + *current += freq_change; + if set.insert(*current) { + Some((*current, false)) } else { - Some((state.1, true)) + Some((*current, true)) } }).find(|state| state.1); - println!("{:?} was there already!", final_state.unwrap().0); + println!("Part 2: {} was there already!", final_state.unwrap().0); }