how to print an array in random order in java?
example:
int[] myArray = {5,4,3,2,1};
when printed, result should possibly be:
3 2 1 4 5
or
4 3 2 5 1
You should look at writing a Fisher-Yates shuffle. It's pretty easy to do, and efficient. Effectively you logically partition the array into a "shuffled" part and an "unshuffled part" - then repeatedly pick a random element from the unshuffled part and swap it with the first element from the unshuffled part, to make that part of the shuffled part.
Alternatively, create a List<Integer>
instead and then use Collections.shuffle
. It's unfortunate that there isn't an equivalent for arrays, but Java's type system doesn't do terribly well in terms of making either arrays or primitives generic :(
(I'm assuming you know how to do the printing side, and that it's the shuffling side which is the tricky bit for you.)
Create a new array order = {0, 1, 2, 3, 4}
and shuffle it. Then something like
for (int i: order)
System.out.print(myArray[i]);
Swap between random elements of array:
import java.util.Random;
public class JavaTest {
public static void main(String[] args) {
int[] myArray = {5,4,3,2,1};
Random random = new Random();
for (int i=0; i<20; i++) { // 20: is custom number
int i1 = random.nextInt(myArray.length);
int i2 = random.nextInt(myArray.length);
int tmp = myArray[i1];
myArray[i1] = myArray[i2];
myArray[i2] = tmp;
}
for (int i=0; i<myArray.length; i++)
System.out.print(myArray[i]);
}
}
int main(){
int array[10]={1,2,3,4,5,6,7,8,9,10};
int i,k,temp;
struct timespec spec;
long ms; // Milliseconds
/* pick a random number from 0 to 9 elements */
for (i = 9;i>0;i--){
clock_gettime(CLOCK_REALTIME, &spec);
ms = spec.tv_nsec / 1.0e6;
srand((int )ms);
temp = rand();
temp = temp % i;
printf(" %d \t ",array[temp]);
k = array[i];
array[i] = array[temp];
array[temp] = k;
}
printf(" %d \t \n ",array[0]);
return 0;
}
create an instance of the random class and then use the integer i which will be the index. where it lands, compute before element and after element length and then do the same recursively.