JSFiddle - React, Tailwind, and code Playground

by tsdexter

JavaScript

var apple = { 'calories': 200, 'protein': 2.0, 'fat': 0.002 },
    crackers = { 'calories': 50, 'protein': 0.3, 'fat': 0.025 },
    peanuts = { 'calories': 100, 'protein': 0.2, 'fat': 0.015 },
 
    items = [apple, crackers, peanuts],
    diet = {'protein': 25, 'fat': 0.25},
    max_val = 0,
    solutions = [],
    g, p, i, item, val;
 
for (i = 0; i < items.length; i += 1) {
    item = items[i];
    item.max = Math.min(
        Math.floor(diet.protein / item.protein),
        Math.floor(diet.fat / item.fat)
    );
}
 
for (g = 0; g <= apple.max; g += 1) {
    for (p = 0; p <= crackers.max; p += 1) {
        for (i = 0; i <= peanuts.max; i += 1) {
            if (i * peanuts.protein + g * apple.protein + p * crackers.protein > diet.protein) {
                continue;
            }
            if (i * peanuts.fat + g * apple.fat + p * crackers.fat > diet.fat) {
                continue;
            }
            val = i * peanuts.calories + g * apple.calories + p * crackers.calories;
            if (val > max_val) {
                solutions = [];
                max_val = val;
            }
            if (val === max_val) {
                solutions.push([g, p, i]);
            }
        }
    }
}
 
document.write("maximum calories: " + max_val + '<br>');
for (i = 0; i < solutions.length; i += 1) {
    item = solutions[i];
    document.write("(apple: " + item[0] + ", crackers: " + item[1] + ", peanuts: " + item[2] + ")<br>");
}