forked from pkulchenko/wxlua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwxluasudoku.wx.lua
More file actions
5216 lines (4442 loc) · 212 KB
/
wxluasudoku.wx.lua
File metadata and controls
5216 lines (4442 loc) · 212 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-------------------------------------------------------------------------=---
-- Name: wxluasudoku.wx.lua
-- Purpose: wxLuaSudoku - a wxLua program to generate/solve/play Sudoku puzzles
-- Author: John Labenski
-- Created: 2006
-- Copyright: (c) 2006 John Labenski. All rights reserved.
-- Licence: wxWindows licence
-------------------------------------------------------------------------=---
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
-- Coding notes:
-- All non gui sudoku functions are in the "sudoku" table and all gui related
-- functions are in the "sudokuGui" table.
-- sudoku.GetXXX() retrieve precalculated or set values from the sudoku table
-- sudoku.SetXXX() set values to the sudoku table
-- sudoku.FindXXX() search the table for "stuff", but do not modify it, returns result
-- sudoku.CalcXXX() search the table for "stuff" and store the values to it for GetXXX functions
sudoku = sudoku or {} -- the table to hold the sudoku solver functions
-- ============================================================================
-- A simple function to implement "cond ? A : B", eg "result = iff(cond, A, B)"
-- note all terms must be able to be evaluated
function iff(cond, A, B) if cond then return A else return B end end
-- make the number or bool into a bool or number
function inttobool(n)
if (n == nil) or (n == 0) then return false end
return true
end
function booltoint(n)
if (n == nil) or (n == false) then return 0 end
return 1
end
-- ============================================================================
-- Simple functions to count the total number of elements in a table
-- Notes about speed : using for loop and pairs() in TableCount is 2X faster
-- than using while loop and next(table). However using next() is slightly
-- faster than using for k,v in pairs(t) do return true end in TableIsEmpty.
function TableCount(atable)
local count = 0
for k, v in pairs(atable) do count = count + 1 end
return count
end
function TableIsEmpty(atable)
return next(atable) == nil
end
-- Set a value in the table or subtable, first making sure that the subtables
-- are created first. Modifies the input table.
-- TableSetValue(3, atable, "How", "Are", 4, "You") ==> atable.How.Are[4].You = 3
function TableSetValue(value, atable, ...)
if type(atable) ~= "table" then atable = {} end
local t = atable -- t moves up levels through atable
local args = {...}
for n = 1, #args-1 do
local a = args[n]
if not t[a] then t[a] = {} end
t = t[a]
end
t[args[#args]] = value
end
-- Remove a value in the table or subtable, first making sure that the subtables
-- exist. Modifies the input table.
-- TableRemoveValue(atable, false, "How", "Are", 4, "You") ==> atable.How.Are[4].You = nil
function TableRemoveValue(atable, only_if_empty, ...)
if type(atable) ~= "table" then return end
local t = atable -- t moves up levels through atable
local args = {...}
for n = 1, #args-1 do
t = t[args[n]]
if not t then return end -- already gone
end
if (not only_if_empty) or ((type(t[args[#args]]) == "table") and TableIsEmpty(t[args[#args]])) then
t[args[#args]] = nil
end
end
-- ============================================================================
-- completely dump the contents of a table
-- atable is the input table to dump the contents of
-- prefix is a string prefix for debugging purposes
-- tablelevel is tracker for recursive calls to TableDump (do not use initially)
function TableDump(atable, prefix, tablelevel)
local function print_val(v)
local t = type(v)
if t == "number" then
return tostring(v)
elseif t == "string" then
return "\""..v.."\""
end
return "'"..tostring(v).."'"
end
prefix = prefix or ""
if tablelevel == nil then
tablelevel = ""
print(prefix.."-Dumping Table "..tostring(atable))
end
prefix = prefix.." "
local n = 0
for k, v in pairs(atable) do
n = n + 1
print(string.format("%s %d: %s[%s] = %s", prefix, n, tablelevel, print_val(k), print_val(v)))
if type(v) == "table" then
TableDump(v, prefix.." ", tablelevel.."["..print_val(k).."]")
end
end
end
-- ============================================================================
-- Make a deep copy of a table, including all sub tables, fails on recursive tables.
-- returns a new table
function TableCopy(atable)
if not atable then return nil end
local newtable = {}
for k, v in pairs(atable) do
if type(v) == "table" then
newtable[k] = TableCopy(v)
else
newtable[k] = v
end
end
return newtable
end
-- Merge the two tables together, adding or replacing values in original_table
-- with those in new_table, returns a new table and doesn't modify inputs
-- fails on recursive tables, returns the new table
function TableMerge(new_table, original_table)
new_table = new_table or {}
local out_table = TableCopy(original_table or {})
for k, v in pairs(new_table) do
if type(v) == "table" then
if out_table[k] and (type(out_table[k]) == "table") then
out_table[k] = TableMerge(v, out_table[k])
elseif out_table[k] then
local ov = out_table[k]
out_table[k] = TableCopy(v)
table.insert(out_table[k], ov)
else
out_table[k] = TableCopy(v)
end
elseif out_table[k] and (type(out_table[k]) == "table") then
table.insert(out_table[k], v)
else
out_table[k] = v
end
end
return out_table
end
-- ============================================================================
-- Flags for the sudokuTable.flags[flag] = true/false/nil
sudoku.ELIMINATE_NAKED_PAIRS = 1 -- for sudoku.CalcAllPossible(sudokuTable)
sudoku.ELIMINATE_HIDDEN_PAIRS = 2 -- set to true to have it run
sudoku.ELIMINATE_NAKED_TRIPLETS = 3 -- for sudoku.CalcAllPossible(sudokuTable)
sudoku.ELIMINATE_HIDDEN_TRIPLETS = 4 -- set to true to have it run
sudoku.ELIMINATE_NAKED_QUADS = 5 -- for sudoku.CalcAllPossible(sudokuTable)
sudoku.ELIMINATE_HIDDEN_QUADS = 6 -- set to true to have it run
sudoku.FILENAME = 7 -- store the fileName from Open/Save functions
sudoku.ELIMINATE_FLAG_MIN = 1 -- for iterating the ELIMINATE flags
sudoku.ELIMINATE_FLAG_MAX = 6
-- given the upper left cell of block you can iterate through the block using
-- for n = 1, 9 do cell = n + block_cell + sudoku.LinearBlockCellTable[n] ... end
sudoku.LinearBlockCellTable = { -1, -1, -1, 5, 5, 5, 11, 11, 11 }
sudoku.CellToRowTable = {}
sudoku.CellToColTable = {}
sudoku.BlockToRowTable = {}
sudoku.BlockToColTable = {}
sudoku.CellToBlockTable = {}
sudoku.BlockToCellTable = {}
for cell = 1, 81 do
local row = math.floor(cell/9.1)+1
local col = cell-(row-1)*9
sudoku.CellToRowTable[cell] = row
sudoku.CellToColTable[cell] = col
local block_row = math.floor(row/3.5)+1
local block_col = math.floor(col/3.5)+1
sudoku.CellToBlockTable[cell] = (block_row-1)*3 + block_col
end
for block = 1, 9 do
local row = math.floor(block/3.5)*3+1
local col = math.fmod(block-1,3)*3+1
sudoku.BlockToRowTable[block] = row
sudoku.BlockToColTable[block] = col
sudoku.BlockToCellTable[block] = (row-1)*9 + col
end
-- ============================================================================
-- Create a sudoku table to be used with the rest of the sudoku functions
function sudoku.CreateTable()
local sudokuTable =
{
values = {}, -- array (1-81) of values[cell#] = value (0 means unset)
row_values = {}, -- array (1-9) of values[row#][value] = { cell1, cell2... }
col_values = {}, -- array (1-9) of values[col#][value] = { cell1, cell2... }
block_values = {}, -- array (1-9) of values[block#][value] = { cell1, cell2... }
possible = {}, -- possible values per cell, possible[cell# 1-81] = { val1, val2... }
invalid = {}, -- array (1-81) of known invalid[cell#] = true/nil
flags = {} -- extra flags for puzzle, eg. ELIMINATE_NAKED_PAIRS
}
for i = 1, 81 do
sudokuTable.values[i] = 0 -- initialize to unknown
sudokuTable.possible[i] = {} -- initialize to empty
end
for i = 1, 9 do
sudokuTable.row_values[i] = {}
sudokuTable.col_values[i] = {}
sudokuTable.block_values[i] = {}
end
sudoku.UpdateTable(sudokuTable)
return sudokuTable
end
-- Update all the values in the table using only the cell values, modifies input sudokuTable.
function sudoku.UpdateTable(sudokuTable)
sudoku.CalcRowColBlockValues(sudokuTable)
sudoku.CalcInvalidCells(sudokuTable)
sudoku.CalcAllPossible(sudokuTable)
end
-- Set the values table in the sudokuTable and update everything, modifies input sudokuTable.
function sudoku.SetValues(sudokuTable, values)
sudokuTable.values = values
sudoku.UpdateTable(sudokuTable)
end
-- Open a sudoku table from a file, the file should be formatted as 9x9 numbers
-- with 9 numbers per row and 9 columns.
-- returns a sudoku.CreateTable() with the values set and "" on success
-- or nil, error_message on failure
function sudoku.Open(fileName)
local values = {}
local value_count = 0 -- number of cols in line
local row_count = 0 -- number of rows read
local line_n = 0 -- actual line number in file
for ln in io.lines(fileName) do
local line = ln
line_n = line_n + 1
local col_count = 0
for digit in string.gmatch(line, "%d") do
local k = tonumber(digit)
if (k >= 0) and (k <= 9) then
table.insert(values, k)
col_count = col_count + 1
value_count = value_count + 1
else
return nil, string.format("Error loading sudoku file : '%s' invalid number '%d' on line %d.", fileName, k, line_n)
end
end
if col_count == 9 then
row_count = row_count + 1
elseif (col_count ~= 0) and (col_count ~= 9) then
return nil, string.format("Error loading sudoku file : '%s' on line %d.\nExpecting 9 columns, found %d.", fileName, line_n, col_count)
end
end
if line_n == 0 then
return nil, string.format("Error opening sudoku file : '%s'.", fileName)
elseif row_count ~= 9 then
return nil, string.format("Error loading sudoku file : '%s', expected 9 rows, found %d.", fileName, row_count)
elseif value_count ~= 81 then
return nil, string.format("Error loading sudoku file : '%s', expected 81 numbers, found %d.", fileName, value_count)
end
local s = sudoku.CreateTable()
s.flags[sudoku.FILENAME] = fileName
sudoku.SetValues(s, values)
return s, ""
end
-- Save a sudoku grid as a 9x9 comma separated table to a file, returns success
function sudoku.Save(sudokuTable, fileName)
local f = io.open(fileName, "w+")
if not f then return false end
local str = sudoku.ToString(sudokuTable)
f:write(str)
io.close(f)
sudokuTable.flags[sudoku.FILENAME] = fileName
return true
end
-- ============================================================================
-- Neatly print the sudoku grid
function sudoku.PrintGrid(sudokuTable)
local str = string.rep("-", 13).."\n"
for r = 1, 9 do
str = str.."|"
for c = 1, 9 do
local v = " "
if sudoku.HasValue(sudokuTable, r, c) then
v = tostring(sudoku.GetValue(sudokuTable, r, c))
end
str = str..v
if math.fmod(c, 3) == 0 then str = str.."|" end
end
str = str.."\n"
if math.fmod(r, 3) == 0 then str = str..string.rep("-", 13).."\n" end
end
print(str)
end
-- Write the grid itself to a string as 9x9 with a space/line separating blocks
function sudoku.ToString(sudokuTable)
local str = ""
for r = 1, 9 do
for c = 1, 9 do
local v = "0"
if sudoku.HasValue(sudokuTable, r, c) then
v = tostring(sudoku.GetValue(sudokuTable, r, c))
end
str = str..v..","
if math.fmod(c, 3) == 0 then str = str.." " end
end
str = str.."\n"
if (r < 9) and (math.fmod(r, 3) == 0) then str = str.."\n" end
end
return str
end
-- Neatly print the possible values for each cell (you must calculate it first)
function sudoku.PrintPossible(sudokuTable)
local str = string.rep("-", 103).."\n"
for r = 1, 9 do
str = str.."|"
for c = 1, 9 do
local has_value = sudoku.HasValue(sudokuTable, r, c)
if has_value then str = str.."<" else str = str.."[" end
local p = sudoku.GetPossible(sudokuTable, r, c)
for i = 1, 9 do
str = str..(p[i] or " ")
end
if has_value then str = str..">" else str = str.."]" end
if math.fmod(c, 3) == 0 then str = str.."|" end
end
str = str.."\n"
if math.fmod(r, 3) == 0 then str = str..string.rep("-", 103).."\n" end
end
print(str)
end
-- ============================================================================
-- Convert a row, col cell index (1-9) into a linear position in the grid (1-81)
function sudoku.RowColToCell(row, col)
return (row-1)*9 + col
end
-- Convert a linear cell index (1-81) into a row, col cell index (1-9)
function sudoku.CellToRowCol(cell)
return sudoku.CellToRowTable[cell], sudoku.CellToColTable[cell]
end
function sudoku.CellToRow(cell)
return sudoku.CellToRowTable[cell]
end
function sudoku.CellToCol(cell)
return sudoku.CellToColTable[cell]
end
-- ============================================================================
-- Check the validity of rows, cols, cells, blocks, values
function sudoku.IsValidValueN(value)
return (value >= 1) and (value <= 9)
end
-- ============================================================================
-- Convert a row, col cell index (1-9) into the linear block number (1-9)
function sudoku.RowColToBlock(row, col)
return sudoku.CellToBlockTable[sudoku.RowColToCell(row, col)]
end
-- Get the block (1-9) that this cell (1-81) is in
function sudoku.CellToBlock(cell)
return sudoku.CellToBlockTable[cell]
end
-- Get the upper left cell of this block
function sudoku.BlockToCell(block)
return sudoku.BlockToCellTable[block]
end
-- Convert a linear block index (1-9) into upper left row, col cell index (1-9)
function sudoku.BlockToRowCol(block)
return sudoku.BlockToRowTable[block], sudoku.BlockToColTable[block]
end
function sudoku.BlockToRow(block)
return sudoku.BlockToRowTable[block]
end
function sudoku.BlockToCol(block)
return sudoku.BlockToColTable[block]
end
-- Get the upper left row, col cell of the block given by row, col
function sudoku.RowColToBlockRowCol(row, col)
local block = sudoku.RowColToBlock(row, col)
return sudoku.BlockToRowTable[block], sudoku.BlockToColTable[block]
end
-- Generate a table of {[cell] = {hash table of cells that are in the row, col, block of this cell}}
sudoku.cellToRowColBlockCellsTable = {}
for cell = 1, 81 do
local row, col = sudoku.CellToRowCol(cell)
local block_cell = sudoku.BlockToCell(sudoku.CellToBlock(cell))
sudoku.cellToRowColBlockCellsTable[cell] = {}
for rcb = 1, 9 do
local c = sudoku.RowColToCell(rcb, col)
sudoku.cellToRowColBlockCellsTable[cell][c] = true
c = sudoku.RowColToCell(row, rcb)
sudoku.cellToRowColBlockCellsTable[cell][c] = true
c = rcb + block_cell + sudoku.LinearBlockCellTable[rcb]
sudoku.cellToRowColBlockCellsTable[cell][c] = true
end
end
-- Generate a table of {[cell] = {array of cells that are in the row, col, block of this cell}}
sudoku.cellToRowColBlockCellsArray = {}
for cell = 1, 81 do
sudoku.cellToRowColBlockCellsArray[cell] = {}
for k, v in pairs(sudoku.cellToRowColBlockCellsTable[cell]) do
table.insert(sudoku.cellToRowColBlockCellsArray[cell], k)
end
end
sudoku.RowCellTable = {}
sudoku.ColCellTable = {}
sudoku.BlockCellTable = {}
sudoku.BlockCellShiftTable = {0, 3, 6, 27, 30, 33, 54, 57, 60}
for n = 1, 9 do
local nn = (n-1)*9
sudoku.RowCellTable[n] = {1+nn, 2+nn, 3+nn, 4+nn, 5+nn, 6+nn, 7+nn, 8+nn, 9+nn}
nn = n - 1
sudoku.ColCellTable[n] = {1+nn, 10+nn, 19+nn, 28+nn, 37+nn, 46+nn, 55+nn, 64+nn, 73+nn}
nn = sudoku.BlockCellShiftTable[n]
sudoku.BlockCellTable[n] = {1+nn, 2+nn, 3+nn, 10+nn, 11+nn, 12+nn, 19+nn, 20+nn, 21+nn}
end
-- ============================================================================
-- Get the cell value at a specific row, col
function sudoku.GetValue(sudokuTable, row, col)
return sudoku.GetCellValue(sudokuTable, sudoku.RowColToCell(row, col))
end
-- Set the cell value at a specific row, col, modifies input sudokuTable.
function sudoku.SetValue(sudokuTable, row, col, value)
local cell = sudoku.RowColToCell(row, col)
local block = sudoku.CellToBlock(cell)
local old_value = sudokuTable.values[cell]
if not sudoku.IsValidValueN(value) then value = 0 end
sudokuTable.values[cell] = value
--remove the old_value from the row, col, block values
if sudoku.IsValidValueN(old_value) then
if sudokuTable.row_values[row] and sudokuTable.row_values[row][old_value] then
sudokuTable.row_values[row][old_value][cell] = nil
if TableIsEmpty(sudokuTable.row_values[row][old_value]) then sudokuTable.row_values[row][old_value] = nil end
end
if sudokuTable.col_values[col] and sudokuTable.col_values[col][old_value] then
sudokuTable.col_values[col][old_value][cell] = nil
if TableIsEmpty(sudokuTable.col_values[col][old_value]) then sudokuTable.col_values[col][old_value] = nil end
end
if sudokuTable.block_values[block] and sudokuTable.block_values[block][old_value] then
sudokuTable.block_values[block][old_value][cell] = nil
if TableIsEmpty(sudokuTable.block_values[block][old_value]) then sudokuTable.block_values[block][old_value] = nil end
end
end
--add new value to the row, col, block values
if value ~= 0 then
if not sudokuTable.row_values[row] then
sudokuTable.row_values[row] = {[value] = {[cell] = cell}}
elseif not sudokuTable.row_values[row][value] then
sudokuTable.row_values[row][value] = {[cell] = cell}
else
sudokuTable.row_values[row][value][cell] = cell
end
if not sudokuTable.col_values[col] then
sudokuTable.col_values[col] = {[value] = {[cell] = cell}}
elseif not sudokuTable.col_values[col][value] then
sudokuTable.col_values[col][value] = {[cell] = cell}
else
sudokuTable.col_values[col][value][cell] = cell
end
if not sudokuTable.block_values[block] then
sudokuTable.block_values[block] = {[value] = {[cell] = cell}}
elseif not sudokuTable.block_values[block][value] then
sudokuTable.block_values[block][value] = {[cell] = cell}
else
sudokuTable.block_values[block][value][cell] = cell
end
end
end
-- Does the cell have a value at a specific row, col
function sudoku.HasValue(sudokuTable, row, col)
return sudoku.HasCellValue(sudokuTable, sudoku.RowColToCell(row, col))
end
-- Set the cell value at a specific cell
function sudoku.GetCellValue(sudokuTable, cell)
return sudokuTable.values[cell]
end
-- Set the cell value at a specific cell, modifies input sudokuTable.
function sudoku.SetCellValue(sudokuTable, cell, value)
local row, col = sudoku.CellToRowCol(cell)
sudoku.SetValue(sudokuTable, row, col, value)
end
-- Does the cell have a value at a specific cell
function sudoku.HasCellValue(sudokuTable, cell)
return sudoku.IsValidValueN(sudokuTable.values[cell])
end
-- ============================================================================
-- Set the row_values, col_values, block_values tables of the input sudokuTable
-- eg. row values table is row_values[row#][value][cell#] = cell#
-- if no value then row_values[row#][value] = nil
function sudoku.CalcRowColBlockValues(sudokuTable)
sudokuTable.row_values = {}
sudokuTable.col_values = {}
sudokuTable.block_values = {}
for cell = 1, 81 do
local row, col = sudoku.CellToRowCol(cell)
local block = sudoku.CellToBlock(cell)
if not sudokuTable.row_values[row] then sudokuTable.row_values[row] = {} end
if not sudokuTable.col_values[col] then sudokuTable.col_values[col] = {} end
if not sudokuTable.block_values[block] then sudokuTable.block_values[block] = {} end
local value = sudoku.GetCellValue(sudokuTable, cell)
if sudoku.IsValidValueN(value) then
if not sudokuTable.row_values[row][value] then
sudokuTable.row_values[row][value] = {[cell] = cell}
else
sudokuTable.row_values[row][value][cell] = cell
end
if not sudokuTable.col_values[col][value] then
sudokuTable.col_values[col][value] = {[cell] = cell}
else
sudokuTable.col_values[col][value][cell] = cell
end
if not sudokuTable.block_values[block][value] then
sudokuTable.block_values[block][value] = {[cell] = cell}
else
sudokuTable.block_values[block][value][cell] = cell
end
end
end
end
-- ============================================================================
-- Can this value be put into this cell given the other existing values?
function sudoku.IsValidValue(sudokuTable, row, col, value)
if sudokuTable.row_values[row][value] or
sudokuTable.col_values[col][value] or
sudokuTable.block_values[sudoku.RowColToBlock(row, col)][value] then
return false
end
return true
end
-- Find all the invalid cells by looking for duplicates, modifies input sudokuTable.
-- fills sudokuTable.invalid table with the values
function sudoku.CalcInvalidCells(sudokuTable)
sudokuTable.invalid = {} -- reset to all good
for n = 1, 9 do
for i, cell_table in pairs(sudokuTable.row_values[n]) do
if TableCount(cell_table) > 1 then
for j, cell in pairs(cell_table) do
sudokuTable.invalid[cell] = true
end
end
end
for i, cell_table in pairs(sudokuTable.col_values[n]) do
if TableCount(cell_table) > 1 then
for j, cell in pairs(cell_table) do
sudokuTable.invalid[cell] = true
end
end
end
for i, cell_table in pairs(sudokuTable.block_values[n]) do
if TableCount(cell_table) > 1 then
for j, cell in pairs(cell_table) do
sudokuTable.invalid[cell] = true
end
end
end
end
end
-- ============================================================================
-- Get the possible values at a specific row, col cell
-- Must be previously set from sudoku.CalcAllPossible
function sudoku.GetPossible(sudokuTable, row, col)
return sudokuTable.possible[sudoku.RowColToCell(row, col)]
end
function sudoku.GetCellPossible(sudokuTable, cell)
return sudokuTable.possible[cell]
end
-- Set the possible values at a specific row, col cell. Modifies input sudokuTable.
function sudoku.SetPossible(sudokuTable, row, col, possibleTable)
sudokuTable.possible[sudoku.RowColToCell(row, col)] = possibleTable
end
function sudoku.SetCellPossible(sudokuTable, cell, possibleTable)
sudokuTable.possible[cell] = possibleTable
end
-- Remove a possible value at a specific row, col cell only. Modifies input sudokuTable.
function sudoku.RemovePossible(sudokuTable, row, col, value)
return sudoku.RemoveCellPossible(sudokuTable, sudoku.RowColToCell(row, col), value)
end
function sudoku.RemoveCellPossible(sudokuTable, cell, value)
sudokuTable.possible[cell][value] = nil
end
-- Remove a possible values from the row, col, block. Modifies input sudokuTable.
-- if exceptTable then don't remove it from exceptTable[cell#] = true
function sudoku.RemovePossibleAll(sudokuTable, cell, value, exceptTable, break_if_empty)
exceptTable = exceptTable or {}
break_if_empty = break_if_empty or false
for i, c in ipairs(sudoku.cellToRowColBlockCellsArray[cell]) do
if (not exceptTable[c]) and sudokuTable.possible[c][value] then
sudokuTable.possible[c][value] = nil
if break_if_empty and (not sudoku.HasCellValue(sudokuTable, c)) and TableIsEmpty(sudokuTable.possible[c]) then
return
end
end
end
end
-- Remove a possible values from the row. Modifies input sudokuTable.
-- if exceptTable then don't remove it from exceptTable[cell#] = true
function sudoku.RemovePossibleRow(sudokuTable, row, value, exceptTable)
exceptTable = exceptTable or {}
for col = 1, 9 do
local cell = sudoku.RowColToCell(row, col)
if (not exceptTable[cell]) and sudokuTable.possible[cell][value] then
sudokuTable.possible[cell][value] = nil
end
end
end
-- Remove a possible values from the col. Modifies input sudokuTable.
-- if exceptTable then don't remove it from exceptTable[cell#] = true
function sudoku.RemovePossibleCol(sudokuTable, col, value, exceptTable)
exceptTable = exceptTable or {}
for row = 1, 9 do
local cell = sudoku.RowColToCell(row, col)
if (not exceptTable[cell]) and sudokuTable.possible[cell][value] then
sudokuTable.possible[cell][value] = nil
end
end
end
-- Remove a possible values from the block. Modifies input sudokuTable.
-- if exceptTable then don't remove it from exceptTable[cell#] = true
function sudoku.RemovePossibleBlock(sudokuTable, block, value, exceptTable)
exceptTable = exceptTable or {}
local block_cell = sudoku.BlockToCell(block)
for n = 1, 9 do
local cell = n + block_cell + sudoku.LinearBlockCellTable[n]
if (not exceptTable[cell]) and sudokuTable.possible[cell][value] then
sudokuTable.possible[cell][value] = nil
end
end
end
-- Get the count of all possible values for rows, cols, and blocks
-- returns 3 tables row_possible[row#][value] = #times possible value occurs in row
-- and the same for col_possible, block_possible
-- if no possible values (all values set) then row_possible[row#] = nil
function sudoku.FindPossibleCountRowColBlock(sudokuTable)
local row_possible = {}
local col_possible = {}
local block_possible = {}
for cell = 1, 81 do
local row, col = sudoku.CellToRowCol(cell)
local block = sudoku.CellToBlock(cell)
local cell_possible = sudoku.GetCellPossible(sudokuTable, cell)
for pvalue, is_possible in pairs(cell_possible) do
if not row_possible[row] then row_possible[row] = {} end
if not col_possible[col] then col_possible[col] = {} end
if not block_possible[block] then block_possible[block] = {} end
row_possible[row][pvalue] = (row_possible[row][pvalue] or 0) + 1
col_possible[col][pvalue] = (col_possible[col][pvalue] or 0) + 1
block_possible[block][pvalue] = (block_possible[block][pvalue] or 0) + 1
end
end
return row_possible, col_possible, block_possible
end
-- Find all the possible values for row, col cell
-- returns a table of possible[value] = true
function sudoku.FindPossibleCell(sudokuTable, row, col)
local possible = {}
-- gather up all the set values in row, col, and block
local rowValues = sudokuTable.row_values[row]
local colValues = sudokuTable.col_values[col]
local blockValues = sudokuTable.block_values[sudoku.RowColToBlock(row, col)]
-- remove the set values from the possible values
for v = 1, 9 do
if (rowValues[v] == nil) and (colValues[v] == nil) and (blockValues[v] == nil) then
possible[v] = v
end
end
return possible
end
-- Find all the possible values for the whole table by filling out the
-- possible table in the input sudokuTable. Modifies input sudokuTable.
function sudoku.CalcAllPossible(sudokuTable)
for cell = 1, 81 do
local row, col = sudoku.CellToRowCol(cell)
local possible = {}
if not sudoku.HasCellValue(sudokuTable, cell) then
local block = sudoku.CellToBlock(cell)
for v = 1, 9 do
if (sudokuTable.row_values[row][v] == nil) and
(sudokuTable.col_values[col][v] == nil) and
(sudokuTable.block_values[block][v] == nil) then
possible[v] = v
end
end
end
sudoku.SetCellPossible(sudokuTable, cell, possible)
end
-- this function checks flags to see if it should run
sudoku.RemovePossibleGroups(sudokuTable)
end
-- Find all the possible pairs, triplets, quads in the table
-- must run CalcAllPossible first, does not eliminate any.
-- returns 3 tables, possible_pairs.rows[row#][key] = { cell1, cell2... },
-- possible_pairs.cols[col#][key] = { cell1, cell2... },
-- possible_pairs.blocks[block#][key] = { cell1, cell2... },
-- and the same for possible_triplets, possible_quads
-- key is constructed from the number group as string.char(val1, val2...)
sudoku.FindAllPossibleGroups_Cache = {}
function sudoku.FindAllPossibleGroups(sudokuTable)
local possible_pairs = {rows = {}, cols = {}, blocks = {}}
local possible_triplets = {rows = {}, cols = {}, blocks = {}}
local possible_quads = {rows = {}, cols = {}, blocks = {}}
local char0 = string.byte("0")
local cache_key_flags = 1*booltoint(sudokuTable.flags[sudoku.ELIMINATE_HIDDEN_PAIRS]) +
2*booltoint(sudokuTable.flags[sudoku.ELIMINATE_HIDDEN_TRIPLETS]) +
4*booltoint(sudokuTable.flags[sudoku.ELIMINATE_HIDDEN_QUADS])
local cache_keys = { 10^1, 10^2, 10^3, 10^4, 10^5, 10^6, 10^7, 10^8, 10^9 }
local function add_possible(atable, rcb_key, key, cell)
local a = atable[rcb_key]
if not a then
atable[rcb_key] = { [key] = {cell} }
elseif not a[key] then
a[key] = {cell}
else
a[key][#a[key]+1] = cell
end
end
for cell = 1, 81 do
local row, col = sudoku.CellToRowCol(cell)
local block = sudoku.CellToBlock(cell)
local cell_possible = sudoku.GetCellPossible(sudokuTable, cell)
local cell_possible_table = {}
local cache_key = cache_key_flags
-- convert key, value table to indexed table and a key for the cache
local count = 0
for n = 1, 9 do
if cell_possible[n] then
cell_possible_table[#cell_possible_table+1] = char0+n
cache_key = cache_key + cache_keys[n]
count = count + 1
end
end
local possible_pairs_keys = {}
local possible_triplets_keys = {}
local possible_quads_keys = {}
-- either use the cached key table or create a new key table for the possible
-- Note: cache cuts time for 100 calls to this fn w/ empty puzzle from 8 to 1 sec
if (count > 1) and sudoku.FindAllPossibleGroups_Cache[cache_key] then
possible_pairs_keys = sudoku.FindAllPossibleGroups_Cache[cache_key].possible_pairs
possible_triplets_keys = sudoku.FindAllPossibleGroups_Cache[cache_key].possible_triplets
possible_quads_keys = sudoku.FindAllPossibleGroups_Cache[cache_key].possible_quads
elseif (count > 1) then
local elim_pairs = (count == 2) or sudokuTable.flags[sudoku.ELIMINATE_HIDDEN_PAIRS]
local elim_triplets = (count == 3) or sudokuTable.flags[sudoku.ELIMINATE_HIDDEN_TRIPLETS]
local elim_quads = (count == 4) or sudokuTable.flags[sudoku.ELIMINATE_HIDDEN_QUADS]
for i = 1, count do
for j = i+1, count do
local pkey = string.char(cell_possible_table[i], cell_possible_table[j])
if elim_pairs then
possible_pairs_keys[#possible_pairs_keys+1] = pkey
end
for k = j+1, count do
local tkey = pkey..string.char(cell_possible_table[k])
if elim_triplets then
possible_triplets_keys[#possible_triplets_keys+1] = tkey
end
if elim_quads then
for l = k+1, count do
local qkey = tkey..string.char(cell_possible_table[l])
possible_quads_keys[#possible_quads_keys+1] = qkey
end
end
end
end
end
sudoku.FindAllPossibleGroups_Cache[cache_key] = {}
sudoku.FindAllPossibleGroups_Cache[cache_key].possible_pairs = possible_pairs_keys
sudoku.FindAllPossibleGroups_Cache[cache_key].possible_triplets = possible_triplets_keys
sudoku.FindAllPossibleGroups_Cache[cache_key].possible_quads = possible_quads_keys
end
for k, key in pairs(possible_pairs_keys) do
add_possible(possible_pairs.rows, row, key, cell)
add_possible(possible_pairs.cols, col, key, cell)
add_possible(possible_pairs.blocks, block, key, cell)
end
for k, key in pairs(possible_triplets_keys) do
add_possible(possible_triplets.rows, row, key, cell)
add_possible(possible_triplets.cols, col, key, cell)
add_possible(possible_triplets.blocks, block, key, cell)
end
for k, key in pairs(possible_quads_keys) do
add_possible(possible_quads.rows, row, key, cell)
add_possible(possible_quads.cols, col, key, cell)
add_possible(possible_quads.blocks, block, key, cell)
end
end
return possible_pairs, possible_triplets, possible_quads
end
-- Find all the naked and hidden pairs, triplets, quads in the table
-- must run CalcAllPossible first, does not eliminate any.
-- returns 2 tables, naked.rows[row#][key] = { cell1, cell2... },
-- naked.cols[col#][key] = { cell1, cell2... },
-- naked.blocks[block#][key] = { cell1, cell2... },
-- and the same for hidden
-- key is constructed from the number group as string.char(val1, val2...)
function sudoku.FindAllNakedHiddenGroups(sudokuTable, find_all)
local flags = sudokuTable.flags
if find_all == true then
sudokuTable.flags = TableCopy(flags) -- unref the table
-- turn all ELIMINATE_XXX on
for n = sudoku.ELIMINATE_FLAG_MIN, sudoku.ELIMINATE_FLAG_MAX do
sudokuTable.flags[n] = true
end
end
local row_possible, col_possible, block_possible = sudoku.FindPossibleCountRowColBlock(sudokuTable)
local possible_pairs, possible_triplets, possible_quads = sudoku.FindAllPossibleGroups(sudokuTable)
local char0 = string.byte("0")
local all_groups = { [2] = 36, [3] = 84, [4] = 126 } -- eg. 9!/(2! * (9-2)!)
if find_all == true then
sudokuTable.flags = flags -- put the flags back to how they were
end
local naked =
{
pairs = {rows = {}, cols = {}, blocks = {}, cells = {}},
triplets = {rows = {}, cols = {}, blocks = {}, cells = {}},
quads = {rows = {}, cols = {}, blocks = {}, cells = {}}
}
local hidden =
{
pairs = {rows = {}, cols = {}, blocks = {}, cells = {}},
triplets = {rows = {}, cols = {}, blocks = {}, cells = {}},
quads = {rows = {}, cols = {}, blocks = {}, cells = {}}
}
-- cache all the cell possible value counts
local cell_possible_count = {}
for n = 1, 81 do
cell_possible_count[n] = TableCount(sudoku.GetCellPossible(sudokuTable, n) or {})
end
local function dofind(rcb_table, num, key, cell_table_, rcb, rcb_possible)
local naked_cell_table = {}
local naked_cell_count = 0
local hidden_cell_table = {}
local hidden_cell_count = 0
local is_hidden = true
-- can only be exactly as many nums in key as in rcb for hidden
for n = 1, num do
if rcb_possible[string.byte(key, n)-char0] ~= num then
is_hidden = false
break
end
end
for n, cell in ipairs(cell_table_) do
if cell_possible_count[cell] == num then
naked_cell_table[#naked_cell_table+1] = cell
naked_cell_count = naked_cell_count + 1
end
if is_hidden then
hidden_cell_table[#hidden_cell_table+1] = cell
hidden_cell_count = hidden_cell_count + 1
end
end
-- has to be at least the same cell_count as num, if more then error, but...
if (naked_cell_count >= num) then
if not rcb_table.naked_table[rcb] then rcb_table.naked_table[rcb] = {} end
rcb_table.naked_table[rcb][key] = naked_cell_table
local cell_table = rcb_table.naked_table_base.cells
for n, cell in pairs(naked_cell_table) do
if not cell_table[cell] then cell_table[cell] = {} end
table.insert(cell_table[cell], key)
end
end
-- has to be at least the same cell_count as num, if more then error, but...
if is_hidden and (hidden_cell_count >= num) then
if not rcb_table.hidden_table[rcb] then rcb_table.hidden_table[rcb] = {} end
rcb_table.hidden_table[rcb][key] = hidden_cell_table
local cell_table = rcb_table.hidden_table_base.cells
for n, cell in pairs(hidden_cell_table) do
if not cell_table[cell] then cell_table[cell] = {} end
table.insert(cell_table[cell], key)
end
end
end
local function find(naked_table, hidden_table, possible_table, num)
local rcb_table = {}
rcb_table.naked_table_base = naked_table
rcb_table.hidden_table_base = hidden_table
rcb_table.naked_table = naked_table.rows
rcb_table.hidden_table = hidden_table.rows
for row, key_table in pairs(possible_table.rows) do
for key, cell_table in pairs(key_table) do
dofind(rcb_table, num, key, cell_table, row, row_possible[row])
end
end