Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function comp(a, b) {
- return b - a;
- }
- function atm(total, values) {
- values = values.sort(comp);
- let counts = {};
- let success = true;
- while (total > 0 && success) {
- for (let i = 0; i < values.length; i++) {
- if (values[i] <= total) {
- if (counts.hasOwnProperty(values[i])) {
- counts[values[i]] += 1;
- } else {
- counts[values[i]] = 1;
- }
- total -= values[i];
- break;
- } else if (i === values.length - 1) {
- success = false;
- }
- }
- }
- if (success) {
- return counts;
- } else {
- return false;
- }
- }
- function hardAtm(total, valuesMap) {
- let counts = {};
- let success = true;
- let valuesArr = [];
- for (value in valuesMap) {
- let sameValues = Array(valuesMap[value]).fill(parseInt(value));
- valuesArr = valuesArr.concat(sameValues);
- }
- values = valuesArr.sort(comp);
- while (total > 0 && success) {
- for (let i = 0; i < values.length; i++) {
- if (values[i] <= total) {
- if (counts.hasOwnProperty(values[i])) {
- counts[values[i]] += 1;
- } else {
- counts[values[i]] = 1;
- }
- total -= values[i];
- values.splice(i, 1);
- break;
- } else if (i === values.length - 1) {
- success = false;
- }
- }
- }
- if (success) {
- return counts;
- } else {
- return false;
- }
- }
- const total = 5665;
- const values = [5000, 1000, 500, 100, 50, 10, 5];
- const shuffledValues = [5, 10, 5000, 500, 50, 100, 1000];
- const valuesMap = {
- '5000': 2,
- '1000': 1,
- '500': 2,
- '10': 10,
- '5': 5
- }
- console.log(atm(total, shuffledValues));
- console.log(hardAtm(total, valuesMap));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement