What is the reason my answer for the powerset problem is flawed? Both my recursive and iterative methods are attached for review

How can I generate all possible subsets from an array of unique integers?

For instance, if I have powerSet[1,2,3], the expected output should be

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

I've tried a recursive approach:

function powerset(array) {
    let set = [[]];
    powersetHelper(array, [], set);
    return set;
}

function powersetHelper(array, subset, set) {
    if (array.length === 0) return;
    for (let i = 0; i < array.length; i++) {
        subset.push(array[i]);
        set.push(subset);
    }
    let newArr = array.slice(1);
    powersetHelper(newArr, [], set)
}

However, this is not providing the correct solution and instead returning

[[], [1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 3], [2, 3], [3]]
. What am I doing wrong?

I also attempted an iterative solution:

function powerset(array) {
    let subset = [];
    let set = [[]];
    while (array.length > 0) {
        for (let j = 0; j < array.length; j++) {
            let num = array[j];
            subset.push(num);
            set.push(subset);
        }
        array = array.slice(1);
    }
    return set;
}

Surprisingly, this implementation is giving me a similar incorrect result as seen below. Despite following a similar logic to my recursive function, it's still producing unexpected output:

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

Answer №1

To avoid referencing the original object, you must create a copy.

function generatePowerSet(array) {
    // Implement your solution here.
    let powerSet = [[]];
    helper(array, [], powerSet);
    return powerSet;
}

function helper(array, subset, powerSet) {
    if (array.length === 0) return;
    for (let i = 0; i < array.length; i++) {
        subset.push(array[i]);
        powerSet.push([...subset]); // Create a copy without reference
    }
    let newArray = array.slice(1);
    helper(newArray, [], powerSet)
}

console.log(generatePowerSet([1, 2, 3])); // [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another approach with the same issue

function generatePowerSet(array) {
    // Implement your solution here.
    let subset = [];
    let powerSet = [[]];
    while (array.length > 0) {
        for (let j = 0; j < array.length; j++) {
            let num = array[j];
            subset.push(num);
            powerSet.push([...subset]);
        }
        array = array.slice(1);
    }
    return powerSet;
}

console.log(generatePowerSet([1, 2, 3])); // [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Reasons for storing `https.get()` inside a request constant in Node.js

When using simple javascript, any content written to the console is displayed on the console itself. An example would be as follows: const name = "david"; This will display david in the console. However, in Node.js, if I store a request in a const varia ...

The Best Way to Refresh a ReactJS Component in Plain HTML/JavaScript

So here's the situation. I'm diving into creating a React Modal component that can seamlessly integrate with any vanilla HTML / JS file. By generating a bundle.js file using Webpack from my React component, it becomes easier to inject it into a d ...

The text of the keyword in AdGroupCriterionService remains unchanged

I've been utilizing the GoogleAds Node Module from https://www.npmjs.com/package/googleads-node-lib. I have successfully managed to modify the Tracking Template and the CpcBid microAmount, however, I am facing an issue with changing the keyword text. ...

Troubleshooting $digest problems with AngularJS and the selectize directive

I am encountering difficulties when utilizing the watch function within a directive in conjunction with a third-party plugin named selectize. Despite researching extensively about $digest and $watch, I am still facing issues. Although my example below is ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

Finding the average value of a multi-dimensional array using just one loop

I'm working on a piece of code that removes parameters from each URL in an array. It then calculates scores for each matched URL-keyword pair and needs to compute the average value of the 'position' attribute. Everything is functioning corr ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Implementing Multiple HTML Files Loading in QUnit

Currently, I am utilizing QUnit for unit testing JavaScript and jQuery. The structure of my HTML document is as follows: <!DOCTYPE html> <html> <head> <title>QUnit Test Suite</title> <script src="../lib/jquery.js">< ...

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

What is the correct way to display the date in a React application?

I am working on a project that involves integrating solidity contracts into a web portal. In one of the contracts, I have stored dates as uint values like this: 1539491531. However, when I display these dates on the web page, they appear different from wh ...

"Error: The req.body object in Express.js is not defined

edit:hey everyone, I'm completely new to this. Here's the html form that I used. Should I add anything else to this question? <form action="/pesquisar" method="post"> <input type="text" id="cO" ...

Exploring the capabilities of data processing in Node.js

I've been attempting to read data from a locally stored JSON file, organize it into individual JS objects, and add them to a queue. However, I'm struggling to find a way to test my parsing function to ensure it's functioning correctly. My cu ...

Ways to eliminate the relationship between parent and child

I am attempting to create a design featuring a large circle surrounded by smaller circles. The parent element is the large circle, and the small circles are its children. My goal is for any circle to change color to red when hovered over, but if I hover ov ...

Brochure displaying shattered tiles using ionic

Whenever I try to load a map using Ionic, it keeps displaying broken tiles. No matter if I load directly from Leaflet or use bower, the issue persists. Even when using pure leaflet code without any special directives, those broken tiles are still there. ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Refining a JQuery scroll animation using mouseover functionality

I came across a JQuery scroll animation (inspired by this specific answer to a similar question that almost perfectly suited my requirements), and I managed to get it working. My goal is to achieve a side-scroll effect of icons when the user hovers over th ...

Only refresh the content when there are updates from the ajax call

Currently, I am populating an HTML table with data retrieved through an AJAX request. The AJAX call is made at regular intervals of X seconds. I am specifically looking for a way to update the table only when the new data fetched from the AJAX call diffe ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Dynamic form name validation in Angular is crucial for ensuring the accuracy and

When it comes to validating a form in Angular, I usually use the ng-submit directive like this: <form name="formName" ng-submit="formName.$valid && submitForm()"></form> This method works well for forms with predefined names that I se ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...