O
O
OlgaParshina2021-06-25 16:11:05
JavaScript
OlgaParshina, 2021-06-25 16:11:05

How to transfer from a function to a loop?

I am writing a project for a coffee machine. Please help me rewrite this code for calculating change in coins from a function into a loop using while and for and output to console.log For example, if 50r is change 10 rubles by 5.

function oldgetChange(num) {
                    if (num >= 10) {
                        console.log(10);
                        getChange(num - 10);
                    } else if (num >= 5) {
                        console.log(5);
                        getChange(num - 5);
                    } else if (num >= 2) {
                        console.log(2);
                        getChange(num - 2);
                    } else if (num >= 1) {
                        console.log(1);
                        getChange(num - 1);
                    } else {
                        console.log("Вся сдача выдана!");
                    }
                }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-06-25
@OlgaParshina

Such a function will return an array of the number of coins of each size, resp. 10, 5, 2 and 1:

function getChange(num) {
  const coins = [10, 5, 2, 1];

  return coins.map((c) => {
    const n = Math.floor(num / c);
    num -= n * c;
    return n;
  });
}
Rewrite it with a loop whileor for. There is also a loop here: the array method iterates map()over each of its elements, executing a function inside for the next value and replacing the element with the returned value.
We take each denomination of coins, from largest to smallest, and tries to shove as many coins of the next denomination as possible into the change amount. The amount of change remaining to be given out is reduced each time by the change given out in coins.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question