-3

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?

  • Welcome! I assume that you request an [Apps Script](https://developers.google.com/apps-script/overview) answer, isn't it? Please share how you tried to solve the problem, so we all can take a look at the code. – Jacques-Guzel Heron Feb 19 '21 at 12:21

1 Answers1

0

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++;

  }

}