Generating random words in Java?
Asked Answered
B

7

14

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!

Brimful answered 10/2, 2011 at 0:5 Comment(1)
random words based on what source? (e.g. random numbers + ???? = random words)Pungy
G
25

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;
}
Gawen answered 10/2, 2011 at 0:17 Comment(5)
Thanks! One thing you need to to is cast 'a' to char or else the compiler freaks out at you. Thanks everyone!Brimful
No, you don't need to cast 'a' to char, but the result of the addition (since this is automatically int). So it should be in fact word[j] = (char)('a' + random.nextInt(26));Dermatoglyphics
Thanks for the correction, it's been a while since I worked with raw characters in Java.Gawen
Haha, no problem...it took like 10secs to fix.Brimful
Random letters aren't wordsProlate
S
12

RandomStringUtils from commons-lang

Selway answered 10/2, 2011 at 0:13 Comment(1)
New link up, no longer dead.Perforated
C
5

Why generating random words? When you can use some dictionaries.

Chamade answered 10/2, 2011 at 0:11 Comment(3)
I am trying to get an average runtime, so randomly generated words should give me the best average. Also, this is for a school assignment, so I must conform to what my teacher wants...Brimful
you should have specified that, and tagged your question as "homework"Chamade
Oh, sorry I didn't even know that was a category, but I suppose that would make perfect sense. I will be sure to do that next time.Brimful
A
4

If you want to generate random words of a given length, you'll either need an algorithm to determine if a given string is a word (hard), or access to a word list of all the words in a given language (easy). If it helps, here's a list of every word in the Scrabble dictionary.

Once you have a list of all words in a language, you can load those words into an ArrayList or other linear structure. You can then generate a random index into that list to get the random word.

Argentiferous answered 10/2, 2011 at 0:13 Comment(0)
G
2

You can call this method for each word you want to generate. Note that the probability of generating anagrams should be relatively low though.

String generateRandomWord(int wordLength) {
    Random r = new Random(); // Intialize a Random Number Generator with SysTime as the seed
    StringBuilder sb = new StringBuilder(wordLength);
    for(int i = 0; i < wordLength; i++) { // For each letter in the word
        char tmp = 'a' + r.nextInt('z' - 'a'); // Generate a letter between a and z
        sb.append(tmp); // Add it to the String
    }
    return sb.toString();
}
Genesis answered 10/2, 2011 at 0:13 Comment(5)
+1 but I would suggest using StringBuilder instead of doing out += ...Brotherson
@Brotherson Wouldn't the compiler optimize his algorithm to use StringBuilder?Rascality
@Rascality I'm pretty sure it wouldn't get optimized.Mandamandaean
@Willi You are correct. Since the String concat is in a loop, the compiler will not optimize the loop operations. The compiler will try to optimize trivial String concats. Source #1532961Rascality
@Rascality U., @Willi: The compiler uses the StringBuilder, but he creates for each += a new one. This line looks after compiling like this: out = new StringBuilder().append(out).append(r.nextInt('z'-'a')+'a').toString(); – By the way, you should here convert to char again, since int + char = int, and thus your loop will append decimal numbers to the StringBuilder.Dermatoglyphics
R
1

If you want random words without using a dictionary...

  1. Make a list of all the letters you want possible in your words
  2. Generate a random index to pick out a letter from the list
  3. Repeat until you have your desired word length

Repeat these steps for the number of words you want to generate.

Rascality answered 10/2, 2011 at 0:13 Comment(0)
L
0
 public static void main(final String[] args) throws IOException {
        final var dict   = getDictionary();
        final var random = ThreadLocalRandom.current();
        final var word   = dict.get(random.nextInt(0, dict.size()));
        System.out.println(word);
    }

    private static List<String> getDictionary() throws IOException {
        Path filePath = Paths.get("/usr/share/dict/words");
        return Files.readAllLines(filePath);
    }
Lanthanide answered 9/7, 2024 at 5:34 Comment(2)
or /usr/dict/words, see en.wikipedia.org/wiki/Words_(Unix)Lanthanide
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Absinthe

© 2022 - 2025 — McMap. All rights reserved.