-12

I want to shuffle a int array with 8 element but I want that when I shuffle it array index and element on that index should not be same

My array is

int num[]={0,1,2,3,4,5,6,7,8};
Shuffel(num);
int a = num[0];  //a should not be equal to 0
int b = num[1];  //b should not be equal to 1
int c = num[2];  //c should not be equal to 2
int d = num[3];  //d should not be equal to 3
int e = num[4];  //e should not be equal to 4

Can anyone help in shuffling like this??

Jd Jatt
  • 1
  • 1
  • 3

1 Answers1

0
public static void main(String[] args) {
    int num[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };

    for (int i : num) {
        System.out.print(i + " ");
    }

    System.out.println();

    shuffleArray(num);

    for (int i : num) {
        System.out.print(i + " ");
    }
}

static void shuffleArray(int[] ar) {
    Random rnd = new Random();
    for (int i = ar.length - 1; i > 0; i--) {
        int index = rnd.nextInt(i + 1);
        if (i == index) {
            ++i;
        } else {
            int a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
        }
    }
}

This will definately work for your use case. If you in general want to avoid num[i]=i, then replace i == index with ar[i] == index || ar[index] == i, thus an endless not terminating loop is possible in some cases.

Ivaylo Toskov
  • 3,911
  • 3
  • 32
  • 48