AdSense

Wednesday, March 18, 2015

Shuffle cards

The idea is much easier than it actually is. If we are at element i, randomly select an index from (i, array.length - 1), swap value of i and index. Iteratively perform this operation until all elements are selected.


public static void shuffleArray(int[] cards){
  int index;
  for(int i = 0; i < cards.length; i++){
   index = (int)(Math.random() * (cards.length - i)) + i;
   swap(cards, i, index);
  }
 }
 private static void swap(int[] cards, int i, int j){
  int tmp = cards[i];
  cards[i] = cards[j];
  cards[j] = tmp;
 }

 public static void main(String[] args) {
  int n = 10;
  int[] array = new int[n];
  for(int i = 0; i < n; i++)
   array[i] = i + 1;
  shuffleArray(array);
  for(int i : array){
   System.out.print(i + " ");
  }
  System.out.println();
 }

No comments:

Post a Comment