Currently, I am working on a function that shuffles two arrays together using recursion. The goal is to combine the top and bottom halves of a deck of cards into a single array with elements interleaved. For example:
- The first element should come from the top half
- The second element should come from the bottom half,
- The third element should come from the top half,
- The fourth element should come from the bottom half,
Any leftover elements will be appended at the end of the array.
Initially, I tried to achieve this without recursion:
function shuffleCards(topHalf, bottomHalf) {
let returnArray = [];
for (let i = 0; i < Math.max(topHalf.length, bottomHalf.length); i++) {
if (topHalf[i]) {
returnArray.push(topHalf[i]);
}
if (bottomHalf[i]) {
returnArray.push(bottomHalf[i]);
}
}
return returnArray;
}
Then, I attempted a recursive solution which looks like this:
function shuffleCards(topHalf, bottomHalf) {
let results = [];
if (topHalf.length) {
results.push(topHalf[0]);
}
if (bottomHalf.length) {
results.push(bottomHalf[0]);
}
return results.concat(shuffleCards(topHalf.slice(1), bottomHalf.slice(1)));
}
However, I keep encountering a syntax error stating "missing ) after argument list" even though I believe all parentheses are correctly placed. Any suggestions or tips would be greatly appreciated!
Thank you!