Jumble String - Java Method

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.

+4
source share
2 answers

You probably just want to use the Fisher-Yates shuffle for this. This requires only one pass, and it must produce a "fair" shuffle (if your random number generator has enough entropy).

+4
source

Your code looks good to me. The main thing I would do is to start the for for index at 0, use the do / while loop inside it and not perform randomization and assignments before the for loop, but do it all from the for loop:

  Random r = new Random(); int rand = 0; for (int i = 0; i < arr.length; i++) { do { rand = r.nextInt(arr.length); } while (checkIfChosen(chosen, rand, i)); chosen[i] = rand; jumbled[i] = arr[rand]; } 

The do / while loop is guaranteed to run at least once, unlike the while loop, which may or may not run depending on the condition.

+1
source

All Articles