简体   繁体   中英

How does it works? Shuffling Array

I am trying to understand shuffling arrays in java. I do understand how it works

for(int i=myList.length-1; i>0; i--) {
        int j = (int) (Math.random() * i +1);
        double temp = myList[i];
        myList[i]=myList[j];
        myList[j]=temp;
        System.out.print(myList[i]);

but I am lil confused about this part

int j = (int) (Math.random() * i +1);

it can create same numbers for ex:

122512111

So how it works and swaps indexes if it has same numbers.

Your code is fine, no need to worry.

Here I try to explain you int j = (int) (Math.random() * i +1); in individual part:

  1. Math.random() :-> gives you random number in float between 0 to 1.

  2. Math.random() * i :-> multiply with i(index) so number don't stay in between range 0 to 1 and range will become 0 to myList.length-2

  3. (Math.random() * i +1) :-> increment our random number with 1, so range will become 0 to myList.length-1

  4. (int) (Math.random() * i +1); :-> convert our number from float to int

**all above range is inclusive of the start and end number:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM