Solving 100 Bushels Using Matrix Factorization
win-vector.com
win-vector.com
Here's a very simple alternative:
for m in range(0,100):
for w in range(0,100):
for c in range (0,100):
if m + w + c == 100 and 3*m+2*w+.5\*c==100:
print(m,w,c) for m in range(100):
for w in range(101-m):
c = 100-m-w
if 3*m + 2*w +.5*c == 100:
print(m,w,c)
No need to specify 0 as starting range, and the ending boundary is not included, so it's 100 at the outer loop, because at first sight the solution can't be m=100 w=0 c=0, The inner loop has to use 101, because perhaps there is a solution with c=0.There's no need for the 3rd loop! Once you have candidates for m and w, there's only one possible c satisfying the requirements. And so you also don't need to check for their sum being 100.
Otherwise OP made an error in using range(0, 100) instead of range(0, 101), but even here you could pedantically point out "how do you know the numbers can't be negative or over 100? You're not supposed to think too much when brute-forcing!" - well you have to do some minimal thinking always :P
Also notice my code is actually simpler.
Of course, with a bigger problem we will have to optimize.
So, w ∈ {5,10,15,20,25,30}, m = 20 - 3w/5, c=100-m-w.
It seems this gives all answers.
Edit: related follow up: any chance this technique is a good fit for enumeration of [Magic Squares][0] of a given order?
Pretty smart parrot.
Being able to access, apply, and restate reasoning processes described in 100-year-old books isn't the insult you think it is.
The word problem directly translates to this system of diophantine equations:
(i) { x + y + z = 100
(ii) { 6x + 4y + z = 200
Replacing z in (ii) using (i) yields: (ii) <=> 6x + 4y - x - y + 100 = 200 <=> 5x + 3y = 100
Which is solvable with the usual method.The matrix version is interesting, but it's bizarrely motivated as an overcomplicated way to solve a simple problem.