What is the easiest way to shuffle the letters of a word which is in an array? I have some words in an array and I choose randomly a word but I also want to shuffle the letters of it.
public static void main (String[] args ) { String [] animals = { "Dog" , "Cat" , "Dino" } ; Random random = new Random(); String word = animals [random.nextInt(animals.length)]; System.out.println ( word ) ; //I Simply want to shuffle the letters of word }
I am not supposed to use that List thing. I’ve come up with something like this but with this code it prints random letters it doesn’t shuffle. Maybe I can code something like do not print if that letter already printed?
//GET RANDOM LETTER for (int i = 0; i< word.length(); i++ ) { char c = (word.charAt(random.nextInt(word.length()))); System.out.print(c); } }
Advertisement
Answer
Really no need for collection and anything more than what follows:
public static void main(String[] args) { // Create a random object Random r = new Random(); String word = "Animals"; System.out.println("Before: " + word ); word = scramble( r, word ); System.out.println("After : " + word ); } public static String scramble( Random random, String inputString ) { // Convert your string into a simple char array: char a[] = inputString.toCharArray(); // Scramble the letters using the standard Fisher-Yates shuffle, for( int i=0 ; i<a.length ; i++ ) { int j = random.nextInt(a.length); // Swap letters char temp = a[i]; a[i] = a[j]; a[j] = temp; } return new String( a ); }