24点牌算法实现
最近陪孩子玩24点牌,很能训练孩子的数学心算,要是早知道这种玩法就好了,我又写了一个JS实现的算法,挺有意思的
var inputs = [4,5,6,7]; var numbers = [{value:inputs[0]},{value:inputs[1]},{value:inputs[2]},{value:inputs[3]}]; var samplesAB = [] // a,b for(var i=0;i<4;i++){ for(var j=0;j<4;j++){ var a = numbers[i]; var b = numbers[j]; if(a!=b){ samplesAB.push({a:a,b:b}) } } } var samplesABC = []; // a,b,c for(var i=0;i<samplesAB.length;i++){ for(var j=0;j<4;j++){ var ab = samplesAB[i]; var c = numbers[j]; if(ab.a!=c && ab.b != c){ samplesABC.push({...ab,c:c}) } } } var samples = []; // a,b,c for(var i=0;i<samplesABC.length;i++){ for(var j=0;j<4;j++){ var abc = samplesABC[i]; var d = numbers[j]; if(abc.a!=d && abc.b!=d && abc.c!=d){ samples.push({...abc,d:d}) } } } //+=*、 var sampleOp1 = []; for(var i =0;i<samples.length;i++){ var sample = samples[i]; sampleOp1.push({...sample,op1:"+"}); sampleOp1.push({...sample,op1:"-"}); sampleOp1.push({...sample,op1:"*"}); sampleOp1.push({...sample,op1:"/"}); } var sampleOp2 = []; for(var i =0;i<sampleOp1.length;i++){ var sample = sampleOp1[i]; sampleOp2.push({...sample,op2:"+"}); sampleOp2.push({...sample,op2:"-"}); sampleOp2.push({...sample,op2:"*"}); sampleOp2.push({...sample,op2:"/"}); } var sampleOp3 = []; for(var i =0;i<sampleOp2.length;i++){ var sample = sampleOp2[i]; sampleOp3.push({...sample,op3:"+"}); sampleOp3.push({...sample,op3:"-"}); sampleOp3.push({...sample,op3:"*"}); sampleOp3.push({...sample,op3:"/"}); } //操作符优先级 var expressions = []; for(var i =0;i<sampleOp3.length;i++){ var sample = sampleOp3[i]; var a = sample.a.value; var b = sample.b.value; var c = sample.c.value; var d = sample.d.value; var op1 = sample.op1; var op2 = sample.op2; var op3 = sample.op3; expressions.push(a + op1 + b + op2 + c + op3 + d); expressions.push("("+a + op1 + b +")" + op2 + c + op3 +d ); expressions.push(a + op1 +"("+ b + op2 + c+")" + op3+d); expressions.push(a + op1 + b + op2 +"("+ c + op3 + d+")"); expressions.push("("+a + op1 + b +")" + op2 +"("+ c + op3 + d+")"); // expressions.push("("+a + op1 + b + op2 + c+")" + op3 + d); expressions.push("(("+a + op1 + b+")" + op2 + c+")" + op3 + d); expressions.push("("+a + op1 +"("+ b + op2 + c+"))" + op3 + d); // expressions.push(a + op1 +"("+ b + op2 + c + op3 + d+")"); expressions.push(a + op1 +"(("+ b + op2 + c +")" + op3 + d+")"); expressions.push(a + op1 +"("+ b + op2 +"("+ c + op3 + d+"))"); } var index = 1000; for(var i=0;i<expressions.length;i++){ var expression = expressions[i]; var value = eval(expression); if(value==24){ console.log(index.toString().substr(1) +" : 24 = " +expression); index++; } }
作者 :秋时
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。