Home > Blockchain >  How to match array of candles in Javascript
How to match array of candles in Javascript

Time:08-28

what is the best way to count the possibility of candles in array in Javascript;

example case:

Billy is collecting candles for his 25th birthday, he's got a box of candles, how much cakes possibly decorated?

const candles = [2,1,2,2,4,5,5,6,7]
// because 25 is a combination of candle 2 & 5, the possibility of candles can be used (25) should be 2 times.

CodePudding user response:

Although it seems like you just posted your homework here without any effort, I am so bored that I implemented a solution for you using two helper functions and ES6 syntax. See here for running the code in your browser. Please accept this answer as correct if it answered your question!

const candles =  [2,1,2,2,4,5,5,6,7]
const age = 25

const possibleCakeDecorations = calculatePossibleCakeDecorations(age, candles)
console.log(possibleCakeDecorations)

// Calculates the possible cake decorations given the age that is to be
// displayed and the array of candles (each a single digit)
function calculatePossibleCakeDecorations(age, candles){
  // 2 -> 3, 1 -> 1, 4 -> 1, 5 -> 2, 6 -> 1, 7 -> 1
  const candleMap = countOccurences(candles)

  // getting each digit of the age separately
  var ageDigits = String(age).split("").map((num)=> {
    return Number(num)
  })
  
  // we identify the bottlenecking candle digit
  const bottleneck = Math.min(...ageDigits)

  return bottleneck
}

// Returns a hashmap with the occurences of the elements in the list
// Example: [2, 2, 1, 2] -> {2 -> 3, 1 -> 1}
function countOccurences(list) {
   
  const map = new Map();

  list.forEach((item) => {
    const key = item;
    const collection = map.get(key);
    if (!collection) {
      map.set(key, 1);
    } else {
      map.set(key, collection   1);
    }
  });

  return map;
}
  • Related