Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created June 18, 2021 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/8e0e2be5cd0824db412ddf27c9a9ed6f to your computer and use it in GitHub Desktop.
Save matthewjberger/8e0e2be5cd0824db412ddf27c9a9ed6f to your computer and use it in GitHub Desktop.
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