patternjavaMinor
Creating an array of random numbers with no duplicates
Viewed 0 times
randomcreatingwithnumbersarrayduplicates
Problem
I only need three random numbers within the range of 1-54 (deck of cards) and none of the three numbers can be a duplicate. I cannot use an
ArrayList; I must use a standard array. Is the method I chose to check for duplicates good enough? public class Test {
public static int genRandom() {
// generate random int value between 1 and 54
int random = 1 + (int) (Math.random() * ((54 - 1) + 1));
return random;
}
public static boolean containsDuplicates(int[] arr) {
// check to see if positions have matching values
if (arr[0] == arr[1] || arr[0] == arr[2] || arr[1] == arr[2]) {
System.out.println("Duplicates Exist");
// if matching value is found, randomize the array again
shuffle(arr);
return true;
}
System.out.println("No duplicates");
return false;
}
public static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = genRandom();
System.out.println(arr[i]);
}
containsDuplicates(arr);
}
public static void main(String[] args) {
int[] cards = new int[3];
shuffle(cards);
}
}Solution
No, not a good way at all.
A similar non-recursive version
doesn't suffer stack overflow, but still may run for indefinitely long time.
As Jerry Coffin mentioned in the comment, a Fisher-Yates algorithm is a way to go.
shuffle and containsDuplicate recursively call each other without guarantee to ever stop doing that. That is the program has a certain probability to die because of stack overflow.A similar non-recursive version
public static boolean containsDuplicates(int[] arr) {
return arr[0] == arr[1] || arr[0] == arr[2] || arr[1] == arr[2];
}
public static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = genRandom();
}
}
public static void main(String[] args) {
do {
shuffle();
} while(containsDuplicates());
}doesn't suffer stack overflow, but still may run for indefinitely long time.
As Jerry Coffin mentioned in the comment, a Fisher-Yates algorithm is a way to go.
Code Snippets
public static boolean containsDuplicates(int[] arr) {
return arr[0] == arr[1] || arr[0] == arr[2] || arr[1] == arr[2];
}
public static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = genRandom();
}
}
public static void main(String[] args) {
do {
shuffle();
} while(containsDuplicates());
}Context
StackExchange Code Review Q#124124, answer score: 5
Revisions (0)
No revisions yet.