How would I shuffle a static array of 52 cards that you input an
integer, n, into a function and it takes the first n cards as the left
segment and the remaining as the right. Then it shuffles this deck
starting from the first of the right segment, then first of the left,
second of the right, second of the left. Once one side is exhausted it
fills in the rest of the shuffle with the other remaining segment. Any
suggestions?
This is more of an algorithms problem than a C++ problem, but it was fun
to think about. First, are you allowed to use external storage? If so
the problem becomes pretty easy. Just follow the algorithm outlined in
opalpa's response.
If, however, you need an "in place" algorithm, things get a little bit
more complicated. I propose the following algorithm for when the total
number of cards is a power of 2. Fixing it to work with any number of
cards is an implementation detail I'll leave to you. The intuition is
as follows. When the algorithm completes, the first half of the array
will be composed of the first and third quarters of the original array.
Likewise, the last half of the array will be composed of the second and
fourth quarters of the original array. So, for our first step we'll
swap the second and third quarter. We've now reduced the problem into
two problems of half the size. The base case in this algorithm is a
problem of size 2, which is correctly shuffled without doing anything.
So, the whole algorithm looks like:
Shuffle(array A)
if (size of A > 2)
swap(second quarter of A, third quarter of A)
Shuffle(first half of A)
Shuffle(second half of A)
How fast is it? The swap takes O(N) time (where N is the total number
of cards). And you have two subproblems of size N/2. So, by the Master
Theorem the running time is bounded by O(N log N).
If you have a specific problem with implementing this (or whatever
solution you choose) in C++, come back and I'm sure someone will be
happy to help further.
-Alan