Searching for all potential arrays of length L that total N or fewer can be achieved using an algorithm

In JavaScript, I am looking for a way to discover all potential arrays - consisting of non-negative integers - with a size L that add up to - at most - N:

function findArrays(size, maxSum){}

For example: findArrays(3, 2)

Sample output:

[[0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [0,2,0], [1,0,0], [1,0,1], [1,1,0], [2,0,0]]

What I have attempted:

I devised the following strategy:

  • Starting from the left, add up the array elements
  • If the sum is equal to N at position i:
    • If the element at the current index is equivalent to N, reset all the indices prior and increment the subsequent slot
    • Otherwise: reset previous slots and increment this position
  • Else:
    • Increase the first available slot

My code snippet:

let getNextArray = (r,L,N)=>{
    let sum=0, ind=0, i;
    for(i=0; i<L; i++){
        sum += r[i];
        if(sum===N){
            ind = i + (r[i]===N?1:0);
            break;
        }
    }
    r[ind]++;
    for(i=0; i<ind; i++){
        r[i]=0;
    }
    return r;
};

let findArrays=(L, N)=>{
    let arrays=[],r=[],i;
    for(i=0; i<L; i++){
        r[i] = 0;
    }
    while(r[L-1]<N){
        r = getNextArray(r,L,N);
        arrays.push(r.slice());
    }
    return arrays;
}

While it works for the given input, when calling it with findArrays(5,3), only half (28 / 56) of the solutions are found. Despite my efforts, I suspect it may not be efficient for larger inputs as it computes the sum each time. There has to be a smarter way to achieve this that eludes me..

Previously, I posed a similar question on a more optimal approach, but now I require fixed size arrays. My apologies for the repetition in questioning, yet potentially beneficial for future reference :)

An alternative approach could involve utilizing a method findArrays(size, sum) and iterating through sums 1:N, although my knowledge falls short on implementing this.

Answer №1

If you want to enhance trincot's solution, consider adding a simple filter function at the end like this:

function generateSubarrays(maxSize, maxSum) {
  let arr = [];
  let result = []; // This array will store all the subarrays

  function recursion(total) {
    let k = arr.length;
    result.push([...arr]);
    if (k === maxSize) return;
    for (let i = 0; i <= maxSum; i++) {
      arr[k] = i;
      recursion(total - i);
    }
    arr.length = k;
  }

  recursion(maxSum);
  return result.filter(({ length }) => length === maxSize);
}

// Example
for (let array of generateSubarrays(3, 2))
  console.log(JSON.stringify(array));

Answer №2

Below is a modified version of a recursive function that provides the desired output. It calculates all potential values at the current level (0..maxSum) and then adds them to the possible results for arrays with size-1:

const calculateArrays = (size, maxSum) => {
  let possibilities = Array.from({
    length: maxSum + 1
  }, (_, i) => i);
  if (size == 1) return possibilities;
  
  let results = [];
  possibilities.forEach(p => {
    calculateArrays(size - 1, maxSum - p).forEach(arr => {
      results.push([p].concat(arr));
    });
  });
  
  return results;
}

console.log(calculateArrays(3, 2));

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

Is it possible to send data to the server in node.js before the page is loaded?

Once a user has logged in, their data is stored on the client side. There are certain pages that can be viewed without requiring a user to log in... For instance, I have created a route on node.js which generates a profile page based on a URL parameter. ...

Manipulating webpage content with JavaScript

How can I provide visual feedback to a user while an ajax request is in progress? For example, when a user clicks a 'process' button that triggers an AJAX request to a server-side script, they should see a 'loading...' message and a gra ...

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

What sets apart .create from .save in mongoose?

A while ago, I completed a bootcamp course on Express and Mongoose on Udemy. In the course, we learned how to add new fields to data by writing code like this: var playground = require("../models/playground.js"); route.post("/", middleware.isLoggedIn,fun ...

Confirming the structure of a URL using JavaScript/jQuery

I have a text field where users input URLs. I need to validate the format of the URL using regular expressions. Specifically, I am looking for invalid URLs such as: http://www.google.com//test/index.html //Invalid due to double slash after hostname http: ...

Creating a function while utilizing this conditional statement

Seeking guidance as I work on defining an 'explode' function. This function is intended to take a string input and insert spaces around all letters except the first and last ones. For example, if we call the function with the string Kristopher, i ...

A guide on breaking down a URL string containing parameters into an array with the help of JavaScript

I need help splitting a long string into an array with specific index structure like this: fname=bill&mname=&lname=jones&addr1=This%20House&... I am looking to have the array set up as shown below: myarray[0][0] = fname myarray[0][1] = b ...

Sending search queries from a frontend built with React.js to a backend in Express.js: What is the best approach?

I have been attempting to develop a basic search bar using react.js that will communicate with my express.js backend in order to retrieve the accurate data from the database and display it on the front-end. However, I am struggling to grasp how to transmit ...

Displaying the specified item within an array using AngularJS

My application features a group of 'players' each with their own unique attributes that I want to showcase within a modal window and cycle through. The user interface is structured like this: <!-- Score Round Modal --> <div class="mo ...

Create a sleek transition for your Bootstrap 4 fixed Navbar by having it smoothly slide down and change to a

Throughout my experience with HTML/CSS, I have predominantly relied on themes that included this feature by default. However, as I now venture into building from scratch, I find myself struggling to recreate it. You'll notice that I have a stylish fi ...

What methods can be used to pause a jQuery function when hovering and resume it when the mouse leaves?

I'm currently working on a jQuery function that operates on the mousemove event. The goal is to have two images - one main image and one shadow image, with the shadow image reflecting movement based on mouse position. While everything is functioning p ...

Ensuring Node.js backend JavaScript waits for completion of my bash script before proceeding

Running three bash commands through a Node.js code snippet. Here's a portion of the script: exec(str, function(error, stdout, stderr){ console.log('stdout:'+stdout); console.log('stderr:'+stderr); if(error!=null){ ...

Searching for a specific field within an array in a nested subdocument in MongoDB: What you need to know

I am having trouble retrieving lookup data for an embedded array within a document. Below is a snippet of the data: { "_id": "58a4fa0e24180825b05e14e9", "fullname": "Test User", "username": "testuser" "teamInfo": { "chal ...

Create a collection showcasing only the values present in an array based on a specified percentage

An array named "data" consists of the given information. [['amazon', 'phone', 'serious', 'mind', 'blown', 'serious', 'enjoy', 'use', 'applic', &apos ...

Whenever I attempt to utilize this function, my console promptly crashes

I've been working on an app that can draw to the console, but I'm encountering crashes when testing my code. The draw function works fine (created in CodeBlocks). However, whenever I try to run the rect() function... I'm struggling to fi ...

Make a div with absolute positioning overflow outside of a div with relative positioning that is scrollable

I am facing an issue with two columns positioned side by side. The right column contains a tooltip that overflows to the left on hover. Both columns are scrollable and relatively positioned to allow the tooltip to follow the scroll. However, the tooltip is ...

Nested React Components in React Router Components

class AppRoutes extends Component { render () { return ( <Suspense fallback={<Spinner/>}> <Switch> <Route exact path="/" component={ HomePage } /> <Route exact path="/acti ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...