I am new to Java and am doing an exercise from a book. The task is to write a static method that takes a string array as an argument and returns a random version of the string in random order. To create a random number, you should use the following:
import java.util.Random; Random r = new Random(); int rand = r.nextInt();
My answer is this:
private static String[] jumble(String[] arr){ String [] jumbled = new String[arr.length]; int [] chosen = new int [arr.length]; Random r = new Random(); int rand = r.nextInt(arr.length); chosen[0] = rand; jumbled[0] = arr[rand]; for(int i = 1; i < arr.length; i++){ while(checkIfChosen(chosen, rand, i)){ rand = r.nextInt(arr.length); } chosen[i] = rand; jumbled[i] = arr[rand]; } print(jumbled); return jumbled; } private static void print(String[]arr){ for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } } private static boolean checkIfChosen(int[] arr, int a, int ind){ for(int i = 0; i < ind; i++){ if(arr[i]==a){ return true; } } return false; }
It works, but it seems so simple. Can anyone improve this? Any simpler ways to accomplish such a task, related to the limitations mentioned in the question?
EDIT: With Fisher Yates Shuffle:
public static void main(String[] args) { String [] original = {"Hello", "How", "Are", "You"}; jumble(original); } private static String[] jumble(String[] arr){ Random r = new Random(); for(int i = arr.length-1; i > 0; i--){ int rand = r.nextInt(i); String temp = arr[i]; arr[i] = arr[rand]; arr[rand] = temp; } print(arr); return arr; } private static void print(String[]arr){ for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } }
Great piece of code and much more efficient than my answer. Thanks.
source share