satisfice
a year ago
The brute force method proposed in the article is so strangely obscure.
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)Etherlord87
a year ago
You waste some CPU cycles, which doesn't matter all that much here, but with more combinations could matter a lot:
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.
Joker_vD
a year ago
Just want to note that "brute force search" is called "brute force" instead of e.g. "search with heuristics" for a reason. Of course you can trim down the search space if you think about the properties of the problem but the whole point of using a brute force approach is to literally allow yourself to not think about the problem.
Etherlord87
a year ago
Whatever you do, you need to find some reasonable balance. You need to reason on what are the minimum possible values for the variables and what are the maximums. In my example the reasoning effort was minimal, much less than figuring the `c` is even or the `w` is divisible by 5.
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.
lupire
a year ago
Your code also has a bug, which would affect the result in some variations of the problem with different parameters, but fortunately does not affect this specific version. You also used 100.
Etherlord87
a year ago
The code wasn't written for other parameters, so it doesn't have a bug.
satisfice
a year ago
what I was going for is simplicity. I wanted code that mapped to the plain conceptual structure of the problem. As soon as you optimize it you begin to obfuscate the code.
Of course, with a bigger problem we will have to optimize.
fph
a year ago
I think it's because OP does not want to hardcode the dimension `n=3`, but write only code that works for all possible matrix sizes just by changing `a` and `b`.
yobbo
a year ago
Some clues to make it faster: w is divisible by 5. 5m=100-3w.
So, w ∈ {5,10,15,20,25,30}, m = 20 - 3w/5, c=100-m-w.
It seems this gives all answers.