移动一根火柴使等式成立js版本

时间:2021-09-10 08:11:19

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="javascript">
function getNum(i){
if (i>1){
return i*getNum(i-1);
}else{
return 1;
}
}
//console.log(getNum(3));

 

 

/**
* 数字1加一根成为7
* 数字2变动一根成为3
* 3减少一个称为2,不变称为5,增加一根可为9
* 4独立
* 5变动可成3,增加可成6、9.
* 6减少可得5,不变可得9,增加可得8.
* 7减少可得1.
* 8减少可得6、9。
*/
function changeNum(data){
return data.length;
}

function compute(){
var rules = data;
var form = document.getElementById("origin").value;

var nums = form.split('=');
var temp = "";
var tempStr = "";
var flag = false; //是否有匹配
var compareFlag = ["add","sub"]; //add:true;sub:false

if (nums[0].indexOf("+") >= 0){
right = nums[1];
left = nums[0].split("+");
opr = "+";
}else{
right = nums[1];
left = nums[0].split("-");
opr = "-";
}

//left[0]是左边第一个数
for (var j=0; j<form.length; j++){
for (var i=0; i<rules.length; i++){
if (form[j] == rules[i].a){
if (rules[i].m == "mv"){
for(var x=0; x<rules[i].b.length; x++){
temp = form;
temp = changeStr(temp, j, rules[i].b[x]);
if (eval(temp.split("=")[0]) == eval(temp.split("=")[1])){
console.log(temp.split("=")[0] + "=" + temp.split("=")[1]);
flag = true;
}
}
}else if (rules[i].m == "add"){
for(var x=0; x<rules[i].b.length; x++){ //第j个数,遍历+
temp = form;
temp = changeStr(temp, j, rules[i].b[x]);
for(var k=0; k<form.length; k++){ //第k个数,遍历-
if(k!=j){
for (var h=0; h<rules.length; h++){
if (rules[h].m == "sub" && form[k] == rules[h].a){
tempStr = temp; //状态保持
for(var y=0; y<rules[h].b.length; y++){
temp = changeStr(temp, k, rules[h].b[y]);

if (eval(temp.split("=")[0]) == eval(temp.split("=")[1])){
console.log(temp.split("=")[0] + "=" + temp.split("=")[1]);
flag = true;
}else{
temp = tempStr; //不能匹配,恢复状态
}
}
}
}
}
}
}
}
}
}
}
if (!flag){
console.log("没有匹配的答案");
}
}


function changeStr(ori,index,fin){
var str = ori.substr(0, index) + fin + ori.substring(index+1, ori.length);
return str;
}


var data = [];

data.push({a:0,b:[8],m:"add"});
data.push({a:0,b:[6,9],m:"mv"});
data.push({a:1,b:[7],m:"add"});
data.push({a:2,b:[3],m:"mv"});
data.push({a:3,b:[5],m:"mv"});
data.push({a:3,b:[9],m:"add"});
data.push({a:5,b:[6,9],m:"add"});
data.push({a:6,b:[5],m:"sub"});
data.push({a:6,b:[9],m:"mv"});
data.push({a:6,b:[8],m:"add"});
data.push({a:7,b:[1],m:"sub"});
data.push({a:8,b:[6,9],m:"sub"});
data.push({a:8,b:[0],m:"sub"});
data.push({a:9,b:[0,6],m:"mv"});
data.push({a:9,b:[3,5],m:"sub"});
data.push({a:9,b:[8],m:"add"});
data.push({a:"+",b:["-"],m:"sub"});
data.push({a:"-",b:["+","="],m:"add"});
data.push({a:"=",b:["-"],m:"sub"});

 

</script>
</head>
<body>
<input id="origin" />
<input type="button" value="计算" onclick="compute()" />
</body>
</html>