SkylerHill-Sky
SkylerHill-Sky

Reputation: 2206

need a random word generator using a dictionary

I'm making a hangman game, so I need a random word generator. My goal is for the user to say how many letters they want in the word and to output a random word with that many letters. I would like to use the dictionary that's supposed to be available in iOS 5. Learn from this link

How can I do this? Does anybody have some advice on a random word generator - preferably using a dictionary.

I don't want just a random text generator, I want them to be actual english words.

Upvotes: 2

Views: 5291

Answers (2)

Hot Licks
Hot Licks

Reputation: 47759

Note that, to have a decent hangman game, you really only need a dictionary of about 5000 words. If you Google "list of English words" you'll come up with a bunch of lists, and you can concatenate them (and eliminate dupes) to create your list. Then you can put them into a single file and then randomly select from the file.

Simple way to select words from the file is to put one word per "line", then use a random number to seek into the file, read and discard one line (since you may have ended up in the middle of a word), then read and use the next line. If your random number (which should be modulo the file length) causes you to hit end-of-file when you go to read the next line, use the very first line of the file.

If you want to have them selected by length, sort the words by length in your file, and, eg, have the first 300 be 4-letter words, the next 500 be 5-letter words, the next 1000 be 6-letter words. Since you know the length, you don't need to use the read-and-discard scheme -- you can calculate, for a given word length, exactly where in the file the list begins and can multiply your random number times word length + 1 (for the newline) to locate a word exactly.

(Hint: Have the first record in the file contain info on the number of lists, the word size of each list, and the number of entries in each list, so that you can refresh the word list without changing your code.)

Upvotes: 1

Richard J. Ross III
Richard J. Ross III

Reputation: 55593

Check out Lexicontext, which has dictionary definitions for many words, and has a simple API for generating a random word:

Lexicontext *dictionary = [Lexicontext sharedDictionary];
NSString *word = [dictionary randomWord];

From there, you can use the rest of the API to get definitions and such from it.

Disclaimer: I have no affiliation with Lexicontext other than being a happy customer.

Upvotes: 7

Related Questions