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

1.7 KiB

id title challengeType forumTopicId dashedName
59713bd26bdeb8a594fb9413 Contar moedas 5 302238 count-the-coins

--description--

Existem quatro tipos de moedas comuns no dinheiro dos EUA:

  • quarters (25 centavos)
  • dimes (10 centavos)
  • nickels (5 centavos) e
  • pennies (1 centavo)

Há seis maneiras de fazer troco com 15 centavos:

  • Um dime e um nickel
  • Um dime e 5 pennies
  • 3 nickels
  • 2 nickels e 5 pennies
  • Um nickel e 10 pennies
  • 15 pennies

--instructions--

Implemente uma função para determinar quantas maneiras há para fazer troco para uma determinada entrada, cents, que representa uma quantidade de centavos americanos usando essas moedas comuns.

--hints--

countCoins deve ser uma função.

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

countCoins(15) deve retornar 6.

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

countCoins(85) deve retornar 163.

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

countCoins(100) deve retornar 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];
}