interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / sudoku / sudoku.om

110 lines · 1973 bytes Raw Blame History
1note Rosetta Code task "Sudoku": https://rosettacode.org/wiki/Sudoku
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text puzzle "850002400720000009004000000000107002305000900040000000000080070017000000000036040"
8text tbar "------+-------+------\n"
9text tsep "| "
10text tsolved "solved:\n"
11global grid ulong 81
12note emit writes every byte of a to stdout; a short write is retried, an error exits 1
13fn emit a view uchar * to void
14o = ulong 0
15while lt o len a bound 4096
16k = write 1 a o sub len a o
17if le k 0
18exit 1
19end
20o = add o ulong k
21end
22end
23note emitu writes n in decimal; 20 digits hold every ulong
24fn emitu n ulong to void
25d = new uchar 20 0
26i = ulong 20
27v = n
28while true bound 20
29i = sub i 1
30put d i uchar add rem v 10 48
31v = div v 10
32if eq v 0
33break
34end
35end
36emit part d i sub 20 i
37end
38note ok says whether digit d may go in cell c: not already in its row, column or 3x3 box
39fn ok c ulong d ulong to bool
40r = div c 9
41k = rem c 9
42b = add mul mul div r 3 3 9 mul div k 3 3
43for i ulong 9
44if eq get grid add mul r 9 i d
45ret false
46end
47if eq get grid add mul i 9 k d
48ret false
49end
50q = add b add mul div i 3 9 rem i 3
51if eq get grid q d
52ret false
53end
54end
55ret true
56end
57note solve fills the first empty cell at or after c with each digit that fits and recurses; on a dead
58note end it empties the cell again (backtracking); the recursion is at most 81 deep
59fn solve c ulong to bool
60p = c
61while lt p 81 bound 81
62if eq get grid p 0
63break
64end
65p = add p 1
66end
67if eq p 81
68ret true
69end
70for x ulong 9
71d = add x 1
72if ok p d
73put grid p d
74if solve add p 1
75ret true
76end
77end
78end
79put grid p 0
80ret false
81end
82fn show to void
83for r ulong 9
84if and gt r 0 eq rem r 3 0
85emit tbar
86end
87for k ulong 9
88if and gt k 0 eq rem k 3 0
89emit tsep
90end
91emitu get grid add mul r 9 k
92if lt k 8
93emit sp
94end
95end
96emit nl
97end
98end
99fn main to int
100for i ulong 81
101put grid i sub ulong get puzzle i 48
102end
103show
104if not solve 0
105exit 1
106end
107emit tsolved
108show
109ret 0
110end