JSFiddle - React, Tailwind, and code Playground

by dvjc

HTML

<div id="answer" />

JavaScript

var a = arithmeticExpansion(18);
document.getElementById("answer").innerHTML = arrayAsArray(a);

// returns an array of distinct integer sets which sum to n
function arithmeticExpansion(n){
    var arr = [];
    
    // only continue if n is a positive integer
    if( parseInt(n) == n && n>=1 ){
        
        if( n < 19 ){
            var known = expansionFor(n);
            if( n < 3 ){
                arr.push( known );
            } else {
                arr = known;
            }
            // base case - [1];
//            arr.push( expansionFor(n) );
//            arr.push(1)
        } else {
            // recursively build
            // concatenates 1[expansion of n-1], 2[expansion of n-2], etc
            for( var x=1;x<n;x++ ){
                var nM = arithmeticExpansion(n-x);
                for( var y=0;y<nM.length;y++ ){
                    if( isArray(nM[y]) ){
                        var nextArr = [x];
                        for( var z=0;z<nM[y].length;z++ ){
                            nextArr.push(nM[y][z]);
                        }
                        arr.push(nextArr);
                    }
                }
                // ensures the trailing edge case is included
                var nextArr = [x];
                nextArr.push(n-x);
                arr.push(nextArr);
            }
            
            // sorts sum sets and removes duplictes
            arr = cleanup(arr);
        }
    }
    return arr;
}

// sorts sum sets and removes duplicates
function cleanup(arr){
    var cleanedUpArr = [];
    
    // sort each child array
    var x=0;
    while( typeof arr[x] !== "undefined" ){
        arr[x].sort();
        x = x + 1;
    }
    
    // sort the parameter array
    arr.sort();
    
    // remove duplicates from the parameter arr
    cleanedUpArr.push( arr[0] );

    for( var x = 1; x<arr.length; x++){
        if( arr[x].toString()!=arr[x-1].toString() ){
            cleanedUpArr.push( arr[x] );
        }
    }
    
...