0

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();
  • You can't do random indexing on a Set, but you could use `toArray()` (or `new ArrayList()`) to get a list. If the set is very large this may be inefficient though. – markspace Feb 17 '21 at 04:46
  • 1
    Does this answer your question? [Picking a random element from a set](https://stackoverflow.com/questions/124671/picking-a-random-element-from-a-set) – SRJ Feb 17 '21 at 04:59

5 Answers5

3

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.

SRJ
  • 2,092
  • 3
  • 17
  • 36
Bing Wang
  • 1,548
  • 1
  • 8
  • 7
1

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.

Kas
  • 21
  • 3
0
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.

markspace
  • 10,621
  • 3
  • 25
  • 39
0
String ranKey = map.keySet().toArray()[new Random().nextInt(map.keySet().size())].toString();
peter
  • 81
  • 2
  • 1
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained. – Amit Verma Feb 17 '21 at 05:47
0

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]);
            }
        }