Pete, the baker"Codewars"

richeskelechi

Riches

Posted on September 20, 2023

Pete, the baker"Codewars"

Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes?

Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients that are not present in the objects, can be considered as 0.

Examples:

// must return 2
cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200});
// must return 0
cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000});

Steps:

  1. Declare a variable and set it to infinity. so this will help us to get the min number of cakes that can be made.
  2. using a loop lets iterate each of the recipes and use it for our comparison.
  3. At each iteration we are checking if each recipe is present in the available object.
  4. if yes, that is the recipe we need for making the cake is available. we will be dividing the value of the available recipe by the value of the required number.
  5. if the dividend is less than the variable we declared in step one, that means only that number of cake can be made with that receipt we store it as the new min number of cakes that can be made.
  6. finally we return the min number of cakes that can be made.

Algorithm

function cakes(recipe, available) {
    let numberOfCakes = Infinity;
    for (const eachRecipe in recipe) {
        if (available.hasOwnProperty(eachRecipe)) {
            const recipeRation = available[eachRecipe] / recipe[eachRecipe];
            if (recipeRation < numberOfCakes) {
                numberOfCakes = recipeRation;
            }
        } else {
            return 0;
        }
    }
    return Math.floor(numberOfCakes);
}
console.log(cakes({ flour: 500, sugar: 200, eggs: 1 }, { flour: 1200, sugar: 600, eggs: 5 }));

Enter fullscreen mode Exit fullscreen mode
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
richeskelechi
Riches

Posted on September 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About