gpt4 book ai didi

javascript - 检查数组中匹配字母的算法(之前,之后,交叉)

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:21:59 28 4
gpt4 key购买 nike

我有一个这样的字母数组

var letters  = 
["Y", "X", "A",
"Y", "O", "H",
"A", "O", "O"];

我创建了一个循环来检查当前字母之前的字母和当前字母之后的字母是否相同。

for (var i = 0; i < letters.length; i++) {
var currentLetter = i;
var before = i - 1;
var after = i + 1;

if (letters[after] == letters[currentLetter]) {
console.log("Array Position " + currentLetter + ": " + letters[currentLetter] + ' matches after');
}
if (letters[before] == letters[currentLetter]) {
console.log("Array Position " + currentLetter + ": " + letters[currentLetter] + ' matches before');
}

我在如何正确检查字母是否相同的逻辑上遇到困难(显然没有交叉,因为它是一维的)。但是有没有我缺少的模式。如果不对每个 block 的算法进行硬编码,我将如何编写它?

示例:

letter[0] should check: letter[1], letter[3], letter[4]
letter[1] should check letter [0], [2], [3], [5] etc..

最佳答案

我为你写了这个 fiddle ,我相信它已经足够接近了,虽然它没有涵盖我猜想的所有奇怪的可能情况,但它足以让你使用:http://jsfiddle.net/0mja7zrr/4/

    var letters1  = 
["Y", "X", "A",
"Y", "O", "H",
"A", "O", "O"];

var letters2 =
["Y", "X", "A",
"Y", "Y", "H",
"A", "O", "Y"];

function checkAcross(index, rowLength, letters){
var indexInRow = index % rowLength;
var rowNum = Math.floor(index / rowLength);
var totalRows = Math.floor(letters.length/rowLength);
var letterToCheck = letters[index];
var delta = 0;
//checking
for(var i = 0; i < totalRows; i++){
delta = Math.abs(rowNum - i); //delta between rows and elements
var firstElementOfRow = rowLength * i; //get the index of first element
if(firstElementOfRow >= index){
if(letterToCheck != letters[firstElementOfRow + indexInRow + delta]){
return false;
}
}
else{
if(letterToCheck != letters[firstElementOfRow +indexInRow - delta]){
return false;
}
}
}
return true;
}

console.log(checkAcross(4,3,letters1));
console.log(checkAcross(4,3,letters2));

关于javascript - 检查数组中匹配字母的算法(之前,之后,交叉),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32670423/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com