package taskspaces.rna;

/**
 * Encapsulates a method to shuffle a string using the Yates-Fischer 
 * method and a method to randomize an array of integers.
 *
 * @author      Rob Markel
 * @version     1.00
 */

public class Shuffler implements java.io.Serializable
{
   /**
    * Randomly shuffles a String using
    * the Yates-Fischer method. 
    * @param s String to be shuffled.
    * @param offset index in String to begin shuffling.
    * @param numToShuffle number of characters following offset to shuffle.
    * @return the shuffled String.
    */
   public static String shuffleString(String s,int offset,int numToShuffle) throws Exception 
   {
      char[] chars = s.toCharArray();
      if((offset + numToShuffle) > chars.length)
      {
         throw new Exception("offset + shuffle number is greater than array length");
      }
      int i = 0;
      int n = 0;
      char tmp;
      MersenneTwisterFast twister = new MersenneTwisterFast(System.currentTimeMillis());
      n = numToShuffle; 
      while(n > 1)
      {
         i = (Math.abs(twister.nextInt() % n));
         tmp = chars[offset + i];
         chars[offset + i] = chars[offset + --n]; 
         chars[offset + n] = tmp;
      } 
      return new String(chars);
   }     

   /**
    * Randomly shuffles an integer array. 
    * @param integers the array to shuffle.
    * @return the shuffled array.
    */
   public static int[] shuffleInts(int[] intArray)
   {
      for (int lastPlace = intArray.length-1; lastPlace > 0; lastPlace--)
      {
         // Choose a random location from among 0,1,...,lastPlace.
         java.util.Random myRand = new java.util.Random(10000000);
         System.out.println("putting seed 10000000 shuffler");
	 //         int randLoc = (int)(Math.random()*(lastPlace+1));
         int randLoc = (int)(myRand.nextDouble()*(lastPlace+1));
         // Swap items in locations randLoc and lastPlace.
         int temp = intArray[randLoc];
         intArray[randLoc] = intArray[lastPlace];
         intArray[lastPlace] = temp;
      }
      return intArray;
   }
}
