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();
Setis not the best data structure for random indexing.Better convert to a
Listand use a random generator to select anindex. If you really need to stay with aSet, you can generate a random indexnand iterate through theSet, stop at thenth element. For selecting multiple elements, there is no benefit of working with aList. Anyiterablewould 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 of1/N, if you didn't select it, select2nd elementwith probability1/(N-1)..and so on.Use conditional probability to show all elements are selected under a fair chance
1/N.