Min = [coin].concat(newMin); // what this line do...?

A Coin Change problem in Dynamic Programming - JavaScript… is below
min = [coin].concat(newMin); // what this line do…? [coin] is array? concatenate arrays or one element?

function MinCoinChange(coins){

    var cache = {};

    this.makeChange = function(amount) {
        var me = this;
        if (!amount) {
            return [];
        }
        if (cache[amount]) {
            return cache[amount];
        }
        var min = [], newMin, newAmount;
        for (var i=0; i<coins.length; i++){
            var coin = coins[i];
            newAmount = amount - coin;
            if (newAmount >= 0){
                newMin = me.makeChange(newAmount);
            }
            if (
                newAmount >= 0 &&
                (newMin.length < min.length-1 || !min.length) &&
                (newMin.length || !newAmount)
                ){
                min = [coin].concat(newMin);
                console.log('new Min ' + min + ' for ' + amount);
            }
        }
        return (cache[amount] = min);
    };
}


var minCoinChange = new MinCoinChange([1, 5, 10, 25]);
console.log(minCoinChange.makeChange(36));

It adds together two arrays, one containing coin, and the other being newMin.

Another way of doing it that would be less confusing, is:

min = [coin, newMin];

Where the first index is the type of coin, and the second index is the amount of those coins.

Even less confusing that is to use an object to store the information, but that would require rewriting several parts of the program too.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.