简体   繁体   中英

How to find all possible combinations of triplets equaling a given sum in JavaScript? ('Stars and Bars' or 'Balls and Bins' problem)

I found a similar post on StackOverflow that answers the question but in Python, and I'm looking for a solution for javascript (google script editor for a google sheet).

Balls and Bins problem

How can I solve this using JavaScript?

Figured it out using nested for loops. How to output arrays of all triples which equal to sum (numSum) by interval.

The reason I used an internal is because I am using much bigger numbers to calculate these for monetary loans, so the interval lets me calculate by $100 chunk instead of each dollar of a huge sum.

     function calcSum(SUM, INTERVAL) {

      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var dataSheet = ss.getSheetByName('Data');
          
      var sumNum = SUM/INTERVAL
    
      var a = 0
      var b = 0
      var c = sumNum
    
      var aTicker = 0
      var bTicker = sumNum
      var cTicker = sumNum
    
      //Loop through all triple combinations of sumNum
      for (i = 0; i < sumNum + 1; i++) {

         for (j = aTicker; j < sumNum + 1; j++) {

            var array = [];
        
            array.push(a * INTERVAL, b * INTERVAL, c * INTERVAL);
        
            dataSheet.getRange("A" + rowCounter + ":D" + rowCounter).setValues([array]);

            rowCounter++;

          }
      
         if (b < bTicker) {
           b++;
         } else {
           b = 0;
           bTicker--;
         }
      
         if (c > 0){
           c--;
         } else {
           cTicker--;
           c = cTicker;
         }
      
       }

    a++;
    aTicker++;

  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM