-
Notifications
You must be signed in to change notification settings - Fork 0
/
digits.go
244 lines (220 loc) · 4.98 KB
/
digits.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
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
package qordle
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
set "github.com/deckarep/golang-set/v2"
"github.com/oleiade/lane/v2"
"github.com/urfave/cli/v2"
)
type Operator int
const (
OpAdd Operator = 0
OpMultiply Operator = 1
OpSubtract Operator = 2
OpDivide Operator = 3
)
func (o Operator) String() string {
var sign string
switch o {
case OpAdd:
sign = "+"
case OpSubtract:
sign = "-"
case OpMultiply:
sign = "*"
case OpDivide:
sign = "/"
}
return sign
}
func (o Operator) apply(lhs, rhs int) (int, bool) {
var ok bool
var val int
switch o {
case OpAdd:
val, ok = lhs+rhs, true
case OpSubtract:
val, ok = lhs-rhs, lhs >= rhs
case OpMultiply:
val, ok = lhs*rhs, true
case OpDivide:
ok = rhs > 0 && lhs%rhs == 0
if ok {
val = lhs / rhs
}
}
return val, ok
}
type Board []int
type Operation struct {
Op Operator `json:"op"`
LHS int `json:"lhs"`
RHS int `json:"rhs"`
Val int `json:"val"`
}
func (o Operation) String() string {
return fmt.Sprintf("%d %s %d = %d", o.LHS, o.Op, o.RHS, o.Val)
}
type Operations []Operation
func (o Operations) String() string {
res := make([]string, len(o))
for i, x := range o {
res[i] = x.String()
}
return strings.Join(res, ", ")
}
func (o Operations) Hash() string {
res := make([]string, len(o))
for i, x := range o {
res[i] = x.String()
}
sort.Slice(res, func(i, j int) bool { return res[i] < res[j] })
return strings.Join(res, "; ")
}
type Candidate struct {
Board Board `json:"board"`
Ops Operations `json:"ops"`
}
type Digits struct{}
func (d Digits) operations(
board Board, operations Operations, target int) ([]Candidate, []Candidate) {
if len(board) == 1 {
return nil, nil
}
seen := set.NewThreadUnsafeSet(board...)
operators := []Operator{OpAdd, OpMultiply, OpSubtract, OpDivide}
var solutions, candidates []Candidate
for i := 0; i < len(board); i++ {
for j := i + 1; j < len(board); j++ {
lhs, rhs := board[i], board[j]
if lhs < rhs {
lhs, rhs = rhs, lhs
}
for _, operator := range operators {
val, ok := operator.apply(lhs, rhs)
switch {
case !ok:
continue
case seen.Contains(val):
continue
default:
seen.Add(val)
operation := Operation{
Op: operator, LHS: lhs, RHS: rhs, Val: val,
}
candidate := Candidate{
Board: make(Board, 0, len(board)-1),
Ops: make(Operations, 0, len(operations)+1),
}
candidate.Ops = append(candidate.Ops, operations...)
candidate.Ops = append(candidate.Ops, operation)
candidate.Board = append(candidate.Board, board[0:i]...)
candidate.Board = append(candidate.Board, board[i+1:j]...)
candidate.Board = append(candidate.Board, board[j+1:]...)
candidate.Board = append(candidate.Board, operation.Val)
switch {
case operation.Val == target:
solutions = append(solutions, candidate)
default:
candidates = append(candidates, candidate)
}
}
}
}
}
return solutions, candidates
}
func (d Digits) Play(ctx context.Context, board Board, target int) <-chan Candidate {
c := make(chan Candidate)
go func() {
defer close(c)
seen := set.NewSet[string]()
queue := lane.NewPriorityQueue[Candidate](lane.Minimum[int])
queue.Push(Candidate{Board: board, Ops: nil}, 0)
for !queue.Empty() {
candidate, step, _ := queue.Pop()
if ctx.Err() != nil {
return
}
solutions, candidates := d.operations(candidate.Board, candidate.Ops, target)
for _, solution := range solutions {
q := solution.Ops.Hash()
if seen.Contains(q) {
continue
}
select {
case <-ctx.Done():
return
case c <- solution:
seen.Add(q)
}
}
for _, candidate := range candidates {
queue.Push(candidate, step+1)
}
}
}()
return c
}
func digits(c *cli.Context) error {
var board Board
var digits Digits
for i := 0; i < c.NArg(); i++ {
val, err := strconv.Atoi(c.Args().Get(i))
if err != nil {
return fmt.Errorf("failed to convert '%s'", c.Args().Get(i))
}
board = append(board, val)
}
ctx, cancel := context.WithCancel(c.Context)
defer cancel()
enc := Runtime(c).Encoder
n, count, eq := 0, c.Int("count"), c.Bool("equation")
for candidate := range digits.Play(ctx, board, c.Int("target")) {
switch {
case eq:
fmt.Fprintln(c.App.Writer)
for _, op := range candidate.Ops {
fmt.Fprintln(c.App.Writer, op)
}
fmt.Fprintln(c.App.Writer)
default:
if err := enc.Encode(candidate); err != nil {
return err
}
}
n++
if count > 0 && n == count {
return nil
}
}
return nil
}
func CommandDigits() *cli.Command {
return &cli.Command{
Name: "digits",
Category: "puzzles",
Usage: "Play digits automatically",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "target",
Aliases: []string{"t"},
Value: 0,
},
&cli.IntFlag{
Name: "count",
Aliases: []string{"N"},
Value: 0,
},
&cli.BoolFlag{
Name: "equation",
Aliases: []string{"e"},
Value: false,
},
},
Action: digits,
}
}