Puzzle — 20 People to consume 20 units of food under constraints
Just write the problem literally and use Reduce
Reduce[
m >= 0 && w >= 0 && b >= 0 && {m, w, b} ∈ Integers &&
2 m + 3/2 w + 1/2 b == 20 && m + w + b == 20, {m, w, b}]
(* (m == 0 && w == 10 && b == 10) || (m == 2 && w == 7 && b == 11) ||
(m == 4 && w == 4 && b == 12) || (m == 6 && w == 1 && b == 13) *)
We can do this more efficiently using IntegerPartitions
:
Counts /@ IntegerPartitions[20, {20}, {1, 3, 4}/2]
{ <|2 -> 6, 3/2 -> 1, 1/2 -> 13|>, <|2 -> 4, 3/2 -> 4, 1/2 -> 12|>, <|2 -> 2, 3/2 -> 7, 1/2 -> 11|>, <|3/2 -> 10, 1/2 -> 10|> }
Also as requested code for only one solution:
Counts /@ IntegerPartitions[20, {20}, {1, 3, 4}/2, 1]
{<|2 -> 6, 3/2 -> 1, 1/2 -> 13|>}
This does not generate all and then throw some away; it only generates the one requested.
As a rule when working any problem similar to this I try to apply IntegerPartitions
as when it fits it is usually much faster than Solve
, Reduce
, etc. Some examples:
- How do I generate a set of n-tuples containing integral solutions to a linear equation provided certain constraints?
- How to merge permutations obtained from Solve on multiple variables?
- Diophantine and odd
Another solution:
Select[FrobeniusSolve[{20, 15, 5}, 200], Total[#] == 20 &]
{{0, 10, 10}, {2, 7, 11}, {4, 4, 12}, {6, 1, 13}}
The first element in each list is the number of men, the second element is the number of women, and the third element is the number of babies.