1

I am trying to write a shuffle method for a card game program. The method works by dividing the deck in half, then interleaving the cards from alternate halves. The issue is, the method simply keeps the array as is. Nothing is being shuffled.

/**
     * Apply a "perfect shuffle" to the argument.
     * The perfect shuffle algorithm splits the deck in half, then interleaves
     * the cards in one half with the cards in the other.
     * @param values is an array of integers simulating cards to be shuffled.
     */
    public static void perfectShuffle(int[] values) {
        int[] shuffled = new int[values.length];
        int k = 0;
        for (int j = 0; j < (values.length + 1) / 2; j++){
           shuffled[k] = values[j];
           k += 2;
        }
        k = 1;
        for (int j = (values.length + 1) / 2; j < values.length; j++){
            shuffled[k] = values[j];
            k += 2;
        }
        values = shuffled;
    }

Where's the bug?

qwerty
  • 810
  • 1
  • 9
  • 26
  • Some answers already show how to fix this. Have a look at this question for an explanation as to why your approach did not work: [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Malte Hartwig Dec 20 '19 at 02:28

2 Answers2

1

You are not re-populating the original array values with the elements of the array shuffled.

values = shuffled; will not make a copy of shuffled and assign values to it. Assuming the values array is a global variable, you should do that manually:

for(int i =0;i<shuffled.length();i++) values[i] = shuffled[i];

Rabih Jabr
  • 90
  • 10
  • Thanks, that seemed to work. However, I'm curious why ```values = shuffled;``` doesn't work. I always thought that arrays store references rather than values, the same as objects, so why can't I make one an alias of the other? – qwerty Dec 20 '19 at 02:50
  • 1
    @ap That's explained in the linked article. – steffen Dec 20 '19 at 11:20
0

Because Java passes everything by value, you need to return shuffled and assign values to the return value of the incorrectly named method perfectShuffle():

public static int[] perfectShuffle(int[] values) {
    int[] shuffled = new int[values.length];
    int k = 0;
    for (int j = 0; j < (values.length + 1) / 2; j++) {
        shuffled[k] = values[j];
        k += 2;
    }
    k = 1;
    for (int j = (values.length + 1) / 2; j < values.length; j++) {
        shuffled[k] = values[j];
        k += 2;
    }
    return shuffled;
}

and

public static void main(String[] args) {
    int[] values = { 1, 2, 3, 4, 5 };
    int[] shuffled = perfectShuffle(values);
    // ...
}
steffen
  • 16,138
  • 4
  • 42
  • 81