I successfully merged two arrays (decks of cards) without using recursion, but I'm curious to understand where I went wrong with the recursive approach

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!

Answer №1

In addition to the missing parenthesis, you have the option of selecting only the first item from the initial array and then invoking the function with the arrays swapped.

function mixCards([val, ...firstHalf], secondHalf) {
    return val === undefined
        ? [...secondHalf]
        : [val, ...mixCards(secondHalf, firstHalf)];
}

console.log(...mixCards([9, 8, 7, 6], [5, 4, 3, 2]));

Answer №2

function mixDeck(deckTop, deckBottom,shuffled = []) {
    if(deckTop.length===0&&deckBottom.length===0)return shuffled;
    if (deckTop.length!==0) {
    shuffled.push(deckTop[0])
    } 
    if (deckBottom.length!==0) {
      shuffled.push(deckBottom[0])
    }
    return mixDeck(deckTop.slice(1), deckBottom.slice(1),shuffled);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh the page with cleared cache using window.location.reload

Is there a way to reload a page using JavaScript and still clear the cache, ensuring that the refreshed page shows the latest content from the server? It seems that other browsers are not displaying the most up-to-date versions of the content. Anyone have ...

Introducing a fresh parameter to initiate and end Server Sent Events

Assistance needed. I have implemented Server Sent Events to dynamically update a website using data from a database. Now, I aim to send a new parameter ('abc.php/?lastID=xxx') back to the PHP script based on information received in the previous ...

Could not locate module: Issue: Unable to resolve './Firebase'

I'm a beginner with React and I've been working on setting up Firebase in my React application. import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; var fire ...

How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component. findId(id:number){ console.log(id) } While this function is executing, it should send the id to the following component: export class ...

Is the `beforeEach` function in Jasmine synchronized?

Is it guaranteed that multiple beforeEach functions will always run sequentially? beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); It appears they do. I conducted a tes ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Integrating JQuery with Sencha Touch: A Comprehensive Guide

Can you show me how to use JQuery with Sencha Touch? I have a Sencha button but when I click on it, nothing happens. I've checked that JQuery is working. xtype: 'button', text: 'Get result', docked: 'bottom', id: 'm ...

Tips for guaranteeing blocking within a loop in Node.JS

While I usually enjoy the asynchronous nature of Node.JS and its callback-soup, I recently encountered an issue with SQLite that required a certain part of my code to be run in a blocking manner. Despite knowing that addressing the SQLite problem would mak ...

The mysterious Vue.js and Nuxt.js custom element

Encountering an issue Seeking assistance with identifying my mistake. Attempting to create reusable components, starting with a button for example. I have created it in the file path: /components/MusicPlayer.vue: <template> <div> <v- ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

invoking a function through prototype

<script> var Nancy = function(){ this.name = 'nancy' } Nancy.prototype.getNancy = function(){ alert(this.name); } Nancy.prototype.getNancy(); function Bob(){ ...

Passport authentication leading to incorrect view redirection in Express

I'm struggling to understand why the URL is updating but leading to the incorrect view. Once a user is authenticated with passport, the URL changes to my code (/clients) but it redirects back to the homepage view. After authentication, I want the us ...

Retrieve information from a container list and save it to a file using Selenium

image description placeholderimage description placeholder My issue revolves around saving a list value to a text file. ...

Vue.js: The href attribute in a link is different from the data

Having <a> href tag below, clicking will redirect to www.duckduckgo.com, with the value of page.publicWebsite being displayed as well. {{page.publicWebsite}} shows www.duckduckgo.com. Is everything functioning correctly? https://i.stack.imgur.com/ ...

Create a function in JavaScript that generates all possible unique permutations of a given string, with a special consideration

When given a string such as "this is a search with spaces", the goal is to generate all permutations of that string where the spaces are substituted with dashes. The desired output would look like: ["this-is-a-search-with-spaces"] ["this ...

Adjusting speed dynamically within a setInterval function in JavaScript

I am working on a react application that requires displaying text with varying intervals between sentences, one at a time. To achieve this functionality, I stored all the sentences in an array and implemented a setInterval function: startShowingText() ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

Tips on resolving the Hydration error in localStorage while using Next.js

Having issues persisting context using localStorage in a Next.js project, resulting in hydration error upon page refresh. Any ideas on how to resolve this issue? type AppState = { name: string; salary: number; info: { email: string; departme ...

What is the process for selecting and accessing a DOM element?

Looking to utilize jQuery selector for accessing deep within the DOM. HTML <table> ...more here <tr> <td class="foo bar clickable"> <div> <div class="number">111</div> //Trying to retrieve "111" ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...