[JS]24点游戏(两种解法)
最近遇到的⽐较有意思的题,是在24点游戏基础上有挑战级别的,先实现了个最笨的穷举法实现,24点游戏的话,常规解法就是通过降维去降低复杂度,通过读编程之美中的解法,以及结合⽹上的⼀些其他语⾔实现,实现了⼀版JS的。
题⽬:
A game I played when I was young: Draw 4 cards from playing cards, u + - * / and () to make the final
results equal to 24.
You will coding in function equalTo24. Function accept 4 parameters a b c d(4 numbers), value range is 1-100.
The result is a string such as "2223" ,(4+2)(5-1); If it is not possible to calculate the 24, plea return "It's not possible!"
All four cards are to be ud, only u three or two cards are incorrect; U a card twice or more is
incorrect too.
You just need to return one correct solution, don't need to find out all the possibilities.
The diffrent between "challenge version" and "simple version":
dismiss的意思
image.png
function equalTo24(arr) {
let answers = new Set();
let S = new Map();
let A = arr;
function run() {
for (var i = 0; i < (1 << 4); i++) {
let t = new Set();
S.t(i, t);
}
for (var i = 0; i < 4; i++) {
let n = new node(A[i], A[i] + "");
let t = new Set();
decentralizet.add(n);
S.t(1 << i, t);
}g7是什么意思
for (var i = 1; i < (1 << 4); i++) {
fork(i);
}
let mSet = S.get((1 << 4) - 1);
for (let v of mSet.values()) {
if (v.value == 24) {
answers.p);
}
ditch
}
if (answers.size == 0) {
console.log("It's no possible");
}
el {
for (let i of answers) {
console.log(i)
bbk}
}
}
function fork(m) {
着哩
var mSet = S.get(m);
if (mSet.size > 0)
return mSet;
el {
for (var x = 1; x < m; x++) {
if ((x & m) == x) {市东中学
let s1 = fork(x);
let s2 = fork(m - x);
for (let n1 of s1)
for (let n2 of s2) {
visin
var str = "(" + n1.exp + "+" + n2.exp + ")";
mSet.add(new node(n1.value + n2.value, str)); str = "(" + n1.exp + "-" + n2.exp + ")";
mSet.add(new node(n1.value - n2.value, str)); str = "(" + n2.exp + "-" + n1.exp + ")";
mSet.add(new node(n1.value - n2.value, str)); str = "(" + n1.exp + "*" + n2.exp + ")";
mSet.add(new node(n1.value * n2.value, str)); if (n1.value != 0) {
str = "(" + n2.exp + "/" + n1.exp + ")";
mSet.add(new node(n2.value / n1.value, str)); }
妙招大看台if (n2.value != 0) {
str = "(" + n1.exp + "/" + n2.exp + ")";
mSet.add(new node(n1.value / n2.value, str)); }
}
}
}
overwhelmedreturn mSet;
}
}
run()
}
var arr = [12,40,5,6];