In binary puzzles , a grid must be filled with ones and zeroes. Each column and row must be a sequence following these rules:
For instance, is a valid sequence; is invalid because there are three zeroes in a row; is invalid because there are more ones than zeroes.
How many valid sequences of length fourteen are possible?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
In Java:
Output:
Clarification of this somewhat dense code:
Each pattern may be represented as a 2 k -bit number, i.e. positive integer less than
maxpat
= 2 2 k . The loop variablepat
loops through all such patterns.In the inner loop,
i
indexes the bits in the pattern, from right to left. In each step, the pattern (in variablex
) is shifted one to the right. We study the bits one by one by looking atx&1
.The variables
b
andnb
("bit" and "no bit") count the numbers of ones and zeroes. After the loop, we check that they are equal. If either of them exceeds half of the pattern length (b > k
) the pattern is invalid, and webreak
out of the inner loop.The variables
sb
andsnb
("sequence of bits") count how many ones or zeroes were counted in a row. If the opposite value is read, they are reset to zero. If any of them becomes three or more (too much!), thebreak
statement gets us out.An alternative solution, "by hand", is doable using the generalization I presented in this problem . We have
2 ⋅ [ ( 7 0 ) ( 7 0 ) + ( 7 0 ) ( 6 1 ) + ( 6 1 ) ( 6 1 ) + ( 6 1 ) ( 5 2 ) + ( 5 2 ) ( 5 2 ) + ( 5 2 ) ( 4 3 ) + ( 4 3 ) ( 4 3 ) ] = 2 ⋅ [ 1 2 + 1 ⋅ 6 + 6 2 + 6 ⋅ 1 0 + 1 0 2 + 1 0 ⋅ 4 + 4 2 ] = 2 ⋅ [ 1 + 6 + 3 6 + 6 0 + 1 0 0 + 4 0 + 1 6 ] = 2 ⋅ 2 5 9 = 5 1 8 .