我尝试制作单词搜索解算器。 因此,此工具的目的是计算给定单词在此项目中的网格a.k.a数组中出现的次数。但是当我制作一个垂直检查的代码时,我陷入了困境,它说“TypeError:无法读取未定义的属性'3'”
这是代码
var baris = [3];
var kolom = [8];
var kata = ["zpw"];
var puzzle= [
["z","x","x","r","r","r","f","z"],
["p","l","q","z","h","h","r","p"],
["w","o","l","p","p","o","o","w"]
];
var i;
var k;
var l;
var x;
var y;
var r=0;//left-right
var s=0;//right-left
var t=0;//up-down
var u=0;//down-up
var z=0;
var a=0;
var n=0;
var p=0;
function vertical() {
for (i=0;i<baris.length;i++) {
for(k=p;k<(baris[i]+baris[i-1] ||baris[i]);k++ ) {
for(l=0; l<kolom[i];l++) {
if(puzzle[k][l] == kata[i].charAt(0)) { //up-down CHECKER
for(y=1;y<kata[i].length ;y++) {
if(kata[i].charAt(y) == puzzle[k+y][l]) {
n=n+1;
console.log(n);
}
}
if(n==kata[i].length-1) {
t=t+1;
}
n=0;
}
}
//console.log(t);
}
t=0;
u=0;
p=p+baris[i];
}
}
vertical();`
希望你们能帮忙找到问题所在。非常感谢你。
答案 0 :(得分:0)
我猜你需要做的是制作一个“干净”的代码,只需考虑算法,写在纸上,在纸上画画,再思考,然后创建原型,然后重构,这样你就可以将算法分成自主隔离功能。作为奖励,您将获得更多的理解代码,这将是灵活的,真实的调试,随时可以改进和扩展。
如我所见,你需要的东西会:
这是仓促编写的代码,没有任何“傻瓜保护”,只能用于具有相同行大小的“谜题”,并且可能非常慢:
// Join a 2D array into a plain string.
function Join2DArray(array){
var val = ""
for(var i = 0; i < array.length; i++)
val += array[i].join("")
return val
}
// Check if substring exists at given position with given letters offset.
function IsSubstring(str, subStr, pos, inc){
var j = 0;
for(var i = pos; i < str.length, j < subStr.length; i += inc, j++)
if (str.charAt(i) != subStr.charAt(j)) return false
if (j < subStr.length) return false
return true
}
// Find all horizontal left->right and vertical up->down words.
function GetWordCount(array2D, word){
var rowCount = array2D.length
var rowSize = array2D[0].length
var string = Join2DArray(array2D)
var wordLen = word.length
var wordCount = 0;
// Search in rows
for(var j = 0; j < rowCount; j++)
for (var i = 0; i <= rowSize - wordLen; i++)
wordCount += IsSubstring(string, word, j * rowSize + i, 1)
// Search in columns
for(var i = 0; i < rowSize; i++)
for(var j = 0; j <= rowCount - wordLen; j++)
wordCount += IsSubstring(string, word, j * rowSize + i, rowSize)
return wordLen > 1 ? wordCount : wordCount / 2
}
var puzzle = [['H', 'E', 'L', 'L', 'O'],
['E', ' ', ' ', ' ', ' '],
['L', ' ', ' ', 'B', ' '],
['L', 'I', 'B', 'R', 'O'],
['O', ' ', ' ', 'O', ' ']]
console.log("HELLO: " + GetWordCount(puzzle, "HELLO")); // 2
console.log("BRO: " + GetWordCount(puzzle, "BRO")); // 2
console.log("LIBRO: " + GetWordCount(puzzle, "LIBRO")); // 1
console.log("O: " + GetWordCount(puzzle, "O")); // 4