I have an array called arr
, with place for 15 elements.
I need to place the numbers 1 through 15 in a random order into that array.
Here is what I have tried:
int[] arr = new int[15];
int i,j,k,n;
for (i = 0; i<15; i++) {
for (j=0; j<15; j++) {
n = (int)(Math.random() * 14 + 1);
if (rij[j] != n) {
rij[i] = n;
break;
}
}
}
Thanks! :)
Use an ArrayList and fill it up with numbers 1 to 15.
Shuffle the list.
Convert it to an array.
This will leave the elements randomly shuffled in a
Integer[]
, if that's fine with you:Do it like this
I will do something like this:
First create a temporary arraylist filled with numbers from start to end, then using random select a number, copy it into array and remove it from the temp arraylist, repeat until the arraylist is empty...
This seems like homework (or an interview question?). If that's the case and you are required to use arrays rather than the built in methods with the Java Collection Objects, (or even if not, really), the answer is the Fisher-Yates Shuffle algorithm
The modern in-place shuffle is:
(I'd have to check, but I suspect this is what Java uses under the hood for its
shuffle()
methods).Edit because it's fun to implement algorithms:
In java, this would be:
And ... this can be further optimized using the inside-out version of the algo since you're wanting to insert a known series of numbers in random order. The following is the best way to achieve what you stated as wanting to do as there are no extra copies being made such as when creating an
ArrayList
and having it copy back out to an array.