Skip to content

Instantly share code, notes, and snippets.

@MarksCode
Created February 3, 2017 10:28
Show Gist options
  • Save MarksCode/ac5fbec74450ba2c53fddb7046bae48d to your computer and use it in GitHub Desktop.
Save MarksCode/ac5fbec74450ba2c53fddb7046bae48d to your computer and use it in GitHub Desktop.
Coin Exchange Problem (max combinations)
//************************************************************************//
// Coin Exchange Problem //
// most combinations to exchange n cents with m coins {C1, C2, ... , Cm} //
// by Ron Marks //
// ex input: 5 3 //
// 1 2 3 //
// output: 4 //
// Explanation: 5 cents, 3 coins (1, 2, 3) //
// { (1,1,1,1,1), (1,1,1,2), (1,2,2), (1,1,3), (2,3) } //
// Final Array: //
// [ [ 1, 1, 1, 1 ], //
// [ 0, 1, 1, 1 ], //
// [ 0, 1, 2, 2 ], //
// [ 0, 1, 2, 3 ], //
// [ 0, 1, 3, 4 ], //
// [ 0, 1, 3, 5 ] ] //
//************************************************************************//
function processData(input) {
var lines = input.split("\n");
var n = parseInt(lines[0].split(" ")[0]); // n cents
var m = parseInt(lines[0].split(" ")[1]); // m coins
var coins = lines[1].split(" ").map(Number); // array of coin values
var arr = new Array(n+1); // Create 2d array size n+1 x m+1
for (var i=0; i<n+1; i++){
arr[i] = new Array(m+1);
}
for (var i=0; i<n+1; i++){ // arrays top row = 0
arr[i][0] = 0;
}
for (var i=0; i<m+1; i++){ // arrays first column = 1
arr[0][i] = 1;
}
for (var j=1; j<m+1; j++){
for (var i=1; i<n+1; i++){
if (coins[j-1] > i){ // if coin[j-1] is greater than i, take value above
arr[i][j] = arr[i][j-1];
} else { // else take values above, plus value to the left coins[j-1] places
arr[i][j] = arr[i][j-1] + arr[i-coins[j-1]][j];
}
}
}
console.log(arr[n][m]); // Final answer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment