# 递归方式穷举Google方程式（javascript实现）

### 定义数据结构

``````var charItem = [
{ c:'W', value:-1, leading:true},
{ c:'D', value:-1, leading:true},
{ c:'O', value:-1, leading:false},
{ c:'T', value:-1, leading:false},
{ c:'G', value:-1, leading:true},
{ c:'L', value:-1, leading:false},
{ c:'E', value:-1, leading:false},
{ c:'C', value:-1, leading:false},
{ c:'M', value:-1, leading:false}
];
var tagCharValue = [
{ used:false, value:0 },
{ used:false, value:1 },
{ used:false, value:2 },
{ used:false, value:3 },
{ used:false, value:4 },
{ used:false, value:5 },
{ used:false, value:6 },
{ used:false, value:7 },
{ used:false, value:8 },
{ used:false, value:9 }
];``````

### 回调函数（具体计算规则）

``````searchingResult(charItem,tagCharValue,0,function(ci){
var minuend = 'WWWDOT';
var subtrahend = 'GOOGLE';
var diff = 'DOTCOM';

var m = MakeIntegerValue(ci, minuend);
var s = MakeIntegerValue(ci, subtrahend);
var d = MakeIntegerValue(ci, diff);

if(m - s == d){
console.log(m + ' - ' + s + ' = ' + d);
}
})``````

### 字符串到整数的转换

``````function MakeIntegerValue(ci, str){
var rs = str.split('');
var outcome = 0;
rs.forEach(function(al){
for(var i=0; i<charItem.length; i++){
if(charItem[i].c == al){
outcome = outcome * 10 + charItem[i].value;
break;
}
}
})
return outcome;
}``````

### 有效性检测

``````function isValueValid(item, value){
if(item.leading){
return !value.used && value.value;
}else{
return !value.used;
}
}``````

### 搜索函数

``````function searchingResult(ci, cv, index, callback){
if(index == charItem.length){
callback(ci);
return;
}
for(var i=0; i<tagCharValue.length; i++){
if(isValueValid(ci[index], cv[i])){
cv[i].used = true;
ci[index].value = cv[i].value;
searchingResult(ci,cv,index + 1, callback);
cv[i].used = false;
}
}
}``````

### 输出结果

``````777589 - 188103 = 589486
777589 - 188106 = 589483``````

### 比较非递归方案

``````for(var w = 1; w <= 9; w++)
for(var d = 1; d <= 9; d++)
for(var o = 0; o <= 9; o++)
for(var t = 0; t <= 9; t++)
for(var g = 1; g <= 9; g++)
for(var l = 0; l <= 9; l++)
for(var e = 0; e <= 9; e++)
for(var c = 0; c <= 9; c++)
for(var m = 0; m <= 9; m++){
var tmp = {};
tmp[w]=1;
tmp[d]=1;
tmp[o]=1;
tmp[t]=1;
tmp[g]=1;
tmp[l]=1;
tmp[e]=1;
tmp[c]=1;
tmp[m]=1;
if(Object.keys(tmp).length == 9){
if(w*100000+w*10000+w*1000+d*100+o*10+t - g*100000-o*10000-o*1000-g*100-l*10-e == d*100000+o*10000+t*1000+c*100+o*10+m)
console.log(w.toString()+w.toString()+w.toString()+d.toString()+o.toString()+t.toString()+'-'+
g.toString()+o.toString()+o.toString()+g.toString()+l.toString()+e.toString()+'='+
d.toString()+o.toString()+t.toString()+c.toString()+o.toString()+m.toString());
}
}``````