Do d01 using mapping and reducing iterators

This commit is contained in:
IamTheFij 2021-12-03 11:01:34 -08:00
parent 5bd5c5123e
commit cfbaaf8126

View File

@ -12,6 +12,7 @@ where
} }
fn part1() { fn part1() {
// My naiive attempt
if let Ok(lines) = read_lines("input.txt") { if let Ok(lines) = read_lines("input.txt") {
let mut last_val: Option<i32> = None; let mut last_val: Option<i32> = None;
let mut num_increase = 0; let mut num_increase = 0;
@ -39,6 +40,34 @@ fn part1() {
} }
} }
fn part1mr() {
// Something more functional
let mut last_val: Option<i32> = 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::<i32>()
.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() { fn part2() {
if let Ok(lines) = read_lines("input.txt") { if let Ok(lines) = read_lines("input.txt") {
let mut num_increase = 0; let mut num_increase = 0;
@ -59,7 +88,7 @@ fn part2() {
num_increase += 1; num_increase += 1;
} }
sliding_values.push_back(val); sliding_values.push_back(val);
println!("{}: {}", val, increase); // println!("{}: {}", val, increase);
} }
Err(e) => println!("ERROR: Could not parse {}. {}", l, e), Err(e) => println!("ERROR: Could not parse {}. {}", l, e),
} }
@ -70,7 +99,39 @@ fn part2() {
} }
} }
fn part2mr() {
let mut sliding_values: VecDeque<i32> = 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::<i32>()
.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() { fn main() {
part1(); part1();
part1mr();
part2(); part2();
part2mr();
} }