freeCodeCamp/curriculum/challenges/italian/10-coding-interview-prep/rosetta-code/count-the-coins.md

1.7 KiB

id title challengeType forumTopicId dashedName
59713bd26bdeb8a594fb9413 Contare le monete 5 302238 count-the-coins

--description--

Ci sono quattro tipi di monete comuni nel dollaro americano:

  • quarter (25 centesimi)
  • dime (10 centesimi)
  • nickel (5 centesimi), e
  • penny (1 centesimo)

Ci sono sei modi per ottenere 15 centesimi:

  • Un dime e un nickel
  • Un dime e 5 penny
  • 3 nickel
  • 2 nickel e 5 penny
  • Un nickel e 10 penny
  • 15 penny

--instructions--

Implementa una funzione che determina quanti modi diversi ci sono per ottenere un certo input, cents, che rappresenta il numero di centesimi, usando queste monete comuni.

--hints--

countCoins dovrebbe essere una funzione.

assert(typeof countCoins === 'function');

countCoins(15) dovrebbe restituire 6.

assert.equal(countCoins(15), 6);

countCoins(85) dovrebbe restituire 163.

assert.equal(countCoins(85), 163);

countCoins(100) dovrebbe restituire 242.

assert.equal(countCoins(100), 242);

--seed--

--seed-contents--

function countCoins(cents) {

  return true;
}

--solutions--

function countCoins(cents) {
  const operands = [1, 5, 10, 25];
  const targetsLength = cents + 1;
  const operandsLength = operands.length;
  const t = [1];

  for (let a = 0; a < operandsLength; a++) {
    for (let b = 1; b < targetsLength; b++) {
      // initialise undefined target
      t[b] = t[b] ? t[b] : 0;

      // accumulate target + operand ways
      t[b] += (b < operands[a]) ? 0 : t[b - operands[a]];
    }
  }

  return t[targetsLength - 1];
}