Generating random words in Java?

Mr_CryptoPrime picture Mr_CryptoPrime · Feb 10, 2011 · Viewed 67.9k times · Source

I wrote up a program that can sort words and determine any anagrams. I want to generate an array of random strings so that I can test my method's runtime.

public static String[] generateRandomWords(int numberOfWords){
String[] randomStrings = new String[numberOfWords];
Random random = Random();
    return null;
}

(method stub)

I just want lowercase words of length 1-10. I read something about generating random numbers, then casting to char or something, but I didn't totally understand. If someone can show me how to generate random words, then I should easily be able to just use a for loop to insert the words into the array. Thanks!

Answer

David Yaw picture David Yaw · Feb 10, 2011

Do you need actual English words, or just random strings that only contain letters a-z?

If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random.

If you don't need English words, then something like this will do:

public static String[] generateRandomWords(int numberOfWords)
{
    String[] randomStrings = new String[numberOfWords];
    Random random = new Random();
    for(int i = 0; i < numberOfWords; i++)
    {
        char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. (1 and 2 letter words are boring.)
        for(int j = 0; j < word.length; j++)
        {
            word[j] = (char)('a' + random.nextInt(26));
        }
        randomStrings[i] = new String(word);
    }
    return randomStrings;
}