-
Notifications
You must be signed in to change notification settings - Fork 12
/
search.go
101 lines (90 loc) · 1.87 KB
/
search.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
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
package main
// SearchPlacement finds a transformed version of each
// digit such that all of the digits fit on the board at
// once.
func SearchPlacement(fixed, digits []Digit, boardSize int) []Digit {
freeSegs := (boardSize + 1) * boardSize * 2
for _, ds := range [][]Digit{fixed, digits} {
for _, d := range ds {
freeSegs -= len(d)
}
}
if freeSegs < 0 {
panic("too many segments for board size")
}
state := newBoardState(boardSize)
for _, d := range fixed {
state.Add(d)
}
digitCopy := make([]Digit, len(digits))
for i, d := range digits {
digitCopy[i] = d.Copy()
}
if searchRecursively(digitCopy, state) {
return digitCopy
}
return nil
}
func searchRecursively(digits []Digit, state *boardState) bool {
if len(digits) == 0 {
return true
}
digit := digits[0]
remaining := digits[1:]
for i := 0; i < 4; i++ {
for x := 0; x <= state.Size(); x++ {
for y := 0; y <= state.Size(); y++ {
if state.CanAdd(digit) {
state.Add(digit)
if searchRecursively(remaining, state) {
return true
}
state.Remove(digit)
}
digit.Translate(Location{0, 1})
}
digit.Translate(Location{1, -(state.Size() + 1)})
}
// Automatically brings it back to the corner.
digit.Rotate()
}
return false
}
type boardState struct {
filled map[Segment]bool
size int
}
func newBoardState(size int) *boardState {
return &boardState{
filled: map[Segment]bool{},
size: size,
}
}
func (b *boardState) Size() int {
return b.size
}
func (b *boardState) CanAdd(d Digit) bool {
for _, s := range d {
for _, l := range s {
for _, c := range l {
if c < 0 || c > b.size {
return false
}
}
}
if b.filled[s] {
return false
}
}
return true
}
func (b *boardState) Add(d Digit) {
for _, s := range d {
b.filled[s] = true
}
}
func (b *boardState) Remove(d Digit) {
for _, s := range d {
b.filled[s] = false
}
}