The shuffle method in ShuffleMethods.java takes an array of ints and shuffles them by chunks of int
s in another array. So for example, if we had an array of ints called nums comprising of 0,1,2,3,4,5 and a chunks of ints of 2,1,3. The method reads the first element of the chunks array which is 2. The shuffle method then gets the first two elements of the nums array 0 & 1 and puts them at the end of the array to give this result: 2,3,4,5,0,1, Then for the next chunks of 1 the number is 2 is selected and put on top of the 0,1 giving this result 3,4,5,2,0,1. And then finally the last chunks of 3 selects 3, 4, 5 and puts them on top of the 2 giving this result 3,4,5,2,0,1.
The shuffle method algorithm complexity is currently \$O(n^3)\$. I am looking to get it down to \$O(n)\$. Also, I am hoping to improve the pairs method which finds the number of consecutive numbers from the original deck that are still together in the shuffled deck.
ShuffleApp.java
package Shuffle;
import java.util.Arrays;
public class ShuffleApp{
public static void main(String[] args){
ShuffleMethods test = new ShuffleMethods();
int[] test1 = {2, 1, 3};
test.makeNew(6);
test.shuffle(test1);
test.pairs();
test.print();
}
}
Shuffle.java
package Shuffle;
public interface Shuffle{
public void makeNew(int size);
public int[] getCurrent();
public void shuffle(int[] chunks);
public int pairs();
}
ShuffleMethods.java
package Shuffle;
import java.util.*;
public class ShuffleMethods implements Shuffle{
private int[] nums;
private int[] numsCopy;
/**Fills nums with ints based on user parameter from 0 to size-1**/
public void makeNew(int size){
nums = new int[size];
for(int i = 0; i < size; i++){
nums[i] = i;
}
numsCopy = nums.clone();
}
public int[] getCurrent(){
return nums;
}
/**Shuffles the ints**/
public void shuffle(int[] chunks){
int temp = 0;
int count = 0;
int endIndex = nums.length;
count = 0;
while(chunks[i] > count) {
temp = nums[0];
for(int k = 1; k < endIndex; k++) {
//Move all the elements back
nums[k-1] = nums[k];
}
nums[endIndex-1] = temp;
count++;
}
endIndex -= chunks[i];
}
}
/**Returns the number of pairs of consecutive numbers in the shuffled deck that were together in the original**/
public int pairs(){
ArrayList<Integer> pairList = new ArrayList<Integer>();
int pairs = 0;
for(int i = 1; i < numsCopy.length; i++) {
if (numsCopy[i-1] == numsCopy[i] - 1 && !pairList.contains(numsCopy[i-1]) && !pairList.contains(numsCopy[i])) {
pairList.add(numsCopy[i-1]);
pairList.add(numsCopy[i]);
}
}
for(int i = 1; i < nums.length; i++) {
if (nums[i-1] == nums[i] - 1 && pairList.contains(nums[i-1]) && pairList.contains(nums[i])) {
pairList.remove(Integer.valueOf(nums[i-1]));
pairList.remove(Integer.valueOf(nums[i]));
pairs++;
}
}
System.out.println("Number of pairs " + pairs);
return pairs;
}