]> gitweb.factorcode.org Git - factor.git/blob - unmaintained/sudokus/sudokus.factor
tools.test: Make the flag public. Finish porting tester changes to fuzzer.
[factor.git] / unmaintained / sudokus / sudokus.factor
1 USING: accessors arrays combinators.short-circuit grouping kernel lists
2 lists.lazy locals math math.functions math.parser math.ranges
3 models.product monads random sequences sets ui ui.gadgets.controls
4 ui.gadgets.layout models.combinators ui.gadgets.alerts vectors fry
5 ui.gadgets.labels shuffle ;
6 IN: sudokus
7
8 : row ( index -- row ) 1 + 9 / ceiling ;
9 : col ( index -- col ) 9 mod 1 + ;
10 : sq ( index -- square ) [ row ] [ col ] bi [ 3 / ceiling ] bi@ 2array ;
11 : near ( a pos -- ? ) { [ [ row ] same? ] [ [ col ] same? ] [ [ sq ] same? ] } 2|| ;
12 : nth-or-lower ( n seq -- elt ) [ length 1 - 2dup > [ nip ] [ drop ] if ] keep nth ;
13
14 :: solutions ( puzzle random? -- solutions )
15     f puzzle random? [ indices [ f ] [ random? swap nth-or-lower ] if-empty ] [ index ] if
16     [ :> pos
17       1 9 [a,b] 80 <iota> [ pos near ] filter [ puzzle nth ] map prune diff
18       [ 1array puzzle pos cut-slice rest surround ] map >list [ random? solutions ] bind
19     ] [ puzzle list-monad return ] if* ;
20
21 : solution ( puzzle random? -- solution ) dupd solutions dup +nil+ = [ drop "Unsolvable" alert* ] [ nip car ] if ;
22 : hint ( puzzle -- puzzle' ) [ [ f swap indices random dup ] [ f solution ] bi nth ] keep swapd >vector [ set-nth ] keep ;
23 : create ( difficulty -- puzzle ) 81 [ f ] replicate
24     40 random solution [ [ f swap [ length random ] keep set-nth ] curry times ] keep ;
25
26 : do-sudoku ( -- ) [ [
27         [
28             81 [ "" ] replicate <basic> switch-models [ [ <basic> ] map 9 group [ 3 group ] map 3 group
29                [ [ [ <spacer> [ [ <model-field> ->% 2 [ string>number ] fmap ]
30                     map <spacer> ] map concat ] <hbox> , ] map concat <spacer> ] map concat <product>
31                [ "Difficulty:" <label> , "1" <basic> <model-field> -> [ string>number 1 or 1 + 10 * ] fmap
32                "Generate" <model-border-btn> -> updates [ create ] fmap <spacer>
33                "Hint" <model-border-btn> -> "Solve" <model-border-btn> -> ] <hbox> ,
34                roll [ swap updates ] curry bi@
35                [ [ hint ] fmap ] [ [ f solution ] fmap ] bi* 3array merge [ [ [ number>string ] [ "" ] if* ] map ] fmap
36            ] bind
37         ] with-self , ] <vbox> { 280 220 } >>pref-dim
38     "Sudoku Sleuth" open-window ] with-ui ;
39
40 MAIN: do-sudoku