From cfbaaf8126e30bd24e95f45be83306345ac1acc7 Mon Sep 17 00:00:00 2001 From: Ian Fijolek Date: Fri, 3 Dec 2021 11:01:34 -0800 Subject: [PATCH] Do d01 using mapping and reducing iterators --- d01/src/main.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/d01/src/main.rs b/d01/src/main.rs index c24cbab..1a2b758 100644 --- a/d01/src/main.rs +++ b/d01/src/main.rs @@ -12,6 +12,7 @@ where } fn part1() { + // My naiive attempt if let Ok(lines) = read_lines("input.txt") { let mut last_val: Option = None; let mut num_increase = 0; @@ -39,6 +40,34 @@ fn part1() { } } +fn part1mr() { + // Something more functional + let mut last_val: Option = None; + let num_increase = read_lines("input.txt") + .expect("Expected a file to read") + .map(|line| line.expect("Could not read line")) + .map(|line| { + line.parse::() + .expect(format!("Error parsing '{}' as in int", line).as_str()) + }) + .map(|value| { + let mut increase = 0; + if let Some(last_val) = last_val { + if value > last_val { + increase = 1; + } + } + last_val = Some(value); + increase + }) + .reduce(|num_increase, increase| num_increase + increase); + + println!( + "Part 1 new, All done! Num increased {}", + num_increase.unwrap() + ); +} + fn part2() { if let Ok(lines) = read_lines("input.txt") { let mut num_increase = 0; @@ -59,7 +88,7 @@ fn part2() { num_increase += 1; } sliding_values.push_back(val); - println!("{}: {}", val, increase); + // println!("{}: {}", val, increase); } Err(e) => println!("ERROR: Could not parse {}. {}", l, e), } @@ -70,7 +99,39 @@ fn part2() { } } +fn part2mr() { + let mut sliding_values: VecDeque = VecDeque::with_capacity(3); + let num_increase = read_lines("input.txt") + .expect("Expected a file to read") + .map(|line| line.expect("Could not read line")) + .map(|line| { + line.parse::() + .expect(format!("Error parsing '{}' as in int", line).as_str()) + }) + .map(|value| { + let mut increase = 0; + if sliding_values.len() < 3 { + sliding_values.push_back(value); + } else { + let outgoing = sliding_values.pop_front().unwrap(); + if value > outgoing { + increase = 1; + } + sliding_values.push_back(value); + } + increase + }) + .reduce(|num_increase, increase| num_increase + increase); + + println!( + "Part 2 new, All done! Num increased {}", + num_increase.unwrap() + ); +} + fn main() { part1(); + part1mr(); part2(); + part2mr(); }