Improving the performance of a function that generates all possible combinations of elements within an array

After coming across this function online, I decided to optimize it.

For instance, if we have an input of [1, 2, 3], the corresponding output would be

[[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Below is the code snippet:

const combinations = arr => {
  let parentValue = [];
  let cursor = 0;

  for (const parentThis of arr) {
    const value = [[parentThis]];
    for (const thiss of parentValue) {
      value.push(thiss.concat([parentThis]));
    }
    parentValue = parentValue.concat(value);
  }
  return parentValue;
};

(I apologize for the unconventional variable names; it's due to executing this as a MongoDB aggregation)

Executing this operation 10,000 times on an array consisting of 10 elements takes approximately 23 seconds. How can I enhance its performance? I'm willing to make some compromises.

One immediate enhancement I noticed was reducing the number of elements. When executed 10,000 times on an array with 9 elements, the time taken decreased to 9 seconds.

I suspect that rejecting certain outputs before they are created (such as single-element combinations and all-elements combinations which might not be very useful) could lead to further improvements, but I’m struggling to implement this in code.

I attempted to enhance the performance by eliminating the initial iteration (by providing [arr[0]] as the initialValue and commencing the outer loop from the second element), although it didn’t result in a noticeable difference.

Answer №1

It takes approximately 1 second to run through 10,000 iterations on an array containing 10 elements.

function powerset(A){
  const n = A.length;
  const numSets = (1 << n) - 1;
  const result = new Array(numSets);

  for (let k=1; k<=numSets; k++){
    const set = [];
    result[k - 1] = set;
    let temp = k;
    let i = 0;
    while (temp){
      if (temp & 1)
        set.push(A[i]);
      temp >>= 1;
      i += 1;
    }
  }
  
  return result;
}


var A = [1,2,3,4,5,6,7,8,9,10];
var start = new Date;
for (let i=0; i<10000; i++)
  var t = powerset(A);
console.log((new Date - start) / 1000);

georg suggested in the comments under this answer that replacing

const result = new Array(numSets);
with const result = []; and changing the assignment to result.push(set); could potentially improve efficiency further. This was tested on node with array sizes ranging from 15-20.

Answer №2

A slight nudge might be all that's needed to optimize the code.

// Instead of using concat method, try using the spread operator for better performance.
parentValue.push(...value);

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

Encountering a bizarre npm issue while attempting to execute npm install for brain.js

Encountering a puzzling error while attempting to install brain.js. Unsure of why Python is being mentioned during the installation process via npm, as there are no similar situations found on Google (and I'm not quite sure how to search for it). G:& ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

Is it possible to determine the outcome of a JavaScript function using Python?

I am currently in the process of creating a web crawler. Extracting links from HTML is simple, but finding links that are generated by JavaScript proves to be more challenging for me. Is there a way to access the JavaScript output in order to determine w ...

How can we determine in JavaScript whether a certain parameter constitutes a square number?

I've developed a function that can determine whether a given parameter is a square number or not. For more information on square numbers, check out this link: https://en.wikipedia.org/?title=Square_number If the input is a square number, it will ret ...

Ways to locate two div class elements that are generated dynamically

I am looking to dynamically create 2 divs in different locations. One for displaying information and another for editing information. I want to be able to delete both divs with the same class when using the delete button. Since they are located in differe ...

insert a new DOM element into an array using jQuery

Looking at the code snippet below: a_ajouter = $('.question'); hidden_div.push(a_ajouter); console.log(hidden_div); Upon examining the output in the console, instead of a DOM object being added to the div as intended, it shows &apo ...

There seems to be a problem with how the navbar is being displayed in ResponsiveSlides.js

I am currently using WordPress, but I have come here seeking help with a jQuery/CSS issue. I am utilizing responsiveSlides.js to create a simple slideshow, however, when viewing it here at gallery link, it appears that something is not quite right. STEPS: ...

Running a service in Express.js without being dependent on incoming requests

I have a backend application built using nodeJS and express. The architecture consists of two main files, app.js for handling express configuration, controllers, and MongoDB connection, and index.js strictly for server creation. Now, I am looking to imple ...

Python script using selenium webdriver to interact with an accordion container and expand its contents (round

After successfully creating a scraper, I encountered an issue where the data I needed to scrape was hidden and required manual expansion before scraping. Upon inspecting the webpage source code, I found that the data was located within 3 different accordio ...

Effortlessly move and rearrange various rows within an HTML table by utilizing JQuery alongside the <thead> elements

My JsFiddle has two tables and I want to switch rows <tr> between them using Jquery. However, due to the presence of the <thead> tag, it is not functioning properly. I suspect that the issue lies with the items in the selector, but I am unsure ...

What is the best way to transform a list of Python+Flask objects into a list of JavaScript objects?

Here's a Flask application that showcases a list of objects. from flask import * app = Flask(__name__) class Entry: def __init__(self, name, surname): self.name = name self.surname = surname entries = [] entries.append(Entr ...

Ways to get a Discord bot to echo a message?

As a novice in the world of discord.js and bot creation, I am eager to implement a simple magic 8-ball inspired command. This command will allow users to ask the bot a question and receive a random answer in response. const commands = [ new SlashCommandBui ...

Creating components and dynamic routing based on the current route

I'm in the process of creating "overview" pages for different sections within my app, each triggered from the root of that particular section. For example, localhost/hi should display the HiOverview component, And localhost/he should display the HeO ...

When using QML, functions like Object.keys, Object.values, and JSON.stringify may return unexpected empty results

I have written a code that exposes a C++ object to QML, and I want to verify the declared properties of the object using native JS methods. However, they are not working as expected. I created a method called FizzBuzzDerived.properties, which functions cor ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Reactjs - There was an error: $node.attr(...).tooltip is not defined

I am currently troubleshooting the SummerNote mention library and encountering an issue - Uncaught TypeError: $node.attr(...).tooltip is not a function The versions I am using are: - "react-summernote": "^2.0.0", - React version: "react": "^16.8.6", ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

Encountering a TypeError when utilizing a npm hashtable within an object definition

I am currently working on setting up a basic stream to read and parse JSON data and then add key-value pairs to a hashtable. My end goal is to create a module that can be utilized in another program, but as I'm troubleshooting, I've hit a roadblo ...

When using React-hook-form, you need to tap twice to delete the last character in the input field, and double tap to enter the first

I have been using React Hook Form to validate my form with multiple inputs. Everything works perfectly, except I noticed one issue where I have to press the backspace key twice to delete the last character and also twice to enter the first character. For e ...