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

Having Trouble Parsing JSON Object with JQuery?

I'm having trouble extracting data from a valid JSON object using jQuery/JavaScript - it always returns as 'undefined'. var json = (the string below). var obj = $.parseJSON(JSON.stringify(JSON.stringify(json))); alert(obj); // aler ...

The issue of the keyboard disappearing on Chrome for Android while switching between different input

Issue with Input Switching on Chrome for Android I am facing difficulty when trying to switch between two input fields. The HTML code is as follows: <input type="text"/> <input type="text"/> When I enter text in the first input and click on ...

I am looking for a way to display or conceal text depending on the presence of an image

Could you please help me with this? I am looking for a solution where text is displayed only when there is content in the src attribute of an img tag. Essentially, I need JavaScript code that can identify if an attribute has content and then make a paragra ...

Issue with storage functionality in Vuex Axios response

Every time I send data to the Vuex storage using an axios response, for example: ** Sidebar.vue ** created(){ this.getRoles(); }, methods: { getRoles(){ var _this = this var roles = null this.$http.get('/api/userroles/ ...

Challenges with extracting and organizing dates using JavaScript regular expressions

My task involves organizing these text rows into specific groups based on certain criteria and names. Il Messaggero Roma 22 settembre 2023 Il Messaggero Roma 21 settembre 2023 Il Messaggero 22 settembre 2023 Il Messaggero 21 settembre 2023 Il Messaggero Ro ...

Implications of using literals, objects, or classes as arguments in functions that are called multiple times can have

Context A project I'm working on involves a scenario where a Shape class is triggering a function call SetPosition( x, y ) on a Drawer class. As part of this process, the Drawer class needs to retain the values (x, y) passed through SetPosition. The ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

Dark opaque background image with Material-UI styling

I'm enclosing all the widgets within a CardMedia component, and adding an image. return ( <CardMedia image={bg} className={classes.bg}> <main className={classes.content}> <div className={classes.toolbar} /> <Grid contai ...

Having trouble injecting ActivatedRouteSnapshot into the component

Struggling to inject ActivatedRouteSnapshot into a component, encountering errors when trying to access query params. Here is the error stack trace: "Error: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?). a ...

Tracking the advancement of synchronous XMLHttpRequest requests

Within the client-side environment, there exists a File-Dropzone utilizing the HTML5 File-API which allows users to drop multiple files for uploading to the server. Each file triggers the creation of a new XMLHttpRequest Object that asynchronously transfer ...

Material-UI: Error thrown when attempting to pass props to makeStyles in React due to missing property 'X' on type '{}'

Currently experimenting with Adapting based on props, you can find more information here import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ // style rule foo: props => ( ...

What could be the reason for the jquery click event not working?

When viewing default.aspx, you can click on the + symbol to increase the quantity and the - symbol to decrease the quantity. <div class="sp-quantity"> <div class="sp-minus fff"> ...

The AJAX response did not include the <script> element

Currently working on a WordPress theme where I am implementing AJAX to load new archive pages. However, encountering an issue where the entire block of Javascript code is not being included in the newly fetched content. Let's say, initially the struc ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

Retrieve all HTML dependencies, such as JavaScript and CSS files, using the same method as a web browser

I am currently working on a Single Page Application (SPA). My main objective is to evaluate the performance of the application using . Given that the application is an SPA, I want to simulate a scenario where all static content is loaded when a user firs ...

Is it possible to utilize TypeScript code to dynamically update the JSON filter with variable values?

I am dealing with a JSON filter in which the value for firmwareversion needs to be replaced with a dynamic value. Here's how I've set it up: //JSON filter this.comX200FilterValue = '{ "deviceType": "ComX", "firmwareV ...

Console warning in Next.js: "The 'style' property did not match."

Currently working on a website with Next.js, I've encountered a red color warning in the console related to the Image component from 'next/Image'. Unsure of the reason for this warning, I'm seeking to resolve it to ensure the project&ap ...

AngularJS and CodeIgniter collaborating to bring server-side pagination

I am currently working on integrating pagination using AngularJS and CodeIgniter. The current implementation requires fetching all records at once. However, I aim to modify it so that the data can be retrieved one page at a time from the server during run ...

Upgrade Angular 8 by substituting interconnected filter and order pipelines with custom functions

According to the Angular documentation Filtering and sorting operations can be resource-intensive. When Angular invokes these pipe methods frequently, it can lead to a degraded user experience, especially with even moderately-sized lists. Misuse of filt ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...