Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array.

Please define the type of the function and provide a minimum of 3 tests using assert to ensure functionality. The function should be written in a functional programming style using Javascript/Typescript.

For example: FunSubsets ([1,2,3],2) => [[1,2],[1,3],[2,3]]

Open to any ideas!

Answer №1

One potential solution is to implement a generator function that includes an additional parameter for storing the temporary result set.

function* subsets(values, size, parts = []) {
    var i;

    size--;
    for (i = 0; i < values.length; i++) {
        if (size) {
            yield* subsets(values.slice(i + 1), size, [...parts, values[i]]);
        } else {
            yield [...parts, values[i]];
        }
    }
}

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

Answer №2

Iterate through the array and for each element, iterate again to create a slice with the length k - 1. Concatenate it with the current element of the first loop and add it to a temporary array that is returned in the end.

let myArray = [1, 2, 3, 4];

let kValue = 2;

function findSubSets(arr, k) {

  let tempArray = [];
  for (var i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      let slice = arr.slice(j, j + k - 1);
      slice.push(arr[i]);
      tempArray.push(slice.reverse());
    }
  }
  return tempArray;
}

let foundSubSets = findSubSets(myArray, kValue);

console.log(JSON.stringify(foundSubSets));

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

Center the text within the div and have it expand outwards from the middle if there is an abundance of text

I have a div that is in the shape of a square box and I want it to be centered. No matter how much text is inside, I would like it to remain in the middle. I am using JQuery to create my square box and would like to center it using CSS. Here is my code: &l ...

Function that returns an array

Hey there, wondering about variable scope in closures! I've come across a lot of questions on this topic but haven't found the solution to my issue. Here's the code snippet: var teams = []; var players = []; var getRoles = function(roleL ...

Angular Square Grid Design

Attempting to create a square grid layout using CSS for ng-repeat items. Essentially, I am looking to have one big square followed by four smaller squares that combined have the same width and height as the big square. Here is my CSS: .container{ widt ...

Error encountered: Cordova plugins return undefined values when testing on an actual device

I am currently utilizing Phonegap in conjunction with ngCordova and AngularJS. The aim is to leverage the capabilities of the plugin (PhoneGap-Image-Resizer) to facilitate media saving on the device. However, I encountered an issue where the plugin throws ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

Refresh a Google chart without having to reload the entire page

I currently have a button that allows me to refresh the data on my page in case there is new data available through an API. Although this button successfully refreshes my datatable, it does not redraw the Google charts I have integrated into my project usi ...

jQuery Ajax Redirect Form

I am currently developing an HTML application with a form. Upon clicking the submit button, I initiate a server-side call using jquery.ajax(). However, when the server returns an exception, such as a Status Code 500, I need to display an error message on t ...

The or operator in Typescript does not function properly when used as a generic argument

My current configuration is as follows: const foo = async <T>(a): Promise<T> => { return await a // call server here } type A = { bar: 'bar' } | { baz: 'baz' } foo<A>({ bar: 'bar' }) .then(response =& ...

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code. The first problem is that although t ...

`Need help setting the active class for a bootstrap navbar using Angular JS?`

In my bootstrap navbar, I have the following menu items: Home | About | Contact I'm looking to assign the active class to each menu item based on the current angular route. Specifically, how can I set class="active" when the angular route is at # ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

Updating the quantity of a product within a state in React allows for easy manipulation of that

My scenario involved attempting to reduce the quantity of a product object in the UI by clicking a button, but the quantity did not update as expected. What is the recommended course of action in situations like this? let product={ a:1,b:2,c:3}; For examp ...

Manipulate the DOM to remove a checkbox using JavaScript

I'm brand new to exploring the world of Javascript and could use some guidance with this task. I have a collection of checkboxes that I'd like to manipulate so that when one is checked, it disappears from the list automatically. I've come ac ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Integrate a fresh global JSX attribute into your React project without the need for @types in node_modules

It is crucial not to mention anything in tsconfig.json. Error Type '{ test: string; }' cannot be assigned to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'test' does not exi ...

Guide on using JSZip and VUE to handle an array of promises and store them in a local variable

My lack of experience with async functions has me feeling a bit lost right now... I'm attempting to loop through files in a folder within a zip file using JSZip, store these files in an array, sort them, and then save them to a local variable for furt ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...