I have this puzzle and I want to solve by code. I wrote simple code trying to brute force but it fail in one condition
https://dotnetfiddle.net/cJyu3w
How can I solve such problems?
Puzzling Stack Exchange is a question and answer site for those who create, solve, and study puzzles. It only takes a minute to sign up.
Sign up to join this communityI have this puzzle and I want to solve by code. I wrote simple code trying to brute force but it fail in one condition
https://dotnetfiddle.net/cJyu3w
How can I solve such problems?
First of all, let's see why your brute-forcing fails. (This is the puzzle part, the rest is plain old math.)
Let's check the parity of the answer numbers, by choosing an odd number (first picture) or an even number (second picture) as the top left unknown:
![]()
No matter which you chose, the number at the bottom right would have to be both odd and even at the same time, so there's no integer solution.
However, there are four equations and four unknowns, so we should have at least one solution (unless the system is inconsistent), or even many, if the equations aren't independent.
Since you wanted to know how to solve this by a computer program, let's do this with Octave.
(Sometimes it's difficult to choose the best programming language for a given problem. Here, we have a free language that actually gives the solution to our problem as the first syntax example on its home page. Choices don't really come easier than that.)
To get started, let's write the four equations out. Let's name the unknowns with letters a-d, so we get:
a +b = 8 c -d = 6 a +c = 13 b +d = 8
Notice that I've placed all the letters in their own columns. This is important for the next step, where we turn this into a matrix of coefficients. That is, we only write the multipliers (0, 1 and -1 in this case) into the columns, and put some brackets around the stuff:
$$\begin{bmatrix} 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & -1 \\ 1 & 0 & 1 & 0\\ 0 & 1 & 0 & 1 \end{bmatrix} \begin{bmatrix} a\\ b\\ c\\ d \end{bmatrix} = \begin{bmatrix} 8\\ 6\\ 13\\ 8 \end{bmatrix} $$
(The column with the letters is there just to keep the notation more or less mathematically valid.)
Then, we just type these in and let Octave solve it (using the backslash operator (A\b
)):
A=[1 1 0 0
0 0 1 -1
1 0 1 0
0 1 0 1]
b=[8
6
13
8]
A\b
(You can Try it online!)
This gives us the answer for all the unknowns (or a warning about a singular matrix if our equations weren't independent, or if our system was inconsistent):
3.5000 4.5000 9.5000 3.5000
Since we got a neat result without any warnings, we can just type it in the proper boxes to achieve the final result: