/**
 * How to shuffle effectively.
 *
 * @author Zach Tomaszewski
 */
public class ShuffleExample {

  /**
   * Generates an int array and shuffles it, printing the results
   * to the screen.
   */
  public static void main(String[] args) {

    //create an ordered, sample array of ints
    int[] sample = new int[20];
    for (int i = 0; i < sample.length; i++) {
      sample[i] = i;
    }

    System.out.println("BEFORE:");
    printArray(sample, sample.length);

    //shuffle it
    shuffle(sample);

    System.out.println();
    System.out.println("AFTER:");
    printArray(sample, -1);

  }


  /**
   * Shuffles the given int[] using the Fisher-Yates shuffle algorithm.
   * <p>
   * See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle for more.
   */
  public static void shuffle(int[] numbers) {

    for (int i = numbers.length - 1; i > 0; i--) {
      int select = (int) (Math.random() * (i + 1)); //0 <= select <= i

      //swap current value with selected value
      int temp = numbers[i];
      numbers[i] = numbers[select];
      numbers[select] = temp;

      //uncomment next line to see shuffle at work
      //printArray(numbers, i - 1);
    }
  }

  /**
   * Prints the given numbers array on line line, placing a '|'
   * char between index div and div + 1.
   */
  public static void printArray(int[] numbers, int div) {
    for (int i = 0; i < numbers.length; i++) {
      System.out.print(numbers[i]);
      if (i == div) {
        System.out.print("|");
      }else {
        System.out.print(" ");
      }
    }
    System.out.println();
  }

}