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

Attempting to rename the "like" button in Django Ajax, however encountering difficulties

My button is currently functioning, but it's embedded within a Django for loop. I want to move the JavaScript logic to a separate file, but before that, I need to rename it appropriately. Check out this excerpt from my code: {% for post in posts %} ...

Extracting information from a JSON file using the array name provided in the URL

Currently, I am facing an issue with printing data in JSON format from my 'data.json' file. In my PHP file (alldata.php), I have successfully managed to obtain all the data (arrays) and print them out in a pretty format. However, my challenge lie ...

Refresh the webpage source code for an AJAX request

When using AJAX calls on a page, I have noticed that the page source remains unchanged. This can be problematic if a user performs forward/backward operations in their browser, as the browser will display the original HTML code instead of the updated conte ...

Need help accessing data from an API using Axios.post and passing an ID?

Can someone help me with passing the ID of each item using Axios.Post in order to display its data on a single page? The image below in my Postman shows how I need to send the ID along with the request. Additionally, I have the first two URL requests for t ...

Sort values depending on the value of another key

I have a list of different types: const types = ['BAKERY', 'FRUITS', 'RESTAURANT', ...]; The length of this array is not fixed. Additionally, I also have a corresponding category list for each type as shown below: const categ ...

Removing sourceMappingURL from an Angular Universal build: A step-by-step guide

Using this repository as my foundation, I have successfully resolved most of the plugin errors except for one that continues to elude me. It's puzzling because no other plugin anticipates a .map file in an SSR build since it is intended for productio ...

Using Laravel and VueJS to send an array to the controller using Axios

I've developed a Laravel 5.4 application combined with VueJS 2.0 for the frontend. The issue I'm facing is that after populating the visitors array on the page and trying to post it to the controller, the data seems to disappear upon returning f ...

ng-class remains stagnant as ng-if dynamically updates when tab is no longer in focus

Implementing an interceptor to display a loader while making API calls can come with its challenges. In this case, two API requests are set at intervals of every 60 seconds using $interval. When the page is in focus, the loader functions correctly by showi ...

The act of transmitting data via a timer using JS WebRTC leads to crashes if the page is reloaded before

In one of my server.js files served by a node, I have written the following code snippet: function multiStep(myConnection, data) { var i=0; var myTimer=setInterval(function() { if (i<data.length){ var element=JSON.string ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

I am looking to show images based on the number chosen from the dropdown menu in CodeIgniter

When a number is selected from the dropdown menu, I want to display images accordingly. The options in the dropdown are 9, 12, and 18. Here is the code snippet for my view page: <form action="<?php echo base_url();?>roxcontrol/numberdisplay" id=" ...

Remove a field from a JSON array

Consider the following JSON array: var arr = [ {ID: "1", Title: "T1", Name: "N1"}, {ID: "2", Title: "T2", Name: "N2"}, {ID: "3", Title: "T3", Name: "N3"} ] Is there a way to remove the Title key from all rows simultaneously without using a loop? The r ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} https://i.sstatic.net/1AnDi.png I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="displa ...

Generate a duplicate of a particular row of results

What is the best way to duplicate an array that contains other associative arrays within it? For example, if I have a result set returned from a mysql_fetch_assoc. Here's the setup... connect $result = query; while ($row = mysql_fetch_assoc($result ...

Decoding the Blueprint of Easel in JavaScript

Recently, I came across a fantastic API that promises to simplify working with CANVAS by allowing easy selection and modification of individual elements within the canvas. This API is known as EaselJS, and you can find the documentation here. While I foun ...

Encountering Vue linting errors related to the defineEmits function

I am encountering an issue with the linting of my Vue SPA. I am using the defineEmits function from the script setup syntactic sugar (https://v3.vuejs.org/api/sfc-script-setup.html). The error messages are perplexing, and I am seeking assistance on how to ...

Display a div element with Angular's ng-show directive

I am encountering difficulties with implementing ng-show and $pristine. Below is the code snippet (also available on CodePen): <blockquote ng-show="!comment.author.$pristine && !comment.rating.$pristine && !comment.comment.$pristine"&g ...