I have a list of recipes, with fluid inputs and outputs per second:
const waterSeparation = {
name: 'water separation',
h2: 20/3,
o2: 10
};
const ammonia = {
name: "ammonia",
h2: -10,
n2: -10,
nh3: 10,
}
In this case, every second, one factory running water separation generates 20/3 units of h2 and 10 units of o2, while a factory making ammonia makes 10 nh3 per second while consuming 10 n2 and 10 h2.
const ratios = [{
recipe: waterSeparation,
count: 20 // how do I pick these numbers?
}, {
recipe: ammonia,
count: 14
} ...]
const results = ratios.reduce((acc, { recipe, count }) => {
Object.keys(recipe).filter(ingredient => ingredient !== 'name').forEach((ingredient) => {
if (ingredient in acc){
acc[ingredient] += recipe[ingredient] * count;
} else {
acc[ingredient] = recipe[ingredient] * count;
}
});
return acc;
}, {});
I know how to calculate the current recipes and their excesses/shortages, but I don’t know how to pick the right number of each factory. I need an algorithm to balance all the recipes to whole number multiples so that all the outputs are consumed with the lowest whole number of factories running each recipe. I would also be okay if I rounded up to the nearest whole number, in case there is no perfect ratio of each recipe. Is there an algorithm for this?