Wrote program for Day 9
This commit is contained in:
parent
6ee3c88c30
commit
7c5fdc5242
6
Week-02/Day-09_Trapping-Rain-Water/day9/Cargo.toml
Normal file
6
Week-02/Day-09_Trapping-Rain-Water/day9/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "day9"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
26
Week-02/Day-09_Trapping-Rain-Water/day9/src/lib.rs
Normal file
26
Week-02/Day-09_Trapping-Rain-Water/day9/src/lib.rs
Normal 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
|
||||
}
|
24
Week-02/Day-09_Trapping-Rain-Water/day9/src/main.rs
Normal file
24
Week-02/Day-09_Trapping-Rain-Water/day9/src/main.rs
Normal 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);
|
||||
}
|
11
Week-02/Day-09_Trapping-Rain-Water/day9/tests/exaples.rs
Normal file
11
Week-02/Day-09_Trapping-Rain-Water/day9/tests/exaples.rs
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user