Wrote program for Day 9

This commit is contained in:
Mariano Riefolo 2024-08-03 14:57:17 +02:00
parent 6ee3c88c30
commit 7c5fdc5242
4 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "day9"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,26 @@
pub fn trap(heights: Vec<u8>) -> u16 {
let maxh = heights.iter().max().cloned().unwrap_or(0);
let mut water: u16 =
maxh as u16 * heights.len() as u16 - heights.iter().map(|x| *x as u16).sum::<u16>();
let mut maxt;
maxt = 0;
for h in heights.iter() {
maxt = std::cmp::max(maxt, *h);
if maxt == maxh {
break;
}
water -= maxh as u16 - maxt as u16;
}
maxt = 0;
for h in heights.iter().rev() {
maxt = std::cmp::max(maxt, *h);
if maxt == maxh {
break;
}
water -= maxh as u16 - maxt as u16;
}
water
}

View File

@ -0,0 +1,24 @@
use std::io::{self, Write};
use day9::trap;
fn main() {
let mut buffer = String::new();
print!("Insert space separated heights: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Failed to read from input.");
let heights = buffer
.trim()
.split(' ')
.filter(|x| !x.is_empty())
.map(|x| x.parse().expect("A not number has been found"))
.collect();
let water = trap(heights);
println!("{}", water);
}

View File

@ -0,0 +1,11 @@
use day9::trap;
#[test]
fn exaple1() {
assert_eq!(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1].to_vec()), 6);
}
#[test]
fn exaple2() {
assert_eq!(trap([4, 2, 0, 3, 2, 5].to_vec()), 9);
}