Skip to content

Instantly share code, notes, and snippets.

@Lisoph
Created December 16, 2019 11:25
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 Lisoph/3e22471e566b1ba69e0f50efd8e51ce8 to your computer and use it in GitHub Desktop.
Save Lisoph/3e22471e566b1ba69e0f50efd8e51ce8 to your computer and use it in GitHub Desktop.
BTreeMap first free key
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