How to select a random key from an UnorderedMap in NEAR Rust SDK?

472 views Asked by At

How can one get a random key from an UnorderedMap in NEAR Rust SDK?

2

There are 2 answers

0
at54321 On

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 rand crate.

Example:

use rand::thread_rng;
use rand::seq::SliceRandom;

let keys = my_map.keys_as_vector();
let random_key = keys.choose(&mut thread_rng());
println!("{:?}", random_key);

Clearly, the bigger your map, the slower this is gonna be.

2
PRINCE ANURAGI 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.