-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumbers.mjs
More file actions
80 lines (70 loc) · 1.72 KB
/
numbers.mjs
File metadata and controls
80 lines (70 loc) · 1.72 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
const OPERATIONS = [
(a,b) => {
const result = a+b;
return {
result,
description: `${a}+${b}=${result}`,
}
},
(a,b) => {
const result = a-b;
return {
result,
description: `${a}-${b}=${result}`,
}
},
(a,b) => {
const result = a*b;
return {
result,
description: `${a}*${b}=${result}`,
}
},
(a,b) => {
const result = a%b === 0 ? a/b : null;
return {
result,
description: `${a}/${b}=${result}`,
}
},
];
let FOUND = false;
function dt(numbers, goal, steps = []) {
for (let i = 0; i < numbers.length && !FOUND; i++) {
const a = numbers[i];
for (let j = 0; j < numbers.length && !FOUND; j++) {
if (i === j) {
continue;
}
const b = numbers[j];
for (let k = 0; k < OPERATIONS.length && !FOUND; k++) {
const step = OPERATIONS[k](a,b);
if (step.result) {
const newSteps = steps.slice();
newSteps.push(step.description);
if (step.result === goal) {
FOUND = true;
console.log(`SOLUTION: ${newSteps}`);
break;
}
const resultNumbers = numbers.filter((numVal, numIndex) => numIndex !== i && numIndex !== j);
resultNumbers.push(step.result);
dt(resultNumbers, goal, newSteps);
}
}
}
}
}
const args = process.argv.slice(2);
const goal = Number.parseInt(args[0]);
const numbers = args.slice(1).map((x) => Number.parseInt(x))
console.log(goal);
console.log(numbers);
console.log(`n = ${numbers.length}`);
const t1 = performance.now();
dt(numbers, goal);
const t2 = performance.now();
if (!FOUND) {
console.log('no solution found');
}
console.log(`took ${t2-t1}ms`);