Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates:

const sumClones = (numbers) => {
 if (Array.isArray(numbers)) {
  return numbers.reduce((acc, elem, i, arr) => {
   if (elem !== arr[i - 1]) acc.push(elem);
   else acc[acc.length - 1] += elem;
   return acc;
  }, []);
 } 
}; 

sumClones([1,1,2,1,1,1,1,2,1,1,1]) => [2,2,4,2,3]

Now, I am working on a function called reduceClones that recursively applies sumClones in order to eliminate any consecutive duplicates from the final output.

const reduceClones = (numbers) => {
  let result = sumClones(numbers);
  while (result[0] === result[1]) {
    result = sumClones(result);
  }
  return result;
};

reduceClones([1,1,2,1,1,1,1,2,1,1,1]) => [8,2,3]

Are there more efficient ways to achieve this task?

Answer №1

Utilize array destructuring in a Haskell-inspired manner with the following approach:

function addAdjacentDuplicates([x1,x2,...xs]){
  
  function addToHead(a,[b,...rest]){
    return [a+b].concat(...rest);
  }
  
  return xs.length ? x1 === x2 ? addToHead(x1,addAdjacentDuplicates([x2,...xs]))
                               : [x1].concat(addAdjacentDuplicates([x2,...xs]))
                   : x1 === x2 ? [x1 + x2]
                               : [x1, x2 || []];
}

var arr = [1,1,2,1,1,1,1,2,1,1,1,4,4,1];
console.log(JSON.stringify(addAdjacentDuplicates(arr)));

Hint: [x1,x2,...xs] as the argument of the addAdjacentDuplicates function will take an array and assign x1 to the first item, x2 to the second item, and xs to the rest of the array. The array destructuring within the arguments of the addToHead function operates in a similar way.

Answer №2

  • It is essential to always utilize pure functions.
  • Begin by working with the first element of the input array.
  • Continuously collect duplicates while they exist in the array.
  • Invoke self repeatedly until the entire input array is processed.
  • Finally, return the accumulated result as res.

function reduceConsecutiveClones(nums, res) {
  if(!nums.length) { return res || []; }
  if(!res) {
    res = [];
    nums = nums.slice();
  }
  
  let sum = first = nums.shift();
  
  while(first === nums[0]) {
    sum += nums.shift();
  }
  
  return reduceConsecutiveClones(
    nums, 
    res.concat(sum)
  );
}

function reduceClones(nums, res = reduceConsecutiveClones(nums)) {
  
  return res.toString() === nums.toString()
    ? res
    : reduceClones(res)
  ;
}


console.log(
  reduceConsecutiveClones([1,1,2,1,1,1,1,2,1,1,1]),
  reduceClones([1,1,2,1,1,1,1,2,1,1,1]) 
);

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

common mistake: using a while loop inside a foreach loop

I am completely new to php and have been struggling to find a solution on my own. Here is the snippet of code that I've been working with: $i = 0; $j = 0; $lastchange = 0; $pricearray = array(); $onlyprices = array(); foreach ($mymainlist as $key =&g ...

Incorporating JSTree Into Your Website's Heading: A Step-By-Step

I'm in search of a way to integrate the following code snippet as a JSTree into the heading section of a webpage, depicted below: <div id="jstree"> <ul> <li>Core 1 <ul> & ...

Steps for modifying material-ui timepicker to display time in a 24-hour format

Presently, I am utilizing a Timepicker from material-ui. It is currently configured with type="time", allowing me to select times throughout the day in 12-hour increments with an AM / PM choice. However, I wish to adjust my picker to a 24-hour format, elim ...

Guide on importing an external JavaScript library in Node.js utilizing a TypeScript declaration file

I am working on a Node.js project using Typescript and I am facing an issue with integrating mime.js (https://github.com/broofa/node-mime). Even though I have a declaration file available (https://github.com/borisyankov/DefinitelyTyped/blob/master/mime/mim ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

What steps can I take to make sure that the asynchronous initialization in the Angular service constructor has finished before proceeding?

Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within the class? constructor() { var sock = new SockJS(this._chatUrl); this.stompClient = Stomp.ov ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

What is the process for testing and executing the code I've written on ACE Cloud 9?

I have integrated ACE on my website to enable users to code freely. My question is, how can I execute the Python code they write? I want to add a run button in the bottom left corner (which I can style using CSS), but I'm not sure how to actually run ...

Remove multiselect label in PrimeNG

I am attempting to change the multiselect label of selected items and replace it with a static default label. Here is what it currently shows: https://i.sstatic.net/qBNHG.png This is what I have tried: .p-multiselect-label { visibility: collapse; ...

Steps for converting a pandas dataframe into a transaction matrix

I am looking to transform my pandas dataframe into a Markov chain transaction matrix import pandas as pd dict1={'state_num_x': {0: 0, 1: 1, 2: 1,3: 1,4: 2,5: 2,6: 2,7: 3,8: 3,9: 4,10: 5,11: 5, 12: 5,13: 5,14: 5,15: 5,16: 6,17: 6 ...

Steps to store a string with all characters in a JavaScript variable

I am faced with a situation where I need to pass variables that are considered Javascript objects, in a format similar to the following: var pageVars= [ { origin:'page', property:'name', value:'whatever' }, { origin:& ...

Flashing tilemap during the update process

I'm attempting to create a game map on a canvas using a JSON file produced by tiled map editor. I believe I am close to accomplishing this, but I encounter one issue. When I include the call to load the map in my update function, the map flickers on ...

Exploring the capabilities of storing and retrieving nested objects within a React database

I'm having trouble retrieving nested items from my database. This is how my database is structured: GET /dwelling/room/ [ { "room_id": 1, "room_name": "Living Room", "room_data": [ { "id": 1, ...

Which is More Effective: Cache Optimization with Hashmap or QuickSort?

If I have N unsorted arrays of integers and want to find their intersection, what is the best approach? There are two efficient methods to tackle this problem. Firstly, I can sort the arrays in place using an nlogn sorting algorithm like QuickSort or Mer ...

Transferring $scope information to resolve in $stateProvider.state

In the app.teams.show parent state, "team" is stored in $scope.data.team. From within a controller, I can access $scope.data.team and thus $scope.data.team.organization_id. The question is: How can I retrieve $scope.data.team.organization_id from inside t ...

Filtering data in a dataframe using an array of specified values

I am dealing with an array named df and a dataframe called data. The array contains unique IDs, for example: df=array([10,11,12]). The dataframe has 3 columns: data, id, value. My goal is to filter the dataframe so that it only includes IDs specified in ...

Changing the color of the timePicker clock in material-ui: a step-by-step guide

I have been attempting to update the color of the time clock in my timeInput component (material-ui-time-picker) for material-ui, but unfortunately, it is not reflecting the change. Here is the code I am using: <TimeInput style ={heure} ...

Issue with CSS: 200vw not scaling correctly for mobile devices

I'm attempting to create a horizontal slide effect between two div elements, so here is the HTML code: <div id="container"> <div class="viewport-1"> <div class="inner-div"> <h1>Viewport background 1</h1></ ...

Configuring React classes for compilation within Play

After incorporating a basic React class into my Play project at /app/assets/js: var Question = React.createClass({ render: function() { return (<div> <p>{this.props.content}</p> <br> <p>{this.props.an ...