Compare commits

...

2 Commits

Author SHA1 Message Date
Johannes
a0509342ae day01-2 use scan with tuple expansion
The previous problem with this was, that I tried returning
"Some((Ref<i32>, _))" 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.
2018-12-01 18:19:07 +01:00
Johannes
0494dee19d day01-2 tuple 2018-12-01 17:54:30 +01:00

View File

@@ -7,29 +7,23 @@ pub fn task1() {
.map(|line| line.parse::<i32>().unwrap()) .map(|line| line.parse::<i32>().unwrap())
.sum(); .sum();
println!("Result: {}", frequency); println!("Part 1: {}", frequency);
} }
pub fn task2() { pub fn task2() {
let contents = utils::read_file("input/day01.txt"); let start_state = (vec![0].into_iter().collect::<HashSet<i32>>(), 0);
let final_state = utils::read_file("input/day01.txt")
let mut seen: HashSet<i32> = HashSet::new();
seen.insert(0);
let start_state = (std::cell::RefCell::new(seen), std::cell::RefCell::new(0));
let final_state = contents
.lines() .lines()
.map(|line| line.parse::<i32>().unwrap()) .map(|line| line.parse::<i32>().unwrap())
.cycle() .cycle()
.scan(&start_state, |(hash_set, current_freq), freq_change| { .scan(start_state, |(set, current), freq_change| {
*current_freq.borrow_mut() += freq_change; *current += freq_change;
if hash_set.borrow_mut().contains(&current_freq.borrow()) { if set.insert(*current) {
Some((current_freq.borrow(), true)) Some((*current, false))
} else { } else {
let value: i32 = *current_freq.borrow_mut(); Some((*current, true))
hash_set.borrow_mut().insert(value);
Some((current_freq.borrow(), false))
} }
}).find(|state| state.1); }).find(|state| state.1);
println!("{:?} was there already!", final_state.unwrap().0); println!("Part 2: {} was there already!", final_state.unwrap().0);
} }