Skip to content

Instantly share code, notes, and snippets.

@IPRIT
Created August 2, 2019 07:45
Show Gist options
  • Select an option

  • Save IPRIT/4d9e6caba3837243ca7a727d15f27778 to your computer and use it in GitHub Desktop.

Select an option

Save IPRIT/4d9e6caba3837243ca7a727d15f27778 to your computer and use it in GitHub Desktop.
function atm (sum, limits) {
const obj = {};
let cur = 0;
const arr = Object.keys( limits ).map(Number).sort((a, b) => b - a);
let i = 0;
while (i < arr.length) {
const v = arr[i];
const c = Math.floor( sum / v );
const mc = Math.min( limits[ v ], c );
i++;
if (mc > 0) {
cur += v * mc;
sum -= v * mc;
obj[v] = mc;
}
if (!sum) {
break;
}
}
if (sum) {
return 'Error';
}
return arr.reduce((result, key) => {
if (obj[key]) {
limits[key] -= obj[key];
return result + obj[key] + 'x' + key + ' ';
}
return result;
}, '').trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment