Created
January 9, 2026 21:40
-
-
Save afvanwoudenberg/e4ba53cc3eed64f4e56a70d558e3bdbd to your computer and use it in GitHub Desktop.
A Takuzu/Binary puzzle solver in SQL (SQLite dialect)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| WITH RECURSIVE | |
| input(puz) AS ( | |
| VALUES ('....00.0....' || | |
| '1....0....11' || | |
| '.1......00..' || | |
| '............' || | |
| '.00...1.....' || | |
| '.......0..0.' || | |
| '.1.11...1...' || | |
| '0......0....' || | |
| '..1..1......' || | |
| '.0..0....0..' || | |
| '.......01.1.' || | |
| '...1...0..1.') | |
| ), | |
| side_len(n) AS ( | |
| SELECT CAST(sqrt(length(puz)) AS INT) FROM input | |
| ), | |
| bits(b) AS ( | |
| VALUES ('0'), ('1') | |
| ), | |
| idx(i) AS ( | |
| SELECT 0 | |
| UNION ALL | |
| SELECT i + 1 FROM idx, side_len WHERE i + 1 < n | |
| ), | |
| x(s, ind) AS ( | |
| SELECT puz, instr(puz, '.') FROM input | |
| UNION ALL | |
| SELECT | |
| substr(s,1,ind-1) || b || substr(s,ind+1), | |
| instr(substr(s,1,ind-1) || b || substr(s,ind+1), '.') | |
| FROM x, bits, side_len | |
| WHERE ind > 0 | |
| -- No row may contain three consecutive identical values | |
| AND substr(substr(s,1,ind-1) || b || substr(s,ind+1), ((ind-1)/n)*n + 1, n) NOT LIKE '%' || b || b || b || '%' | |
| -- No column may contain three consecutive identical values | |
| AND NOT EXISTS ( | |
| SELECT 1 | |
| FROM idx i | |
| WHERE i <= n-3 | |
| AND substr(substr(s,1,ind-1) || b || substr(s,ind+1), i*n + ((ind-1)%n) + 1, 1) = b | |
| AND substr(substr(s,1,ind-1) || b || substr(s,ind+1), (i+1)*n + ((ind-1)%n) + 1, 1) = b | |
| AND substr(substr(s,1,ind-1) || b || substr(s,ind+1), (i+2)*n + ((ind-1)%n) + 1, 1) = b | |
| ) | |
| -- Every row must contain exactly the same number of 0s and 1s. | |
| AND ( | |
| SELECT count(*) | |
| FROM idx i | |
| WHERE substr(substr(s,1,ind-1) || b || substr(s,ind+1), ((ind-1)/n)*n + i + 1, 1) = b | |
| ) <= n/2 | |
| -- Every column must contain exactly the same number of 0s and 1s. | |
| AND ( | |
| SELECT count(*) | |
| FROM idx i | |
| WHERE substr(substr(s,1,ind-1) || b || substr(s,ind+1), i*n + ((ind-1)%n) + 1, 1) = b | |
| ) <= n/2 | |
| ) | |
| SELECT x.s | |
| FROM x, side_len | |
| WHERE ind = 0 | |
| -- No two rows may be identical. | |
| AND (SELECT count(*) = count(DISTINCT substr(x.s, i*n + 1, n)) FROM idx i) | |
| -- No two columns may be identical. | |
| AND ( | |
| SELECT count(*) = count(DISTINCT | |
| (SELECT group_concat(substr(x.s, r.i*n + c.i + 1, 1), '') FROM idx r) | |
| ) | |
| FROM idx c | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment