How to choose a random element from a Gee.HashSet?

To choose a random element from a Gee.HashSet I’m doing this:

// var s = new Gee.HashSet<string>(); // populate s;
int j = s.size == 1 ? 0 : Random.int_range(0, s.size - 1);
int i = 0;
foreach (var x in s) {
    if (i == j)
        return x;
    i++;
}
assert_not_reached();

But is there a better way?

I have also tried this which seems to work – is this the best way?:

// var s = new Gee.HashSet<string>(); // populate s;
var array = (string[]) s.to_array(); // cast needed to get rid of warning
int j = array.length == 1 ? 0 : Random.int_range(0, array.length - 1);
return array[j];

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.