Pages

Rendre la monnaie !

//MAP a new objet

Here are some of the most commonly used methods provided by the Map object in JavaScript:

  1. set(key, value): Adds or updates an element with a specified key and a value to a Map object.

  2. get(key): Returns the value associated to the key, or undefined if there is none.

  3. size: Returns the number of key/value pairs in the Map object.

  4. Itération over a Map object

aMap.forEach((value, key) => {
    console.log(`$${key}: ${value}`);
});

🪛 en action pour rendre la monnaie !



/**
 * Calculates the change for a given amount.
 *
 * @param {number} amount - The amount for which to calculate the change.
 * @returns {Map<number, number>} - A map containing the denominations as keys and the count of each denomination as values.
 */
function calculateChange(amount) {
  const denominations = [100, 20, 10, 5, 1];
  let change = new Map();

  for (let bill of denominations) {
    let count = Math.floor(amount / bill);
    if (count > 0) {
      change.set(bill, count);
      amount -= bill * count;
    }
    if (amount === 0) {
      break;
    }
  }

  return change;
}

// Generate a random number between 1 and 1000
let randomAmount = Math.floor(Math.random() * 1000) + 1;
let text = `Random amount: ${randomAmount}`;

console.log(text);

let change = calculateChange(randomAmount);

// Calculate the number of tab spaces needed
let tabs = Math.ceil(text.indexOf(":") - 1); // Each tab is approximately 4 spaces

// Display the change
change.forEach((value, key) => {
  console.log(
    `${" ".repeat(tabs)}${value}: ${key >= 5 ? "bill" : "coin"}${
      value > 1 ? "s" : ""
    }\t${key}${key >= 5 ? "💶" : "🪙"}`
  );
});




 


Programmation récursive

Rendre la monnaie peut être resolu par une programmation recursive :