Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathCountDownProblem.java
More file actions
Latest commit
317 lines (276 loc) · 8.99 KB
/
Copy pathCountDownProblem.java
File metadata and controls
317 lines (276 loc) · 8.99 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
importjava.util.ArrayList;
importjava.util.List;
importjava.util.OptionalInt;
importjava.util.Set;
importjava.util.stream.Stream;
/*
* This program is Java port of the Haskell example at
* https://www.cs.nott.ac.uk/~pszgmh/pgp-countdown.hs
*
* The problem and the solution approaches are explained
* in Prof. Graham Hutton's youtube video at
* https://youtu.be/CiXDS3bBBUo?list=PLF1Z-APd9zK7usPMx3LGMZEHrECUGodd3
*
* This Java program requires JDK 21+
*/
classCountDownProblem {
// data Op = Add | Sub | Mul | Div
enumOp {
Add, Sub, Mul, Div;
// instance show Op
@Override
publicStringtoString() {
returnswitch (this) {
caseAdd -> "+";
caseSub -> "-";
caseMul -> "*";
caseDiv -> "/";
};
}
}
// cache enum value array
staticfinalOp[] operators = Op.values();
// valid' :: Op -> Int -> Int -> Bool
staticbooleanisValid(Opop, intx, inty) {
returnswitch (op) {
caseAdd -> x <= y;
caseSub -> x > y;
caseMul -> x != 1 && y != 1 && x <= y;
caseDiv -> y != 1 && x % y == 0;
};
}
// apply :: Op -> Int -> Int -> Int
staticintapply(Opop, intx, inty) {
returnswitch (op) {
caseAdd -> x + y;
caseSub -> x - y;
caseMul -> x * y;
caseDiv -> x / y;
};
}
// data Expr = Val Int | App Op Expr Expr
sealedinterfaceExpr {
// brak helper for instance Show Expr
staticStringbrak(Exprexpr) {
returnswitch (expr) {
// brak (Val n) = show n
caseVal(varn) -> Integer.toString(n);
// brak e = "(" ++ show e ++ ")"
default -> "(" + toStr(expr) + ")";
};
}
// instance Show Expr
staticStringtoStr(Exprexpr) {
returnswitch (expr) {
// show (Val n) = show n
caseVal(varn) -> Integer.toString(n);
// show (App o l r) = brak l ++ show o ++ brak r
// where
// brak (Val n) = show n
// brak e = "(" ++ show e ++ ")"
caseApp(varop, varl, varr) -> brak(l) + op + brak(r);
};
}
}
recordVal(intv) implementsExpr {
// instance Show Expr
@Override
publicStringtoString() {
returnExpr.toStr(this);
}
}
recordApp(Opop, Exprl, Exprr) implementsExpr {
// instance Show Expr
@Override
publicStringtoString() {
returnExpr.toStr(this);
}
}
// eval :: Expr -> [Int]
// Using OptionalInt instead of List<Integer>
staticOptionalInteval(Exprexpr) {
returnswitch (expr) {
// eval (Val n) = [n | n > 0]
caseVal(varn) -> n > 0 ? OptionalInt.of(n) : OptionalInt.empty();
// eval (App o l r) = [apply o x y | x <- eval l,
// y <- eval r,
// valid o x y]
caseApp(varop, varl, varr) -> {
varx = eval(l);
vary = eval(r);
yield (x.isPresent() && y.isPresent() &&
isValid(op, x.getAsInt(), y.getAsInt())) ?
OptionalInt.of(apply(op, x.getAsInt(), y.getAsInt())) :
OptionalInt.empty();
}
};
}
// type Result = (Expr,Int)
recordResult(Exprexpr, intvalue) {
@Override
publicStringtoString() {
returnexpr.toString() + " = " + value;
}
}
// combine'' :: Result -> Result -> [Result]
staticList<Result> combine(Resultlx, Resultry) {
// (l,x), (r,y) pattern
varl = lx.expr();
varx = lx.value();
varr = ry.expr();
vary = ry.value();
// combine'' (l,x) (r,y) = [(App o l r, apply o x y) | o <- ops, valid' o x y]
returnStream.of(operators).
filter(op -> isValid(op, x, y)).
map(op -> newResult(newApp(op, l, r), apply(op, x, y))).
toList();
}
// results' :: [Int] -> [Result]
staticList<Result> results(List<Integer> ns) {
// results' [] = []
if (ns.isEmpty()) {
returnList.of();
}
// results' [n] = [(Val n,n) | n > 0]
if (ns.size() == 1) {
varn = head(ns);
returnn > 0 ? List.of(newResult(newVal(n), n)) : List.of();
}
// results' ns = [res | (ls,rs) <- split ns,
// lx <- results' ls,
// ry <- results' rs,
// res <- combine'' lx ry]
varres = newArrayList<Result>();
// all possible non-empty splits of the input list
// split :: [a] -> [([a],[a])] equivalent for-loop
for (inti = 1; i < ns.size(); i++) {
varls = ns.subList(0, i);
varrs = ns.subList(i, ns.size());
varlxs = results(ls);
varrys = results(rs);
for (Resultlx : lxs) {
for (Resultry : rys) {
res.addAll(combine(lx, ry));
}
}
}
returnres;
}
// List utilities
// : operator
static <T> List<T> cons(Thead, List<T> tail) {
finalvartailLen = tail.size();
returnswitch (tailLen) {
case0 -> List.of(head);
case1 -> List.of(head, tail.get(0));
case2 -> List.of(head, tail.get(0), tail.get(1));
case3 -> List.of(head, tail.get(0), tail.get(1), tail.get(2));
default -> {
varres = newArrayList<T>(1 + tailLen);
res.add(head);
res.addAll(tail);
yield res;
}
};
}
static <T> Thead(List<T> list) {
returnlist.get(0);
}
static <T> List<T> tail(List<T> list) {
finalvarlen = list.size();
returnlen == 1 ? List.of() : list.subList(1, len);
}
// subs :: [a] -> [[a]]
staticList<List<Integer>> subs(List<Integer> ns) {
// subs [] = [[]]
if (ns.isEmpty()) {
returnList.of(List.of());
}
// subs (x:xs)
varx = head(ns);
varxs = tail(ns);
// where yss = sub(xs)
varyss = subs(xs);
// yss ++ map (x:) yss
varres = newArrayList<List<Integer>>();
res.addAll(yss);
yss.stream().
map(l -> cons(x, l)).
forEach(res::add);
returnres;
}
// interleave :: a -> [a] -> [[a]]
// Using Stream<List<Integer> instead of List<List<Integer>>
staticStream<List<Integer>> interleave(intx, List<Integer> ns) {
// interleave x [] = [[x]]
if (ns.isEmpty()) {
returnStream.of(List.of(x));
}
// interleave x (y:ys)
vary = head(ns);
varys = tail(ns);
// outer : translated as Stream.concat
// (x:y:ys) : map (y:) (interleave x ys)
returnStream.concat(
// x:y:ys == x:ns
Stream.of(cons(x, ns)),
// map (y:) (interleave x ys)
interleave(x, ys).map(l -> cons(y, l))
);
}
// perms :: [a] -> [[a]]
// Using Stream<List<Integer> instead of List<List<Integer>>
staticStream<List<Integer>> perms(List<Integer> ns) {
// perms [] = [[]]
if (ns.isEmpty()) {
returnStream.of(List.of());
}
// perms (x:xs)
varx = head(ns);
varxs = tail(ns);
// concat (map ...) is translated as flatMap
// concat (map (interleave x) (perms xs))
returnperms(xs).flatMap(l -> interleave(x, l));
}
// choices :: [a] -> [[a]]
// Using Stream<List<Integer> instead of List<List<Integer>>
staticStream<List<Integer>> choices(List<Integer> ns) {
// concat . map is translated as flatMap
// choices = concat . map perms . subs
returnsubs(ns).stream().flatMap(CountDownProblem::perms);
}
// solutions'' :: [Int] -> Int -> [Expr]
// Using Stream<Expr> instead of List<Expr>
staticStream<Expr> solutions(List<Integer> ns, intn) {
// solutions'' ns n = [e | ns' <- choices ns, (e,m) <- results' ns', m == n]
returnchoices(ns).
flatMap(choice -> results(choice).stream()).
filter(res -> res.value() == n).
map(Result::expr);
}
/*
* usage example:
*
* java CountDownProblem.java 1,3,7,10,25,50 765
*/
publicstaticvoidmain(String[] args) {
if (args.length != 2) {
System.err.println("usage: java CountDownProblem.java <comma-separated-values> <target>");
System.exit(1);
}
inttarget = Integer.parseInt(args[1]);
List<Integer> numbers = Stream.of(args[0].split(",")).map(Integer::parseInt).toList();
// uniqueness check
try {
Set.of(numbers.toArray());
} catch (IllegalArgumentExceptioniae) {
System.err.println(iae);
System.exit(2);
}
varstart = System.currentTimeMillis();
solutions(numbers, target).forEach(e -> {
System.out.println(e);
});
System.out.println("Time taken (ms): " + (System.currentTimeMillis() - start));
}
}