Generating random words in Java?

前端 未结 6 1750
抹茶落季
抹茶落季 2021-02-14 09:47

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.

publi         


        
6条回答
  •  野的像风
    2021-02-14 10:32

    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();
    }
    

提交回复
热议问题