Estoy intentando escribir una función que tome dos matrices como entradas, que representen las mitades superior e inferior de una baraja de cartas, y las mezcle usando recursividad. Estoy intentando devolver una sola matriz que contiene los elementos de ambas matrices de entrada intercaladas, así:
...etc.
Quiero agregar los elementos restantes al final de la matriz.
Así es como lo resolví sin recursividad:
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 }
y este es mi intento con la recursividad:
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))); }
Sigo recibiendo el error de sintaxis "falta) después de la lista de argumentos", pero estoy bastante seguro de que todos los paréntesis están en el lugar de escritura.
¿Algun consejo?
¡Gracias!
Además de los paréntesis faltantes, podría tomar solo el primer elemento de la primera mitad y llamar a la función con matrices intercambiadas.
function shuffleCards([value, ...topHalf], bottomHalf) { return value === undefined ? [...bottomHalf] : [value, ...shuffleCards(bottomHalf, topHalf)]; } console.log(...shuffleCards([1, 2, 3, 4], [5, 6, 7, 8]));
function shuffleCards(topHalf, bottomHalf,results = []) { if(topHalf.length===0&&bottomHalf.length===0)return results; if (topHalf.length!==0) { results.push(topHalf[0]) } if (bottomHalf.length!==0) { results.push(bottomHalf[0]) } return shuffleCards(topHalf.slice(1), bottomHalf.slice(1),results); }