patternjavaModerate
Shuffle the elements of the array randomly
Viewed 0 times
theelementsarrayrandomlyshuffle
Problem
I have written the code to shuffle the elements of the array. Please let me know of any loopholes in the written code.
I got his question as an assignment and want to know if it is correct or not.
package dataStructureInJava;
import java.awt.SystemTray;
import java.util.Random;
import java.util.Scanner;
public class ShuffleArr {
public static void main(String[] args){
System.out.println("Main Method Started");
int [] arr = initArr();
printArr(arr);
arr = swapArr(arr);
printArr(arr);
System.out.println("Main MEthod Ended");
}
public static int[] initArr(){
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("Enter the limit of the arr");
int limit = in.nextInt();
System.out.println("Enter the maximum value of the arr");
int maxValue = in.nextInt();
int[] arr = new int[limit];
for(int ii=0;ii<limit;ii++){
arr[ii] = rand.nextInt(maxValue);
}
return arr;
}
public static int[] swapArr(int[] arr){
Random rand = new Random();
for(int ii=0;ii<arr.length;ii++){
arr = swap(arr,ii,rand.nextInt(arr.length));
}
return arr;
}
public static int[] swap(int[] arr,int ii,int jj){
int temp=arr[ii];
arr[ii]=arr[jj];
arr[jj]=temp;
return arr;
}
public static void printArr(int[] arr){
System.out.println("Element of the arr are");
System.out.print("{");
for(int ii=0;ii<arr.length;ii++){
System.out.print(arr[ii] + " ");
}
System.out.print("}");
System.out.println();
}
}I got his question as an assignment and want to know if it is correct or not.
Solution
Naming
Spacing
You should use a lot more spaces, because they make your code easier to read.
I would at least add spaces after
- I would write
arrayout instead of shortening it toarr(it's just two more letters), because it's more readable (but I do like that you are very consistent with your shortening).
- is there a reason that you are using
ii/jjinstead of the more commonly usedi/j?
Spacing
You should use a lot more spaces, because they make your code easier to read.
I would at least add spaces after
, and ;, before {, and around all = and `Code Snippets
public static int[] swapArr(int[] arr) {
Random random = new Random();
for (int i = arr.length - 1; i >= 0; i--) {
int j = random.nextInt(i + 1);
arr = swap(arr, i, j);
}
return arr;
}public static void swap(int[] arr, int ii, int jj) {
int temp = arr[ii];
arr[ii] = arr[jj];
arr[jj] = temp;
}swap(arr, i, j);Context
StackExchange Code Review Q#79922, answer score: 10
Revisions (0)
No revisions yet.