Created
August 9, 2018 18:00
-
-
Save anthonynsimon/7297be5cdad2f312f9a6ff5b637030ba to your computer and use it in GitHub Desktop.
rust two ways
This file contains hidden or 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
use std::collections::HashMap; | |
#[derive(Hash, Eq, PartialEq, Debug)] | |
struct Item { | |
rank: u32, | |
revision: u32, | |
} | |
fn should_insert(item: &Item, acc: &HashMap<u32, Item>) -> bool { | |
match acc.get(&item.rank) { | |
Some(existing) if existing.revision < item.revision => true, | |
None => true, | |
_ => false, | |
} | |
} | |
fn main() { | |
let data = vec![ | |
Item { rank: 1, revision: 1 }, | |
Item { rank: 0, revision: 1 }, | |
Item { rank: 4, revision: 1 }, | |
Item { rank: 1, revision: 2 }, | |
Item { rank: 0, revision: 2 }, | |
Item { rank: 3, revision: 1 }, | |
]; | |
let mut result: HashMap<u32, Item> = HashMap::new(); | |
for item in data { | |
if should_insert(&item, &result) { | |
result.insert(item.rank, item); | |
} | |
} | |
println!("{:?}", result); | |
} |
This file contains hidden or 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
use std::collections::HashMap; | |
#[derive(Hash, Eq, PartialEq, Debug)] | |
struct Item { | |
rank: u32, | |
revision: u32, | |
} | |
fn main() { | |
let data = vec![ | |
Item { rank: 1, revision: 1 }, | |
Item { rank: 0, revision: 1 }, | |
Item { rank: 4, revision: 1 }, | |
Item { rank: 1, revision: 2 }, | |
Item { rank: 0, revision: 2 }, | |
Item { rank: 3, revision: 1 }, | |
]; | |
let mut result: HashMap<u32, Item> = HashMap::new(); | |
for item in data { | |
// Decide if item should be kept or discarded | |
let to_insert = match result.get(&item.rank) { | |
// Mark item for insert if key exists and revision is greater than existing | |
Some(existing) if existing.revision < item.revision => Some(item), | |
// or if key doesn't exist yet | |
None => Some(item), | |
// otherwise discard | |
_ => None, | |
}; | |
// Insert item if marked | |
if let Some(new_item) = to_insert { | |
result.insert(new_item.rank, new_item); | |
} | |
} | |
println!("{:?}", result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment