Created
December 16, 2019 11:25
-
-
Save haudan/3e22471e566b1ba69e0f50efd8e51ce8 to your computer and use it in GitHub Desktop.
BTreeMap first free key
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::BTreeMap; | |
fn first_free_key<V>(map: &BTreeMap<usize, V>) -> usize { | |
map.keys() | |
.zip(map.keys().skip(1)) | |
.find(|(a, b)| (*b - *a) > 1) | |
.map(|(a, _)| *a + 1) | |
.unwrap_or_else(|| map.keys().last().map(|x| x + 1).unwrap_or(0)) | |
} | |
fn main() { | |
let mut map = BTreeMap::new(); | |
map.insert(0usize, "Hi"); | |
map.insert(2usize, "Hi"); | |
map.insert(3usize, "Hi"); | |
let idx = first_free_key(&map); | |
println!("IDX: {}", idx); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment