jeudi 24 mai 2018

choose a random value from a inverse weigthed map

I'm using a Map with eligible words for a hangman game I'm developing. The Integer in the Map stores the times a word has been chosen, so in the beginning the Map looks like this:

alabanza 0
esperanza 0
comunal 0
aprender 0
....

After some plays, the Map would look like this

alabanza 3
esperanza 4
comunal 3
aprender 1
....

I'd like to choose the next word randomly but having the less chosen word a bigger probability of been chosen.

I've read Java - Choose a random value from a HashMap but one with the highest integer assigned but it's the opposite case.

I''ve also thought I could use a list with repeated words (the more times a word appears in the list, the more the probabilities of been chosen) but I've only managed to get to this:

int numberOfWords=wordList.size(); //The Map
List<String> repeatedWords=new ArrayList<>();
for (Map.Entry<String,Integer> entry : wordList.entrySet()) {
    for (int i = 0; i < numberOfWords-entry.getValue(); i++) {
        repeatedWords.add(entry.getKey());
    }
}
Collections.shuffle(repeatedWords);  //Should it be get(Random)?
String chosenWord=repeatedWords.get(0);

I think this fails when the amount of words chosen equals the amount of words.




Aucun commentaire:

Enregistrer un commentaire