0

I am trying to build a word-based-game application in Java. I browsed through some existing questions and got some idea how to get wordlist. Some of the questions I have referred to:

How to pick a random english word from a list

Random word selection

My motive is to generate a random word. After getting the wordlist downloaded as a text file, I am trying to generate a

Map<String, Integer> m = new HashMap<String, Integer>();

which could give me a word since I could query it using a random integer generated.

Is this a recommended approach or is there a better way to generate a random word from the wordlist?

Thanks.

Community
  • 1
  • 1
bdhar
  • 21,619
  • 17
  • 70
  • 86

3 Answers3

4

Stick the word list into an array or ArrayList, and pick a random index. ArrayList is easier to work with since it can grow dynamically as you're reading your dictionary file.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • From this post (http://stackoverflow.com/questions/1518103/hashmap-vs-arraylist-performance-am-i-correct) I could understand `HashMap` has a better performance over `ArrayList` when it comes to random retrieval. Am I wrong? – bdhar Feb 08 '11 at 13:00
  • @bdhar unfortunately, you can't get what you want from HashMap until you already have it – dhblah Feb 08 '11 at 13:02
  • @bdhar There's a difference between looking up an item by index and using an arbitrary key. Nothing beats an array (or ArrayList) for the former, which is your case. – NPE Feb 08 '11 at 13:02
  • @gasan - if the `HashMap` is like this: `new HashMap()`, the random number would be the `Integer` and I can get a random word using `HashMap.get(Integer)` right?? – bdhar Feb 08 '11 at 13:09
  • @bdhar right. But it will be unnecessary spent of performance and resources – dhblah Feb 08 '11 at 13:13
1

you could use List or even an String array and fill it with big words list and then generate random number and then select the word from the list using that random number as index.

dhblah
  • 9,751
  • 12
  • 56
  • 92
1
  1. Your proposed Map does not achieve you goal, because HashMaps allow you to access a value associated with a given key, doesn't allow you to access a key associated with value. So if you use a HashMap, it should be Map<Integer, String>

  2. The primary benefit of a HashMap over other data structures is the constant lookup time: no matter how big the map gets, the time it takes to retrieve a value for a given key stays the same. Contrast this with an unordered ArrayList where the time taken to look for an element can increase as the size of the List increases. However, since you're not looking for a specific word, just any word, the HashMap benefit doe not apply to you case.

  3. As others have said, best approach seems to be:

ArrayList words = new ArrayList();

//add all the words

Random r = new Random() //Object for generating random numbers

String randomWord = words.get(r.nextInt(words.size()));

Anas Elghafari
  • 1,062
  • 1
  • 10
  • 20