题解 | #24点运算#
24点运算
http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
穷举主要就是排列组合问题 而排列组合主要就是全排列,这里用到了递归进行逐级的全排列 但是可重复的全排列没想好怎么写,暂时只能用了三层循环
var line
while (line = readline()){
var matchFlag = false
var params = line.split(" ")
//过滤大小王
if(params.includes("JOKER")||params.includes("joker")) {
print("ERROR")
break
}
//数据处理
params = params.map(item => {
switch(item) {
case "J":
return 11
case "Q":
return 12
case "K":
return 13
case "A":
return 1
default:
return parseInt(item)
}
})
//数字序列生成
var arrangeArr = allArrangement(params)
//运算符序列生成
var opt = ["+","-","*","/"]
var optArrangeArr = everyArrangement(["+","-","*","/"])
arrangeArr.forEach(digits => {
optArrangeArr.forEach(opts => {
var result = digits[0]
for(let i=0;i<3;i++) {
switch(opts[i]) {
case "+":
result += digits[i+1]
break
case "-":
result -= digits[i+1]
break
case "*":
result *= digits[i+1]
break
case "/":
result = (result - result % digits[i+1]) / digits[i+1]
break
}
}
if (result == 24 && !matchFlag) {
digits = digits.map(item => {
switch(item) {
case 11:
return "J"
case 12:
return "Q"
case 13:
return "K"
case 1:
return "A"
default:
return parseInt(item)
}
})
print(`${digits[0]}${opts[0]}${digits[1]}${opts[1]}${digits[2]}${opts[2]}${digits[3]}`)
matchFlag = true
}
})
})
if (!matchFlag) {
print("NONE")
}
}
//不重复全排列
function allArrangement(arr) {
if (arr.length == 1) return [[arr[0]]]
var result = []
arr.forEach((newItem,index) => {
var otherArr = arr.slice(0,index).concat(arr.slice(index+1))
allArrangement(otherArr).forEach(beforeItem => {
result.push(beforeItem.concat([newItem]))
})
})
return result
}
//可重复全排列
function everyArrangement(arr) {
var result = []
arr.forEach(item1 => {
arr.forEach(item2 => {
arr.forEach(item3 => {
result.push([item1,item2,item3])
})
})
})
return result
}