码迷,mamicode.com
首页 > 编程语言 > 详细

算法-wordpuzzle

时间:2016-04-09 19:05:28      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

哈哈哈哈哈哈哈,今天调了大半天的代码,终于通过啦。

这个是一个找单词的算法,用了一种最基础,最直观的算法解决了。

思路很简单,先找到每个点,再把每个点的8个方向存在的字符传读出来,分别计算可能的字符串序列,再堆栈。最后这个栈loop去word里面找元素。

不过效率很低,用了很多loop



/*
* word puzzle problem
*
* we have this,fat,two,that in two-dimensional array with 4*4,find them out
* */

/*
* method 1
*
* */
var arr=[[‘t‘,‘h‘,‘i‘,‘s‘],[‘w‘,‘a‘,‘t‘,‘s‘],[‘o‘,‘a‘,‘h‘,‘g‘],[‘f‘,‘g‘,‘d‘,‘t‘]];
var result=[];
var word=["this","fat","two","that"];
function method(arr){
var len=arr.length;
for(var i=0;i<4;i++){
for(var j=0;j<4;j++){
var stack=[];
stack=tostr(arr,i,j);

for(var m=0;m<stack.length;m++){
if(word.indexOf(stack[m])!=-1){
result.push(stack[m]);
}
}
}
}
return result;
}


function possiblestr(str){
var len=str.length;
var stack=[];
for(var i=1;i<len;i++){
stack.push(str.substring(0,i+1));
}
return stack;
}

function tostr(arr,a,b){
var tempstr=‘‘;
var tempstack=[];
var result=[];
//to right
for(var i=b;i<4;i++){
tempstr+=arr[a][i];
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to left
for(var i=b;i>=0;i--){
tempstr+=arr[a][i]
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to up
for(var i=a;i>=0;i--){
tempstr+=arr[i][b];
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to bottom
for(var i=a;i<4;i++){
tempstr+=arr[i][b];

}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to right top
for(var i= a,j=b;j<4&&i>=0&&j>=0;i--,j++){
tempstr+=arr[i][j];
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to right down
for(var i= a,j=b;i<4&&i>=0&&j>=0;i++,j++){
tempstr+=arr[i][j];
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to left top
for(var i= a,j=b;j>=0&&i>=0&&j>=0;i--,j--){
tempstr+=arr[i][j];
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
tempstr=‘‘;
//to left down
for(var i= a,j=b;i<4&&i>=0&&j>=0;i++,j--){
tempstr+=arr[i][j];
}
if(tempstr.length>1){
tempstack=toarray(tempstr);
result=result.concat(tempstack);
}
return result;
}

//str to array one by one
function toarray(str){
var stack=[];
for(var i=2;i<=str.length;i++){
stack.push(str.substring(0,i));
}
return stack;
}

alert(method(arr));


 

算法-wordpuzzle

标签:

原文地址:http://www.cnblogs.com/wz0107/p/5372259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!