题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { // Write your code here const queue = (arr, len) => { let res = []; // 所有排列结果 let arrange = (tempArr, leftArr) => { // tempArr:排列好的元素 leftArr:待排列元素 if (tempArr.length === len) { // 这里就是递归结束的地方 res.push(tempArr.join("")); // 得到全排列的每个元素都是字符串 } else { leftArr.forEach((item, index) => { let temp = [].concat(leftArr); temp.splice(index, 1); // 第一个参数是当前分离出的元素所在数组;第二个参数temp是传入的leftArr去掉第一个后的结果 arrange(tempArr.concat(item), temp); // 这里使用了递归 }); } }; arrange([], arr); return res; }; const operations = [ "+", "+", "+", "-", "-", "-", "*", "*", "*", "/", "/", "/", ]; const operationQueue = queue(operations, 3); const trans = (a) => { switch (a) { case "A": return 1; case "J": return 11; case "Q": return 12; case "K": return 13; default: return parseInt(a); } }; const calculate = (a, b, operation) => { switch (operation) { case "+": return trans(a) + trans(b); case "-": return trans(a) - trans(b); case "*": return trans(a) * trans(b); case "/": return parseInt(trans(a) / trans(b)); } }; while ((line = await readline())) { let tokens = line.split(" "); if (tokens.some((item) => item === "joker" || item === "JOKER")) { console.log("ERROR"); } else { const cardsQueue = queue(tokens, 4); let isBreak = false; for (let cardsStr of cardsQueue) { for (let operationStr of operationQueue) { let res1 = calculate( cardsStr[0], cardsStr[1], operationStr[0] ); let res2 = calculate(res1, cardsStr[2], operationStr[1]); let res3 = calculate(res2, cardsStr[3], operationStr[2]); if (res3 === 24) { console.log( cardsStr[0].concat( operationStr[0], cardsStr[1], operationStr[1], cardsStr[2], operationStr[2], cardsStr[3] ) ); isBreak = true; break; } } if (isBreak) break; } if (!isBreak) console.log("NONE"); } } })();