I am a beginner in Java and am doing an exercise from a book. The task is to write a static method which takes as an argument a string array and returns a jumbled up version of the string in random order. To create a random number you must use the following:
import java.util.Random;
Random r = new Random();
int rand = r.nextInt();
My answer is as follows:
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;
}
This does work but it seems so bl**dy long winded for something so simple. Can anyone improve on this? Any easier ways to implement such a task adhering to the constraints 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]);
}
}
A great piece of code and much more efficient than my answer. Thanks.
You probably just want to use the Fisher-Yates shuffle for this. It only takes one pass to do it and should produce a “fair” shuffle (assuming your random number generator has enough bits of entropy).