How can one get a random key from an UnorderedMap in NEAR Rust SDK?
How to select a random key from an UnorderedMap in NEAR Rust SDK?
472 views Asked by user702991 At
2
There are 2 answers
2
On
If you know you key space then you can use near_sdk::env::random_seed() to generate a random seed and use that to get any key from the unordered_map.
https://docs.rs/near-sdk/latest/near_sdk/env/fn.random_seed.html
For Example:
If you have a Unordered_map<u64, Some_Struct>
The You generate a seed and convert it from Vec which random_seed() gives to u64
let randomId = u64::from_be_bytes(env::random_seed())
And get this from unordered_map as
unordered_map.get(&randomId).unwrap()
Not the most efficient way but you can try this. Open to better solutions.
If performance is not a concern for you, the simplest and most obvious way to do that is to use the keys_as_vector() method on the map and then get a random element from it via the choose() method in the
randcrate.Example:
Clearly, the bigger your map, the slower this is gonna be.