Created
June 18, 2021 04:31
-
-
Save matthewjberger/8e0e2be5cd0824db412ddf27c9a9ed6f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let mut array = Array::default(); | |
array.push(3); | |
array.push(1); | |
array.push(3); | |
array.push(2); | |
array.push(5); | |
println!("Popped: {:#?}", array.pop_max(9)); | |
} | |
#[derive(Default)] | |
struct Array { | |
items: Vec<i32>, | |
} | |
impl Array { | |
pub fn push(&mut self, item: i32) { | |
self.items.push(item); | |
} | |
// pub fn pop_max(&mut self) -> i32 { | |
// let max = self.items.iter().max().unwrap(); | |
// let position = self.items.iter().position(|&i| i == *max).unwrap(); | |
// self.items.remove(position) | |
// } | |
/// Pops parameters sent into it, returns positions of popped values | |
pub fn pop_max(&mut self, mut value: i32) -> Vec<usize> { | |
let mut positions = Vec::new(); | |
while value > 0 { | |
let max = self.items.iter().max().unwrap(); | |
let position = self.items.iter().position(|&i| i == *max).unwrap(); | |
positions.push(position); | |
let v = self.items.remove(position); | |
value -= v; | |
} | |
positions | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment