How to pull random string from a keySet?

128 Views Asked by At

I'm working on a problem in which I need to pull a random String from a keySet. Just wondering if anyone can give me some direction here. I'm pretty lost on it. I've found quite a few ways to do it if I were using an int, but not a String. For example I want to quiz a user on States and their Capitals, and to pull out a random Key from the keySet for the question. Here's the set:

Set<String> states = stateCapitals.keySet();
5

There are 5 best solutions below

0
Bing Wang On BEST ANSWER

Set is not the best data structure for random indexing.

Better convert to a List and use a random generator to select an index. If you really need to stay with a Set, you can generate a random index n and iterate through the Set, stop at the nth element. For selecting multiple elements, there is no benefit of working with a List. Any iterable would be fine.

The key idea is to dynamically adjust selection probability so you can choose m (out of sizeof(Set)): In the easiest example of m=1, select 1st element with probability of 1/N, if you didn't select it, select 2nd element with probability 1/(N-1)..and so on.

Use conditional probability to show all elements are selected under a fair chance 1/N.

0
markspace On
ArrayList<States> statesList = new ArrayList<>( states );
State x = statesList.get( (int)(statesList.size() * Math.random()) );

The code above will get what you want but this could be inefficient if it's a very large list.

0
Kas On

A keySet similar to HashSet is un-ordered and thus makes no guarantee to the order of the element in the set. So pulling a random string might not be as effective thing to do from a set.

Convert the set into arrays or list and then performing random string gets might be good solution.

1
peter On
String ranKey = map.keySet().toArray()[new Random().nextInt(map.keySet().size())].toString();
0
Pritesh Patel On

Try this code

onPress: function () {
        debugger;
        var textArray = ['Pritesh', 'Nimesh', 'Harshil', 'Ravi', 'Amit', 'Brijesh'];
        var randomNumber = Math.floor(Math.random() * textArray.length);
        for (var i = 0; i < textArray.length; i++) {
            if (i === randomNumber) {
                console.log(textArray[i]);
            }
        }