Friday, June 10, 2011

Shuffle int array java - random swapping

import java.util.Random;
import java.util.Random;

class integer {
 // this class is created to pass the array as a reference
 int array[] = { 55, 44 };
}

public class shuffle {

 public static void main(String[] args) {

  integer object = new integer();

  shuffleByRandomSwapping(object.array, 2);
  printAll(object.array);
 }

 static void printAll(int array[]) {

  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
  }

 }

 static void shuffleByRandomSwapping(int array[], int amount) {

  Random generator = new Random();

  if (array.length == 1) {
   // no meaning of swapping
   return;
  } else

   for (int i = 0; i < amount; i++) {

    if (array.length == 2) {

     if (amount % 2 != 0) {
      // just a simple swap
      int temp = array[0];
      array[0] = array[1];
      array[1] = temp;
     } else {
      // no effective swapping takes place
      return;
     }
    } else {

     int index1 = generator.nextInt(array.length);
     int index2 = generator.nextInt(array.length);

     while (index1 == index2) {
      // if index1==index2 no swapping takes place
      index2 = generator.nextInt(array.length);
     }

     int temp = array[index1];
     array[index1] = array[index2];
     array[index2] = temp;

    }
   }
 }
}

No comments:

Post a Comment