-
Notifications
You must be signed in to change notification settings - Fork 0
/
zebra_puzzle wth_logs.go
74 lines (69 loc) · 1.63 KB
/
zebra_puzzle wth_logs.go
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
// +build uselogs
package zebra
import (
"log"
)
func recursiveBacktrackingWithLogs(assignment *[]uint8, csp *CSP) bool {
log.Println(*assignment)
printAssignment(csp.v)
if complete(csp.v) {
return true
}
idx := selectUnassigned(&csp.v, assignment, *csp)
log.Println("-", "Selecting variable at idx", idx)
domainValueLoop:
for _, d := range csp.d {
log.Println("--", "Selecting value", catElem(idx, d))
csp.v[idx] = d
for _, c := range csp.c {
log.Println("---", "Selecting constraint", c)
switch {
case !c.forApplicability()(csp.v...):
log.Println("----", "Constraint not applicable")
continue
case !c.forSatisfaction()(csp.v...):
log.Println("----", "Constraint not satisfied")
log.Println("--", "Discarding value", catElem(idx, d))
csp.v[idx] = 0
continue domainValueLoop
default:
log.Println("----", "Constraint ok")
}
}
log.Println("--", "Accepting value", catElem(idx, d), "at idx", idx)
copy(*assignment, csp.v)
outcome := recursiveBacktracking(assignment, csp)
if !outcome {
csp.v[idx] = 0
log.Println("--", "Discarding value", catElem(idx, d), "at idx", idx)
continue domainValueLoop
}
return true
}
return false
}
func printAssignment(assignment []uint8) {
grid := make([][]domainer, 5)
for i, v := range assignment {
grid[i%5] = append(grid[i%5], catElem(uint8(i), v))
}
log.Println(grid)
}
func catElem(idx, val uint8) domainer {
switch idx / 5 {
case 0:
return nationality(val)
case 1:
return color(val)
case 2:
return drink(val)
case 3:
return smoke(val)
case 4:
return pets(val)
case 5:
return number(val)
default:
return nil
}
}