DEV Community

Discussion on: Daily Challenge #262 - No One Likes Spare Change

Collapse
 
kvharish profile image
K.V.Harish • Edited

Not sure if this is an efficient solution but here is mine in JavaScript. I took the liberty to return an object instead of the number of coins and sorted the denominations instead of expecting it in order. I also added the test case suggested by davidmmooney.

const coins1 = [1, 5, 10, 25];
const coins2 = [1, 2, 5, 10, 20, 50];
const coins3 = [1, 5, 20, 25];
const coins4 = [2, 9, 5, 1];

const getChangeAsCoins = (coins, amount) => {
  coins = coins.sort((a, b) => a - b);
  let remaining = amount,
      index = coins.length - 1,
      change = {};

  while(remaining !== 0 || index !== -1) {
    numOfCoins = Math.floor(remaining / coins[index])
    change[coins[index]] = numOfCoins;
    remaining = remaining % coins[index];
    index--;
  }

  console.log(change);
}

getChangeAsCoins(coins1, 123);
/*
  {
    1: 3,
    5: 0,
    10: 2,
    25: 4
  }
*/
getChangeAsCoins(coins2, 123);
/*
  {
    1: 1,
    2: 1,
    5: 0,
    10: 0,
    20: 1,
    50: 2
  }
*/
getChangeAsCoins(coins1, 75);
/*
  {
    1: 0,
    5: 0,
    10: 0,
    25: 3
  }
*/
getChangeAsCoins(coins2, 75);
/*
  {
    1: 0,
    2: 0,
    5: 1,
    10: 0,
    20: 1,
    50: 1
  }
*/
getChangeAsCoins(coins3, 40);
/*
  {
    1: 0,
    5: 3,
    20: 0,
    25: 1
  }
*/
getChangeAsCoins(coins4, 53);
/*
  {
    1: 1,
    2: 1,
    5: 1,
    9: 5
  }
*/
Collapse
 
tinstaafl profile image
tinstaafl

the 'coins3,40' test returns the wrong answer it should be "20: 2"