Skip to content

Instantly share code, notes, and snippets.

@abhiaiyer91
Created January 27, 2017 06:31
Show Gist options
  • Save abhiaiyer91/cd85aa3c4ff1fdd40d2464cafb57eea6 to your computer and use it in GitHub Desktop.
Save abhiaiyer91/cd85aa3c4ff1fdd40d2464cafb57eea6 to your computer and use it in GitHub Desktop.

Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:

1+1+1+1, 1+1+2, 2+2. The order of coins does not matter:

1+1+2 === 2+1+1 Also, assume that you have an infinite ammount of coins.

Your function should take an amount to change and an array of unique denominations for the coins:

  countChange(4, [1,2]) // => 3
  countChange(10, [5,2,3]) // => 4
  countChange(11, [5,7]) //  => 0

Solution:

var countChange = function(money, coins) {
  return findComboCount(money, coins, 0);
}

function findComboCount(money, coin, index) {
  if(money === 0){
    return 1;
  }
  else if (money < 0 || coin.length == index) {
    return 0;
  }
  else {
    var withFirstCoin = findComboCount(money - coin[index], coin, index);
    var withoutFirstCoin = findComboCount(money, coin, index + 1);
    return withFirstCoin + withoutFirstCoin;
  }
} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment